import numpy as np
from mayavi.scripts import mayavi2
from tvtk.api import tvtk
 
class simplepolys(object):
 
        def __init__(self, heightmap):
            self.points = []
            self.polygons = []
            self.heightmap = heightmap
            self.mesh = None
 
        def createmesh(self):
            points = np.asarray(self.points)
            polygons = np.asarray(self.polygons)
            self.mesh = tvtk.PolyData(points=points, polys=polygons)
 
 
        def createpolys(self, size):
            '''
            Erzeugt Polygone und Punkte aus der gegebenen heightmap.
            '''
            heightmap = self.heightmap
            width = len(self.heightmap)
            for n, i in enumerate(heightmap):
                for k, j in enumerate(i):
                    self.points.append([n*size, j, k*size])
            polygons = [[x-1,x,x+width] for x,n in enumerate(self.points) if ((x % width) != 0) and ((x/width) < width-1)]
            polygons = polygons + [[x,x-1,x-1-width] for x,n in enumerate(self.points) if ((((x) % width) != 0) and (((x)//width) >= 1))]
            #for x, n in enumerate(self.points):
             #   print(x)
            self.polygons = polygons
 
@mayavi2.standalone
def view(mesh):
    '''Stellt ein tvtk.Polydata mesh im mayavi2 Standalone Client dar.'''
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.surface import Surface
 
    mayavi.new_scene()
    src = VTKDataSource(data=mesh)
    mayavi.add_source(src)
    s = Surface()
    mayavi.add_module(s)
 
if __name__ == '__main__':
    import perlin2D
 
    heightmap = []
    for i in range(500):
        inmap = []
        for j in range(500):
            inmap.append(perlin2D.Noise(i, j,0.03125, 0.5, 0.25))
        heightmap.append(inmap)
 
    a = simplepolys(heightmap)
    a.createpolys(0.05)
    print('FINISHED CALCULATING')
    a.createmesh()
    view(a.mesh)