def areas(self): """area of elements For surface element the faces' area is returned. For volume elements the sum of the faces'areas is returned. """ #In case of quadratic faces, the face's area should be #the area inside the polygon of face vertices or #the area of the equivalent linear face? ##this function would require some changes (here proposed inside the function as starting): ##create a _default_surfacetype to create quad8 instead of hex8 ?maybe also a _default_volumetype to create tet4 instead of quad4 ? def defaultSurfacetype(nplex): """Default face type for a surface mesh with given plexitude. For the most common cases of plexitudes, we define a default face type. The full list of default types can be found in mesh._default_facetype. """ return _default_surfacetype.get(nplex,None) import geomtools nfacperel= len(self.eltype.faces[1])#nfaces per elem mf=Mesh(self.coords, self.getFaces())#mesh of all faces mf.eltype = elementType(defaultSurfacetype(mf.nplex())) ntriperfac= mf.select([0]).convert('tri3').nelems()#how many tri per face elfacarea = geomtools.areaNormals( mf.convert('tri3').toFormex()[:])[0].reshape(self.nelems(), nfacperel*ntriperfac)#elems'faces'areas return elfacarea.sum(axis=1)#elems'areas
def readTetgen(fn): """Read and draw a tetgen file. This is an experimental function for the geometry import menu. """ res = {} base,ext = os.path.splitext(fn) if ext == '.node': nodes = readNodeFile(fn)[0] res['tetgen'+ext] = nodes elif ext in [ '.ele', '.face' ]: nodes,nodenrs = readNodeFile(utils.changeExt(fn,'.node'))[:2] if ext == '.ele': elems = readEleFile(fn)[0] elif ext == '.face': elems = readFaceFile(fn)[0] if nodenrs.min() == 1 and nodenrs.max()==nodenrs.size: elems = elems-1 M = Mesh(nodes,elems,eltype=elems.eltype) res['tetgen'+ext] = M elif ext == '.smesh': nodes,elems = readSmeshFile(fn) ML = [ Mesh(nodes,elems[e]) for e in elems ] res = dict([('Mesh-%s'%M.nplex(),M) for M in ML]) elif ext == '.poly': nodes,elems = readPolyFile(fn) ML = [ Mesh(nodes,elems[e]) for e in elems ] res = dict([('Mesh-%s'%M.nplex(),M) for M in ML]) return res
def readMesh(self,ncoords,nelems,nplex,props,eltype,normals,sep,objtype='Mesh'): """Read a Mesh from a pyFormex geometry file. The following arrays are read from the file: - a coordinate array with `ncoords` points, - a connectivity array with `nelems` elements of plexitude `nplex`, - if present, a property number array for `nelems` elements. Returns the Mesh constructed from these data, or a subclass if an objtype is specified. """ # Make sure to import the Mesh subclasses that can be read from plugins.trisurface import TriSurface ndim = 3 x = readArray(self.fil,Float,(ncoords,ndim),sep=sep) e = readArray(self.fil,Int,(nelems,nplex),sep=sep) if props: p = readArray(self.fil,Int,(nelems,),sep=sep) else: p = None M = Mesh(x,e,p,eltype) if objtype != 'Mesh': try: clas = locals()[objtype] except: clas = globals()[objtype] M = clas(M) if normals: n = readArray(self.fil,Float,(nelems,nplex,ndim),sep=sep) M.normals = n return M
def crop(self, x_0, x_1, y_0, y_1, with_normals=False): """ This function generates another mesh (not depthMesh) by cropping the organized set of veftices (a depth ROI) """ w, h = self.depth.shape[1], self.depth.shape[0] if x_0 < 0 or y_0 < 0 or x_1 >= w or y_1 >= h or x_1 <=x_0 or y_1 <= y_0: return None mesh = Mesh() vcs_aux = self.vcs.reshape(self.depth.shape[0], self.depth.shape[1], 3) # Vertices mesh.vcs = vcs_aux[y_0:y_1, x_0:x_1, :].reshape(-1, 3) mesh.vcs_q = mesh.vcs.shape[0] # Normals if with_normals: vnorms_aux = self.vnorms.reshape(self.depth.shape[0], self.depth.shape[1], 3) mesh.vnorms = vnorms_aux[y_0:y_1, x_0:x_1, :].reshape(-1, 3) # Facets mesh.faces = DepthMesh.genFacets(x_1 - x_0, y_1 - y_0) mesh.faces_q = mesh.faces.shape[0] # texture mapping txcoord_aux = self.txcoord.reshape(self.depth.shape[0], self.depth.shape[1], 2) mesh.txcoord = txcoord_aux[y_0:y_1, x_0:x_1, :].reshape(-1, 2) mesh.texture = self.texture mesh.txwidth, mesh.txheight = self.txwidth, self.txheight return mesh
def gen_mesh_from_voxels_mc(voxels, voxelsize, gmsh3d=False, scale_factor=0.25): import scipy.spatial as scsp tri = marching_cubes(voxels, voxelsize) nel, nnd, dim = tri.shape coors = tri.reshape((nel * nnd, dim)) tree = scsp.ckdtree.cKDTree(coors) eps = nm.max(coors.max(axis=0) - coors.min(axis=0)) *1e-6 dist, idx = tree.query(coors, k=24, distance_upper_bound=eps) uniq = set([]) for ii in idx: ukey = ii[ii < tree.n] ukey.sort() uniq.add(tuple(ukey)) ntri = nm.ones((nel * nnd,), dtype=nm.int32) nnod = len(uniq) ncoors = nm.zeros((nnod, 3), dtype=nm.float64) for ii, idxs in enumerate(uniq): ntri[nm.array(idxs)] = ii ncoors[ii] = coors[idxs[0]] mesh = Mesh.from_data('voxel_mc_data', ncoors, nm.ones((nnod,), dtype=nm.int32), {0: nm.ascontiguousarray(ntri.reshape((nel, nnd)))}, {0: nm.ones((nel,), dtype=nm.int32)}, {0: '%d_%d' % (2, 3)}) if gmsh3d: from vtk2stl import vtk2stl import tempfile import os auxfile = os.path.join(tempfile.gettempdir(), 'dicom2fem_aux') vtk_fn = auxfile + '_surfmc.vtk' stl_fn = auxfile + '_surfmc.stl' geo_fn = auxfile + '_surf2vol.geo' mesh_fn = auxfile + '_volmv.mesh' mesh.write(vtk_fn) vtk2stl(vtk_fn, stl_fn) geofile = open(geo_fn, 'wt') geofile.write(gmsh3d_geo.replace('__INFILE__', stl_fn).replace('__SCFACTOR__', str(scale_factor))) geofile.close() os.system('gmsh -3 -format mesh -o %s %s' % (mesh_fn, geo_fn)) mesh = Mesh.from_file(mesh_fn) return mesh
def createAnimatedModel(self, f11): wld = self.wld_container.wld_file_obj f10 = wld.getFragment(f11.fragRef) if f10.type != 0x10: print 'Model::createAnimatedModel() ERROR expected 0x10 fragment but got:', f10.type return # Lets initially try to only read all the mesh pieces and assemble the basic # model. Once that is working we can start looking into animation # Loop over the parts of the model/skeleton: the entries list in the f10 fragment # define these root_mesh = None for i in range(0, f10.size1): if i > 0: f2d = wld.getFragment(f10.entries[i][3]) # entry[3] -> fragRef2 # f2d.dump() f36 = wld.getFragment(f2d.fragRef) # f36.dump() m = Mesh(self.name+'_mesh_'+str(i)) m.buildFromFragment(f36, self.wld_container, False) m.root.reparentTo(root_mesh.root) else: # the root node (index 0) does not have a mesh m = Mesh(self.name+'_mesh_'+str(i)) # empty dummy mesh root_mesh = m self.meshes.append(m) # get model part orientation data from 0x10->0x13->0x12 ref chain f13 = wld.getFragment(f10.entries[i][2]) # entry[2] -> fragRef1 f12 = wld.getFragment(f13.fragRef) denom = float(f12.rotDenom) if denom != 0.0: rotx = f12.rotx/denom roty = f12.roty/denom rotz = f12.rotz/denom m.root.setHpr(rotx / 512.0 * 360.0, roty / 512.0 * 360.0, rotz / 512.0 * 360.0) denom = float(f12.shiftDenom) if denom != 0.0: shiftx = float(f12.shiftx)/denom shifty = float(f12.shifty)/denom shiftz = float(f12.shiftz)/denom # print shiftx, shifty, shiftz m.root.setPos(shiftx, shifty, shiftz) self.loaded = 1
def test_mesh(): '''Basic test of the Mesh factory method and mesh extending''' ox, dx, nx = 0., 10., 5 mesh = Mesh(type='uniform', ox=ox, lx=dx, nx=nx, block='B1') assert mesh.num_elem == nx assert mesh.boundary_nodes == [1, nx+1] assert np.allclose(mesh.boundary, [ox, dx]) # verify extending the mesh dxb, nb = 4., 2 mesh.extend(dxb, nb, block='B2') assert mesh.num_elem == nx + nb assert mesh.boundary_nodes == [1, nx+nb+1] assert np.allclose(mesh.boundary, [0., dx+dxb]) assert len(mesh.nodes) == len(mesh.vertices)
def load_ply(self, filename): Mesh.load_ply(self, filename) v_array=np.array(self.verts, dtype=np.float32) bbox=(np.min(v_array,0), np.max(v_array,0) ) self.v_array = v_array.astype(np.float32) self.bbox = bbox self.zoom=1.0/la.norm(bbox[1]) self.tri_array = np.array(self.tris, dtype=np.uint32) self.n_array = self.vert_props['normal'].astype(np.float32) logging.debug( 'done matrix {}'.format(self.zoom) ) return self.zoom
def save_state( self, filename, state=None, out=None, fill_value=None, post_process_hook=None, file_per_var=False, **kwargs ): extend = not file_per_var if (out is None) and (state is not None): out = self.state_to_output(state, fill_value=fill_value, extend=extend) if post_process_hook is not None: out = post_process_hook(out, self, state, extend=extend) float_format = get_default_attr(self.conf.options, "float_format", None) if file_per_var: import os.path as op meshes = {} for var in self.variables.iter_state(): rname = var.field.region.name if meshes.has_key(rname): mesh = meshes[rname] else: mesh = Mesh.from_region(var.field.region, self.domain.mesh, localize=True) meshes[rname] = mesh vout = {} for key, val in out.iteritems(): if val.var_name == var.name: vout[key] = val base, suffix = op.splitext(filename) mesh.write(base + "_" + var.name + suffix, io="auto", out=vout, float_format=float_format, **kwargs) else: self.domain.mesh.write(filename, io="auto", out=out, float_format=float_format, **kwargs)
def from_conf(conf, init_fields=True, init_variables=True, init_equations=True, init_solvers=True): mesh = Mesh.from_file(conf.filename_mesh) eldesc_dir = op.join(install_dir, "eldesc") domain = Domain.from_mesh(mesh, eldesc_dir) domain.setup_groups() domain.fix_element_orientation() domain.setup_neighbour_lists() obj = ProblemDefinition(conf=conf, domain=domain, eldesc_dir=eldesc_dir) # Default output file trunk and format. obj.ofn_trunk = io.get_trunk(conf.filename_mesh) obj.output_format = "vtk" obj.set_regions(conf.regions, conf.materials, conf.funmod) if init_fields: obj.set_fields(conf.fields) if init_variables: obj.set_variables(conf.variables) if init_equations: obj.set_equations(conf.equations) if init_solvers: obj.set_solvers(conf.solvers, conf.options) obj.ts = None return obj
def gen_mesh_from_voxels_mc(voxels, voxelsize): import scipy.spatial as scsp tri = marching_cubes(voxels, voxelsize) nel, nnd, dim = tri.shape coors = tri.reshape((nel * nnd, dim)) tree = scsp.ckdtree.cKDTree(coors) eps = nm.max(coors.max(axis=0) - coors.min(axis=0)) *1e-6 dist, idx = tree.query(coors, k=24, distance_upper_bound=eps) uniq = set([]) for ii in idx: ukey = ii[ii < tree.n] ukey.sort() uniq.add(tuple(ukey)) ntri = nm.ones((nel * nnd,), dtype=nm.int32) nnod = len(uniq) ncoors = nm.zeros((nnod, 3), dtype=nm.float64) for ii, idxs in enumerate(uniq): ntri[nm.array(idxs)] = ii ncoors[ii] = coors[idxs[0]] mesh = Mesh.from_data('voxel_mc_data', ncoors, nm.ones((nnod,), dtype=nm.int32), {0: nm.ascontiguousarray(ntri.reshape((nel, nnd)))}, {0: nm.ones((nel,), dtype=nm.int32)}, {0: '%d_%d' % (2, 3)}) return mesh
def __init__(self, heightfield): mesh = Mesh() size = 32 factor = 1.0 vertices = [] for z in xrange(size): z = float(z)/float(size-1) for x in xrange(size): x = float(x)/float(size-1) y = heightfield[x,z] vertices.append(mesh.vertex(x, y, z)) for y in xrange(size-1): for x in xrange(size-1): v0 = vertices[(x+1) + (y+1)*size] v1 = vertices[(x+1) + (y+0)*size] v2 = vertices[(x+0) + (y+0)*size] v3 = vertices[(x+0) + (y+1)*size] mesh.face(v0, v1, v2) mesh.face(v3, v0, v2) splits = Splits(mesh, heightfield) while len(mesh.verts) < 21840: #while len(mesh.verts) < 3000: print len(mesh.faces), len(mesh.verts) splits.perform() mesh.save('mesh.bin') self.vbo = mesh.serialize()
def draw( self ) : qm = tr.quaternion_matrix( self.Q[3:] ) if self.drawstate & MESH : glPushMatrix() glMultTransposeMatrixf( qm ) Mesh.draw( self ) glPopMatrix() if self.drawstate & WIREFRAME : glPushMatrix() glMultTransposeMatrixf( qm ) glDisable(GL_LIGHTING) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) Mesh.draw( self ) glBegin(GL_LINES) glVertex3f(0,0,0) glVertex3f( self.x[-1,0] , self.x[-1,1] , self.x[-1,2] ) glEnd() glEnable(GL_CULL_FACE) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glEnable(GL_LIGHTING) glPopMatrix() if self.drawstate & TRACE : glDisable(GL_LIGHTING) glBegin(GL_POINTS) for p in self.trace : glVertex3f( *p[:3] ) glEnd() glEnable(GL_LIGHTING) if self.drawstate & GRAVITY : glPushMatrix() glDisable(GL_LIGHTING) glTranslatef( 2 , 2 , 0 ) glScalef(.1,.1,.1) glMultTransposeMatrixf( qm ) glColor3f(1,.5,0) glBegin(GL_LINES) glVertex3f( 0 , 0 , 0 ) glVertex3f( *self.G ) glEnd() glEnable(GL_LIGHTING) glPopMatrix()
def test_linear_element(): '''Test the implementation of the linear element with simple integrals''' dx = 5. num_elem = 5 mesh = Mesh(type='uniform', ox=0., lx=dx, nx=num_elem) elem_num = 1 connect = mesh.connectivity(elem_num) vertices = mesh.coordinates(connect) elem = LinearElement(elem_num, connect, vertices) # --- test some integrals ex = lambda x: x ex2 = lambda x: x ** 2 # Integrate[phi] ans = elem.integrate() exact = integrate(N, (x, 0, 1)) assert areclose(ans, exact) # Integrate[dphi] ans = elem.integrate(derivative=True) exact = integrate(dN, (x, 0, 1)) assert areclose(ans, exact) # Integrate[x phi] ans = elem.integrate(ex) exact = integrate(x * N, (x, 0, 1)) assert areclose(ans, exact) # Integrate[x dphi] ans = elem.integrate(ex, derivative=True) exact = integrate(x * dN, (x, 0, 1)) assert areclose(ans, exact) # Integrate[x x phi] ans = elem.integrate(ex, ex) exact = integrate(x * x * N, (x, 0, 1)) assert areclose(ans, exact) # Integrate[x x dphi] ans = elem.integrate(ex,ex,derivative=True) exact = integrate(x*x*dN,(x,0,1)) assert areclose(ans, exact)
def __init__(self, parent, color=0xFF0000, x=0, y=0): Mesh.__init__(self) self.parent = parent self.position.x = x self.position.y = y #self.matrix.translate(x, y, 0.0) self.color = color r, g, b = self.toRgb(self.color) v = [ 0.0, 0.0, r, g, b, 0.0 + BLOCK_SIZE, 0.0, r, g, b, 0.0 + BLOCK_SIZE, 0.0 + BLOCK_SIZE, r, g, b, 0.0, 0.0 + BLOCK_SIZE, r, g, b, ] i = [ 0, 1, 2, 2, 3, 0 ] self.set_data(vertices=v, indices=i)
def combine_meshes(mesh1, mesh2, ensure_continuity = False): """ Combine two meshes into one disconnected mesh. This function relies on the user to make sure that nothing weird is going on. for example, the meshes probably should not intersect. I'm not sure what would happen if they do! Also, I assume that all the meshes are linear (linear mapping from real to reference space). Also, this function does not apply any mappings -- it assumes they have already been applied to the elements of the subordinate meshes. """ vertices = copy.copy(mesh1.vertices) vertices.extend(mesh2.vertices) elements = copy.copy(mesh1.elements) elements.extend(mesh2.elements) result = Mesh(vertices, elements) if ensure_continuity: result.condense_duplicate_vertices() return result
def __init__(self, obj_file_name): self.default_shape_name = obj_file_name or 'initial_shape' self.default_surface_name = 'initial_surface' self.default_material_name = 'default' # Name of the shape/surface/material from the most recently parsed 'o'/'g'/'usemtl' line respectively self.curr_shape_name = self.default_shape_name self.curr_surf_name = self.default_surface_name self.curr_mtl_name = self.default_material_name # To keep of track of number of polygons parsed so far self.next_polygon_index = 0 # A tuple of indices per vertex element self.indices = [ ] # Shortcut to be able to access the current surface in fewer characters and lookups self.curr_surf = Surface(0, self.default_material_name) # Dictionary of names -> shapes. Initialise to a default shape with a default surface self.shapes = { self.default_shape_name : Shape({ self.default_surface_name : self.curr_surf }) } Mesh.__init__(self)
def JoinAlongEdge(a, b, eta, etb, tol=0.001): """ Join two meshes along common edge ================================= INPUT: a : first Mesh object b : second Mesh object eta : tag of edges in a to be merged etb : tag of edges in b to be merged """ if a.ndim != 2: raise Exception('this method is for 2D meshes only') if b.ndim != 2: raise Exception('this method is for 2D meshes only') # collect vertices along edge of a Va = set() for ca in a.etag2cids[eta]: ia, ed = ca[0], ca[1] la = Edg2Vids[(a.ndim, len(a.C[ia][2]))][ed] Va.update([a.C[ia][2][iv] for iv in la]) # new vertices and cells list V, C = a.V[:], a.C[:] # remap vertices of b v2v = zeros(b.nv, dtype=int) # map verts in b to new verts in a k = a.nv # new vertex index for vb in b.V: # for each vertex in b found = -1 # found vb in Va (-1 => not found) for ia in Va: # for each vertex in Va va = a.V[ia] # vertex of a dd = sqrt((vb[2]-va[2])**2.0+(vb[3]-va[3])**2.0) # distance between vertices if dd < tol: # overlapping vertex found = ia # found coincident vertex in a break # no need to check other verts in Va if found < 0: # not found iv = k # index of vertex to be added V.append([iv, vb[1], vb[2], vb[3]]) # add new vertex k += 1 # next new vertex index else: # use vertex of a iv = found # index of vertex to be added v2v[vb[0]] = iv # set map # remap cells of b k = a.nc # new cell index for c in b.C: # for each cell in b if len(c) < 4: # if there is no edge tags data etags = {} # empty etags dictionary else: # there is etags data etags = {k:v for k,v in c[3].items() if v!=etb} # filter etb out C.append([k, c[1], [v2v[i] for i in c[2]], etags]) # add new cell k += 1 # next cell number # create and return mesh return Mesh(V, C)
def create_box_shape(w, h, d): points = [] vertices = [] ibo = [0, 1, 3, 2, 0, 4, 5, 1, 0, 4, 6, 7, 5, 7, 3, 2, 6] h_w = w * 0.5 h_h = h * 0.5 h_d = d * 0.5 points.append(vector3.Vector3(-h_w, -h_h, -h_d)) #000 points.append(vector3.Vector3(-h_w, -h_h, h_d)) #001 points.append(vector3.Vector3(-h_w, h_h, -h_d)) #010 points.append(vector3.Vector3(-h_w, h_h, h_d)) #011 points.append(vector3.Vector3(h_w, -h_h, -h_d)) #100 points.append(vector3.Vector3(h_w, -h_h, h_d)) #101 points.append(vector3.Vector3(h_w, h_h, -h_d)) #110 points.append(vector3.Vector3(h_w, h_h, h_d)) #111 for i in range(8): vertices.append(points[i].x) vertices.append(points[i].y) vertices.append(points[i].z) data = {} data["vbo"] = {} data["vbo"]["type"] = GL_ARRAY_BUFFER data["vbo"]["size"] = ctypes.sizeof(GLfloat * len(vertices)) data["vbo"]["data"] = (GLfloat * len(vertices))(*vertices) data["vbo"]["attributes"] = [{}] data["vbo"]["attributes"][0]["size"] = 3 data["vbo"]["attributes"][0]["type"] = GL_FLOAT data["vbo"]["attributes"][0]["stride"] = 0 data["vbo"]["attributes"][0]["offset"] = 0 data["vbo"]["attributes"][0]["normalized"] = GL_FALSE data["ibo"] = {} data["ibo"]["type"] = GL_ELEMENT_ARRAY_BUFFER data["ibo"]["size"] = ctypes.sizeof(GLuint * len(ibo)) data["ibo"]["data"] = (GLuint * len(ibo))(*ibo) mesh = Mesh("dbg_aabb") mesh.get_buffer().clear_buffer() mesh.get_buffer().prepare_buffer(GL_LINE_STRIP, len(ibo), GL_UNSIGNED_INT, data) mesh.get_buffer().create_buffer() return mesh
def test_case(): compute_stress = True num_elements_x = 50 num_elements_y = 50 num_total_nodes = (num_elements_x + 1) * (num_elements_y + 1) input_mesh = Mesh.create_plate(position=(0, 0), width=60, height=20, num_elements_width=num_elements_x, num_elements_height=num_elements_y) input_forces_nodes = list(range(0, num_total_nodes, num_elements_x + 1)) input_forces = [PointForceLoad(input_forces_nodes, [-1000, 0])] input_constraints_nodes = list( range(num_elements_x, num_total_nodes, num_elements_x + 1)) input_constraints = [FixedConstraint(input_constraints_nodes, [0, 0])] print("Computing...") solver = Solver(input_mesh, input_forces, input_constraints) u_x_y = solver.compute() print("Writing Results...") with open('displacement_x.txt', 'w') as mesh_file: for node, u in zip(input_mesh.nodes, u_x_y[0::2]): mesh_file.write("{} {} {}\n".format(node.coordinate.x, node.coordinate.y, u)) with open('displacement_y.txt', 'w') as mesh_file: for node, u in zip(input_mesh.nodes, u_x_y[1::2]): mesh_file.write("{} {} {}\n".format(node.coordinate.x, node.coordinate.y, u)) if compute_stress: stress = solver.stress_computation(u_x_y) print("Writing Stress...") with open('stress_x.txt', 'w') as mesh_file: for node, u in zip(input_mesh.nodes, stress): mesh_file.write("{} {} {}\n".format(node.coordinate.x, node.coordinate.y, u[0])) with open('stress_y.txt', 'w') as mesh_file: for node, u in zip(input_mesh.nodes, stress): mesh_file.write("{} {} {}\n".format(node.coordinate.x, node.coordinate.y, u[1])) with open('stress_xy.txt', 'w') as mesh_file: for node, u in zip(input_mesh.nodes, stress): mesh_file.write("{} {} {}\n".format(node.coordinate.x, node.coordinate.y, u[2]))
def test_funspace_8(): '''Testing of FunctionSpace.int_phi_phi, MMS''' ox, dx, nx = 0., 10., 10 mesh = Mesh(type='uniform', lx=dx, nx=nx, block='B1') V = FunctionSpace(mesh, {'B1': Element(type='link2')}) rhs = np.random.rand(V.num_dof) A = V.int_phi_phi() f = lambda x: np.interp(x, V.X, rhs) b = V.int_phi(f) assert areclose(np.dot(A, rhs), b) return
def __init__(self, scene, M=poseMatrix(), mesh=Mesh(), color=[1., 1., 1.], primitive=GL_TRIANGLES, visible=True): ''' Initialises the model data ''' print('+ Initializing {}'.format(self.__class__.__name__)) # if this flag is set to False, the model is not rendered self.visible = visible # store the scene reference self.scene = scene # store the type of primitive to draw self.primitive = primitive # store the object's color (deprecated now that we have per-vertex colors) self.color = color # store the shader program for rendering this model self.shader = None # mesh data self.mesh = mesh if self.mesh.textures == 1: self.mesh.textures.append(Texture('lena.bmp')) #self.vertices = None #self.indices = None #self.normals = None #self.vertex_colors = None #self.textureCoords = None #self.textures = [] # dict of VBOs self.vbos = {} # dict of attributes self.attributes = {} # store the position of the model in the scene, ... self.M = M # We use a Vertex Array Object to pack all buffers for rendering in the GPU (see lecture on OpenGL) self.vao = glGenVertexArrays(1) # this buffer will be used to store indices, if using shared vertex representation self.index_buffer = None
class Label(object): def __init__(self, imgName, width, height): positions = [Point(-width/2, -height/2, 0), Point(width/2, -height/2, 0), Point(-width/2, height/2, 0), Point(width/2, height/2, 0)] textures = [[0, 0], [1, 0], [0, 1], [1, 1]] indices = [0, 1, 2, 3, 2, 1] # positions, indices and textures - lists can be accessed over the mesh self.mesh = Mesh(positions, indices, textures=textures, imgName=imgName) def draw(self): self.mesh.draw(GL_TRIANGLES, len(self.mesh.indices), 0) def render(self, window): renderer = window.getRenderer() renderer.render(self, "PT")
def read_2d_mesh(self): """Считывает данные о сетке из файла .inp, перенумеровывая узлы от нуля""" self.skip_to("N O D E S") self.skip_lines(1) # пропускаем строку self.read_nodes() self.skip_to('E L E M E N T S') self.skip_lines(1) # пропускаем строку self.read_elements() self.create_edges() self.leave_only_border_edges() return Mesh(self.nodes.values(), self.elements, self.edges)
def readTetgen(fn): """Read and draw a tetgen file. This is an experimental function for the geometry import menu. """ res = {} base, ext = os.path.splitext(fn) if ext == '.node': nodes = readNodeFile(fn)[0] res['tetgen' + ext] = nodes elif ext in ['.ele', '.face']: nodes, nodenrs = readNodeFile(utils.changeExt(fn, '.node'))[:2] if ext == '.ele': elems = readEleFile(fn)[0] elif ext == '.face': elems = readFaceFile(fn)[0] if nodenrs.min() == 1 and nodenrs.max() == nodenrs.size: elems = elems - 1 M = Mesh(nodes, elems, eltype=elems.eltype) res['tetgen' + ext] = M elif ext == '.smesh': nodes, elems = readSmeshFile(fn) ML = [Mesh(nodes, elems[e]) for e in elems] res = dict([('Mesh-%s' % M.nplex(), M) for M in ML]) elif ext == '.poly': nodes, elems = readPolyFile(fn) ML = [Mesh(nodes, elems[e]) for e in elems] res = dict([('Mesh-%s' % M.nplex(), M) for M in ML]) return res
def read_mesh(fname, name=None): """ Defines mesh based on data provided in COO and MEM tabs """ if name is None: name = fname[:-5] # strip 'xlsx' from end of filename and use as name # Define new mesh object mesh_obj = Mesh(name=name) # Read in node data from Excel file COO_df = read_COO(fname) # Define nodes and append to mesh mesh_obj.define_nodes(df=COO_df) del COO_df # Read in member data from Excel file MEM_df = read_MEM(fname) # Define elements and append to mesh mesh_obj.define_line_elements(df=MEM_df) del MEM_df return mesh_obj
def test_computeL1Error1D(self): # create mesh left = 2.5 width = 1.5 mesh = Mesh(3, width, x_start=left) # create "numerical solution" data numerical_solution = [(1.0,2.0),(1.6,2.2),(2.5,2.7)] # specify "exact solution" function def exact(x): return x**2 + 3.0 # compute exact integral of difference exact_integral = 0.0 for i in xrange(mesh.n_elems): # express local numerical solution as linear function y(x) = m*x + b el = mesh.getElement(i) xL = el.xl xR = el.xr yL = numerical_solution[i][0] yR = numerical_solution[i][1] dx = xR - xL dy = yR - yL m = dy / dx b = yL - xL*m # compute local integral of difference local_integral = (xR**3 - xL**3)/3.0 - 0.5*m*(xR**2 - xL**2)\ + (3.0-b)*(xR - xL) # add to global integral of difference exact_integral += local_integral # compute numerical integral of difference numerical_integral = computeL1ErrorLD(mesh, numerical_solution, exact) # assert that numerical and exact integrals are approximately equal n_decimal_places = 14 self.assertAlmostEqual(numerical_integral,exact_integral,n_decimal_places)
def readMesh(self, ncoords, nelems, nplex, props, eltype, normals, sep, objtype='Mesh'): """Read a Mesh from a pyFormex geometry file. The following arrays are read from the file: - a coordinate array with `ncoords` points, - a connectivity array with `nelems` elements of plexitude `nplex`, - if present, a property number array for `nelems` elements. Returns the Mesh constructed from these data, or a subclass if an objtype is specified. """ # Make sure to import the Mesh subclasses that can be read from plugins.trisurface import TriSurface ndim = 3 x = readArray(self.fil, Float, (ncoords, ndim), sep=sep) e = readArray(self.fil, Int, (nelems, nplex), sep=sep) if props: p = readArray(self.fil, Int, (nelems, ), sep=sep) else: p = None M = Mesh(x, e, p, eltype) if objtype != 'Mesh': try: clas = locals()[objtype] except: clas = globals()[objtype] M = clas(M) if normals: n = readArray(self.fil, Float, (nelems, nplex, ndim), sep=sep) M.normals = n return M
def merge_mesh(base_mesh, extended_mesh, extended_snapping_correspondences, extended_snapping_region): new_mesh = Mesh() new_mesh.positions = base_mesh.positions.tolist() new_mesh.faces = base_mesh.faces.copy() snapping_region_faces = set() for face in new_mesh.faces: face_is_in_snapping_region = True for vertex in face: if vertex not in extended_snapping_region: face_is_in_snapping_region = False break if face_is_in_snapping_region: snapping_region_faces.add(Triangle(face)) extended_correspondences = extended_snapping_correspondences.copy() for i, position in enumerate(extended_mesh.positions): # if i in extended_correspondences: if i in extended_snapping_region: continue new_index = len(new_mesh.positions) extended_correspondences[i] = new_index new_mesh.positions.append(position) for face in extended_mesh.faces: # face_is_in_snapping_region = True # for vertex in face: # if vertex not in extended_snapping_region: # face_is_in_snapping_region = False # break # # don't copy faces that are completely in the snapping region # if face_is_in_snapping_region: # continue new_face = [extended_correspondences[vertex] for vertex in face] if Triangle(new_face) in snapping_region_faces: continue new_mesh.faces.append(new_face) return new_mesh
def _process_mesh(self, mesh, scene): vertices = (mesh.num_vertices * Vertex)() for i in range(mesh.num_vertices): vertices[i].Position = Vec3(*mesh.vertices[i]) vertices[i].Normal = Vec3(*mesh.normals[i]) if mesh.texcoords[0]: vertices[i].TexCoords = Vec2(*mesh.texcoords[0][i][:2]) vertices[i].Tangent = Vec3(*mesh.tangents[i]) vertices[i].Bitangent = Vec3(*mesh.bitangents[i]) else: vertices[i].TexCoords = Vec2(0, 0) vertices[i].Tangent = Vec3(0, 0, 0) vertices[i].Bitangent = Vec3(0, 0, 0) idx = [i for face in mesh.indices for i in face] indices = (ctypes.c_uint * len(idx))(*idx) # process materials textures = [] material = scene.materials[mesh.material_index] # we assume a convention for sampler names in the shaders. Each diffuse texture should be named # as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. # Same applies to other texture as the following list summarizes: # diffuse: texture_diffuseN # specular: texture_specularN # normal: texture_normalN # 1. diffuse maps diffuse_maps = self._load_material_textures(material, assimp.TextureType_DIFFUSE, "texture_diffuse") textures.extend(diffuse_maps) # 2. specular maps specular_maps = self._load_material_textures( material, assimp.TextureType_SPECULAR, "texture_specular") textures.extend(specular_maps) # 3. normal maps normal_maps = self._load_material_textures(material, assimp.TextureType_HEIGHT, "texture_normal") textures.extend(normal_maps) # 4. height maps height_maps = self._load_material_textures(material, assimp.TextureType_AMBIENT, "texture_height") textures.extend(height_maps) return Mesh(vertices, indices, textures)
def test_funspace_4(): '''Test of FunctionSpace.int_phi_phi made up of linear elements, Laplace matrix multiply ''' ox, dx, nx = 0., 1., 10 mesh = Mesh(type='uniform', lx=dx, nx=nx, block='B1') V = FunctionSpace(mesh, {'B1': Element(type='link2')}) C = V.int_phi_phi(derivative=(True, True)) sol = np.ones(V.num_dof) b = np.dot(C, sol) assert norm(b) < 1.e-12
def _compile(self): self._need_compile = False try: p, q = vec4(-1.0, -1.0, 0.0, 1.0), vec4(+1.0, -1.0, 0.0, 1.0) s, t = vec4(-1.0, +1.0, 0.0, 1.0), vec4(+1.0, +1.0, 0.0, 1.0) mesh_def = MeshDef(*("./gl/vs.glsl", "./gl/fs.glsl"), np.array((*p, *q, *s, *t), dtype=np.float32), np.array([0, 1, 2, 2, 1, 3], dtype=np.int32)) self.scene = [Mesh(self.gl, mesh_def)] except Exception as e: print(e.with_traceback(None))
def save_regions(self, filename_trunk, region_names=None): """Save regions as meshes.""" if region_names is None: region_names = self.domain.regions.get_names() output("saving regions...") for name in region_names: region = self.domain.regions[name] output(name) aux = Mesh.from_region(region, self.domain.mesh, self.domain.ed, self.domain.fa) aux.write("%s_%s.mesh" % (filename_trunk, region.name), io="auto") output("...done")
def line(nb_segments): """Create a 1D mesh along a single line made of nb segments """ #create mesh m = Mesh() #create points pids = [] for i in range(nb_segments + 1): pid = m.add_dart(0) m.set_position(pid, float(i)) pids.append(pid) #create segments for i in range(nb_segments): did = m.add_dart(1) m.link(did, pids[i]) m.link(did, pids[i + 1]) #return return m
def main(): #creation de notre class mesh myMesh = Mesh() #parsage du .off placé en argument myMesh.parseEntry(sys.argv[1]) if len(sys.argv) > 1 else myMesh.parseEntry() baseMeshPath = sys.argv[1] if len(sys.argv) > 1 else "../models/cylindre.off" #choix du point centrale du Handle originIndex = 400 sauvPoint = myMesh.points[originIndex] newPointPos = (myMesh.points[originIndex][0]+0.5, myMesh.points[originIndex][1]+1, myMesh.points[originIndex][2]) #creation du Handle tailleHandle = 0 #Si 0 le Handle n'est qu'un point listePointsHandle = myMesh.getAllVoisins(originIndex, tailleHandle) sauvListePointsHandle = myMesh.getCoordonneesListePoints(listePointsHandle) newListePointsHandle = myMesh.createHandle(sauvListePointsHandle, newPointPos) #Creation de la ROI tailleROI= 5 zone = IntrestZone(myMesh) zone.findPointsByVoisins(originIndex,tailleROI) #lancement de la minimisation res = minimizationHandle(myMesh, zone, originIndex,newListePointsHandle, True) #mise à jour des point du mesh for i in range(zone.numberOfPoints): myMesh.points[zone.intrestPoints[i]] = (res[0][i], res[1][i], res[2][i]) myMesh.saveMeshOff() #print("\n points d'origine: ", sauvListePointsHandle) #print("\n points voulus: ", newListePointsHandle) #print("\n point centrale obtenu: ", myMesh.points[originIndex]) affichage(myMesh, zone, originIndex, newPointPos, sauvPoint)
def close_loop_example(): # one more example, originally not a closed loop curve F = Formex(pattern('11')).replic(2,1,1) + Formex(pattern('2')).replic(2,2,0) M = F.toMesh() draw(M,color='green') drawNumbers(M,color=red) drawNumbers(M.coords,color=blue) print "Original elements:",M.elems conn = connectivity.connectedLineElems(M.elems) if len(conn) > 1: message("This curve is not a closed circumference") return None sorted = conn[0] print "Sorted elements:",sorted showInfo('Click to continue') clear() M = Mesh(M.coords,sorted) drawNumbers(M) return M.toFormex()
def print_stats(generation, individuals): global TIME def ave(values): return float(sum(values)) / len(values) def std(values, ave): return math.sqrt( float(sum((value - ave)**2 for value in values)) / len(values)) newTime = time.time() genTime = newTime - TIME TIME = newTime ave_beam = ave( [i.beamTotal for i in individuals if i.phenotype is not None]) std_beam = std( [i.beamTotal for i in individuals if i.phenotype is not None], ave_beam) ave_fit = ave( [i.fitness[0] for i in individuals if i.phenotype is not None]) std_fit = std( [i.fitness[0] for i in individuals if i.phenotype is not None], ave_fit) ave_used_codons = ave( [i.used_codons for i in individuals if i.phenotype is not None]) std_used_codons = std( [i.used_codons for i in individuals if i.phenotype is not None], ave_used_codons) print( "Gen:%d best:%s beams:s:%d ave:%.1f+-%.1f Used:%.1f+-%.1f tt:%.2f beams:%d+-%.1f" % (generation, individuals[0].fitness, individuals[0].beamTotal, ave_fit, std_fit, ave_used_codons, std_used_codons, genTime, ave_beam, std_beam)) if SAVE_BEST: print "saving best individual" bestMesh = Mesh(individuals[0].phenotype) filename = 'xxx.' + str(generation) bestMesh.create_mesh(True, filename)
def create_mesh(self, part, road_width): self.write('#MESH\n') part_name = part.get_part_name() #makes global seed half of the road width globalSeed = road_width / 2 #creating mesh object mesh = Mesh(part, globalSeed) part.create_mesh(mesh) self.write(part_name + '.seedPart(size=' + str(globalSeed) + ', deviationFactor=0.1, minSizeFactor=0.1)\n') self.write('e = ' + part_name + '.edges\n') self.write(part_name + '.generateMesh()\n') self.seperate_sec()
def __init__(self): if Shot.shot_mesh is None: Shot.shot_mesh = Mesh.create_sphere((0.1, 0.1, 0.1), 4, 4) Shot.shot_material = Material(Color(1, 1, 0, 1), "ShotMaterial") super().__init__("Shot") # The position and direction will be overwritten by the code that spawns the shot self.position = Vector3(0, 0, 0) self.mesh = Shot.shot_mesh self.material = Shot.shot_material self.shot_speed = 6 self.direction = Vector3(0, 0, 0)
def set_block( self , s , d ) : aoy = m.atan2( s[2] , s[0] ) aoz = m.atan2( s[1] , m.sqrt(s[0]**2+s[2]**2) ) rot = tr.rotation_matrix( aoy , (0,1,0) ) rot = np.dot( tr.rotation_matrix( -aoz , (0,0,1) ) , rot ) rot = np.dot( tr.rotation_matrix( m.pi/2.0 , (0,0,1) ) , rot ) v , n , t = self.gen_v( 1 , 1 , s ) for x in range(v.shape[0]) : for y in range(v.shape[1]) : for z in range(v.shape[2]) : v[x,y,z] = np.dot(rot,v[x,y,z]) n[x,y,z] = np.resize(np.dot(rot,np.resize(n[x,y,z],4)),3) Mesh.__init__( self , buffers = (v,n,t) ) self.x = np.array( ((0,0,0,1),(s[0],0,0,1),(0,0,s[2],1),(s[0],0,s[2],1),(0,s[1],0,1),(s[0],s[1],0,1),(0,s[1],s[2],1),(s[0],s[1],s[2],1)) , np.float64 ) for i in range(len(self.x)) : self.x[i] = np.dot(rot,self.x[i]) self.r = np.resize( np.dot( rot , np.array((s[0],s[1],s[2],0) , np.float64 )/2.0 ) , 3 ) self.m = np.array( [ d*s[0]*s[1]*s[2] / 8.0 ] * len(self.x) , np.float64 ) self.M = self.calc_m( self.x , self.m ) self.Mi = np.linalg.inv( self.M )
def render_asset(self, asset): # Render the models: for m in asset.models: model_name = m.filename glPushMatrix() for t in m.transformers: transformers = Renderer.get_chained_transformers(asset, t) Renderer.apply_transformers(transformers) if model_name in self.asset_manager.meshes.keys(): self.render_model(self.asset_manager.meshes[model_name], materials=m.materials) glPopMatrix() # Render the files: for f in asset.files: a = self.asset_manager.sub_assets.get(f.filename, None) if a: glPushMatrix() for t in f.transformers: transformers = Renderer.get_chained_transformers(asset, t) Renderer.apply_transformers(transformers) self.render_asset(a) glPopMatrix() # Render the props: for pc in asset.prop_containers: glPushMatrix() for t in pc.transformers: transformers = Renderer.get_chained_transformers(asset, t) Renderer.apply_transformers(transformers) for p in pc.props: self.render_prop(p) glPopMatrix() # Render the decal glColor3f(1.0, 1.0, 1.0) for decal in asset.decals: if not decal.is_terrain(): continue extent = decal.get_extents() glPushMatrix() glTranslatef(-extent[0], 0, -extent[2]) for t in decal.transformers: transformers = Renderer.get_chained_transformers(asset, t) Renderer.apply_transformers(transformers) decal_mesh = Mesh.gen_square(extent[0] * 2, extent[2] * 2) decal_materials = list(decal.materials) self.render_model(decal_mesh, materials=decal_materials) glPopMatrix() # Render the lights for light in asset.lights: self.render_light(light, asset)
def remesh(mesh1, mesh2, snapping_region1, snapping_region2, smoothing_factor=1, osculating_circle_angle_subtended=pi/4): point_cloud = PointCloud([(mesh1, snapping_region1), (mesh2, snapping_region2)], smoothing_factor, osculating_circle_angle_subtended) boundaries = UpdateablePriorityQueue() new_mesh = Mesh() # new_mesh.positions.append(np.array([0,0,0])) # initialize new_mesh and boundaries with snapping regions' boundaries add_snapping_region_boundary(boundaries, new_mesh, mesh1, snapping_region1, point_cloud) add_snapping_region_boundary(boundaries, new_mesh, mesh2, snapping_region2, point_cloud) it = 0 while boundaries: it += 1 if it % 20 == 0: save_mesh(new_mesh, it/20) (is_deferred, priority, vertex), edge = boundaries.pop() if priority < .1: # priority < 0 only set for cuts cut_ear(new_mesh, edge, vertex, boundaries, point_cloud) continue # vertex = predict_vertex(edge, field, other_vertex) # closest_dist, closest_vertex = find_closest_boundary(vertex, boundaries, new_mesh) closest1 = find_closest_boundary(vertex, boundaries, new_mesh) closest2 = (math.inf,0) for i,pos in enumerate(new_mesh.positions): dist = np.linalg.norm(pos - vertex) if dist < closest2[0]: closest2 = (dist, i) closest_dist, closest_vertex = min(closest1, closest2) if closest_dist < point_cloud.guidance_field(vertex) / 2: if is_deferred: print("merge") # create triangle with closest vertex of closest_edge # edge1_length = np.linalg.norm(new_mesh.positions[closest_edge[0]] - vertex) # edge2_length = np.linalg.norm(new_mesh.positions[closest_edge[1]] - vertex) # vertex_index = closest_edge[0] if edge1_length < edge2_length else closest_edge[1] vertex_index = closest_vertex connect_triangle(new_mesh, edge, vertex_index, boundaries, point_cloud) # if vertex closer to edge endpoints than closest_edge endpoints: # split closest_edge # else: # merge to closest_edge endpoint else: boundaries.push(edge, (True, priority, vertex)) else: grow_triangle(new_mesh, edge, vertex, boundaries, point_cloud) # TODO return maps from old to new vertices on snapping region boundary return new_mesh
def create_meshes_from_blender(vlist, flist, mlist, library): fstart = 0 material = None meshes = [] # we start by putting all vertices in one array varray = np.array(vlist, dtype='f') for f in range(len(flist)): if material is None: material = mlist[f] elif material != mlist[f]: # new mesh is denoted by change in material farray = np.array(flist[fstart:f], dtype=np.uint32)[:, :, 0] vmax = np.max(farray.flatten()) vmin = np.min(farray.flatten()) - 1 #print('+++ vertices ID in range [{},{}] and vstart={} / vmax={}'.format(np.min(farray.flatten()), np.max(farray.flatten()), vstart, vmax)) meshes.append( Mesh(vertices=varray[vmin:vmax, :], faces=farray - vmin - 1, material=library.materials[material])) # start the next mesh fstart = f farray = np.array(flist[fstart:], dtype=np.uint32)[:, :, 0] vmax = np.max(farray.flatten()) vmin = np.min(farray.flatten()) - 1 meshes.append( Mesh(vertices=varray[vmin:vmax, :], faces=farray - vmin - 1, material=library.materials[material])) print('--- Created {} mesh(es) from Blender file.'.format(len(meshes))) return meshes
class TexturePlane: ## Constructor def __init__(self, image): self._image = to8U(image) self._geometry = Mesh() self._initGeometry() self._texture_id = None def gl(self): glEnable(GL_TEXTURE_2D) if self._texture_id is None: self._texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._texture_id) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, self._image.shape[1], self._image.shape[0], GL_RGBA, GL_UNSIGNED_BYTE, self._image) self._geometry.gl() def boundingBox(self): return self._geometry.boundingBox() @timing_func def _initGeometry(self): h, w = self._image.shape[:2] points = np.array([(0.0, 0.0, 0.0), (w - 1.0, 0.0, 0.0), (w - 1.0, h - 1.0, 0.0), (0.0, h - 1.0, 0.0)]) index_array = np.array([(0, 1, 2, 3)]) tex_coords = np.array([(0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]) self._geometry.setPositions(points) self._geometry.setInexArray(index_array) self._geometry.setTexCoords(tex_coords)
def __makeMeshes(self): geom = self.settings['geometry'] nxCells = sum(geom['divisions']) cells = empty(nxCells, dtype=object) cellIndx = 0 zipped = zip(geom['bounds'], geom['divisions'], geom['universes']) for indx, (bnd, div, xsMat) in enumerate(zipped): lower = geom['bounds'][indx - 1] if indx else 0 corners = linspace(lower, bnd, div + 1) for count in range(div): mesh = Mesh(self, corners[count:count + 2], xsMat) cells[cellIndx] = mesh cellIndx += 1 self.meshes = cells
def main(): parser = argparse.ArgumentParser() parser.add_argument("mesh1", type=str) parser.add_argument("mesh2", type=str) parser.add_argument("output", type=str) parser.add_argument("iterations", type=int) parser.add_argument("--elasticity", type=int, default=1) parser.add_argument("--smoothing", type=float, default=1) # TODO offset? args = parser.parse_args() mesh1 = Mesh(PlyData.read(args.mesh1)) mesh2 = Mesh(PlyData.read(args.mesh2)) output = merge(mesh1, mesh2, args.iterations, args.elasticity, args.smoothing) # IPython.embed() save_mesh(mesh1, "output1.ply") save_mesh(mesh2, "output2.ply") save_mesh(output, args.output, np_array=False) (trimesh.load("output1.ply") + trimesh.load("output2.ply")).show() trimesh.load(args.output).show()
def __init__(self, obj_file_name): self.default_shape_name = obj_file_name or 'initial_shape' self.default_surface_name = 'initial_surface' self.default_material_name = 'default' # Name of the shape/surface/material from the most recently parsed 'o'/'g'/'usemtl' line respectively self.curr_shape_name = self.default_shape_name self.curr_surf_name = self.default_surface_name self.curr_mtl_name = self.default_material_name # To keep of track of number of polygons parsed so far self.next_polygon_index = 0 # A tuple of indices per vertex element self.indices = [] # Shortcut to be able to access the current surface in fewer characters and lookups self.curr_surf = Surface(0, self.default_material_name) # Dictionary of names -> shapes. Initialise to a default shape with a default surface self.shapes = { self.default_shape_name: Shape({self.default_surface_name: self.curr_surf}) } Mesh.__init__(self)
def test_funspace_3(): '''Test of FunctionSpace.int_phi_phi made up of linear elements, Laplace matrix integration ''' ox, dx, nx = 0., 1., 1 mesh = Mesh(type='uniform', lx=dx, nx=nx, block='B1') V = FunctionSpace(mesh, {'B1': Element(type='link2')}) # Integrate[N'(x) N'(x) {x, 0, 1}] f = lambda i, j: integrate(dN[i] * dN[j], (x, ox, dx)) ans = V.int_phi_phi(derivative=(True, True)) exact = Matrix(2, 2, lambda i, j: f(i,j)) assert areclose(exact, ans)
def compile(self): self._need_compile = False try: self.scene = [] for node in scene_def: assert len(node) == 4 mesh = Mesh(self.gl, *node) self.scene.append(mesh) print("compiled") except Exception as e: print(e)
def save_regions( self, filename_trunk, region_names = None ): """Save regions as meshes.""" if region_names is None: region_names = self.domain.regions.get_names() output( 'saving regions...' ) for name in region_names: region = self.domain.regions[name] output( name ) aux = Mesh.from_region(region, self.domain.mesh) aux.write( '%s_%s.mesh' % (filename_trunk, region.name), io = 'auto' ) output( '...done' )
def __init__(self): super().__init__("RandomCube") #defining random height height = random.uniform(1,3) # Create a cube on a random positions self.mesh = Mesh.create_cube((random.uniform(0, 2), height,random.uniform(0, 2))) self.position = Vector3(random.uniform(-20, 20), (height / 2) -1, random.uniform(-20, 20)) #distance right and left height distance front and back # Pick a random Color for the cube self.material = Material(Color(random.uniform(0.1, 1), random.uniform(0.1, 1), random.uniform(0.1, 1), 1), "CubeMaterial")
def remesh(self,edgelen=None): """Remesh a TriSurface. edgelen is the suggested edge length """ if edgelen is None: self.getElemEdges() E = Mesh(self.coords,self.edges,eltype='line2') edgelen = E.lengths().mean() tmp = utils.tempFile(suffix='.stl').name tmp1 = utils.tempFile(suffix='.stl').name pf.message("Writing temp file %s" % tmp) self.write(tmp,'stl') pf.message("Remeshing using VMTK (edge length = %s)" % edgelen) cmd = "vmtk vmtksurfaceremeshing -ifile %s -ofile %s -edgelength %s" % (tmp,tmp1,edgelen) sta,out = utils.runCommand(cmd) os.remove(tmp) if sta: pf.message("An error occurred during the remeshing.") pf.message(out) return None S = TriSurface.read(tmp1) os.remove(tmp1) return S
def save_region_field_meshes(self, filename_trunk): output("saving regions of fields...") for field in self.fields: fregion = self.domain.regions[field.region_name] output("field %s: saving regions..." % field.name) for region in self.domain.regions: if not fregion.contains(region): continue output(region.name) aux = Mesh.from_region_and_field(region, field) aux.write("%s_%s_%s.mesh" % (filename_trunk, region.name, field.name), io="auto") output("...done") output("...done")
def __init__( self , fov , ratio , near , far , skybox_img , duck_img ) : self.fov = fov self.far = far self.near = near self.ratio = ratio self.last_time = timer() self.water = Water( 128 ) self.box = Skybox( skybox_img ) self.duck = Mesh( 'data/duck.gpt' , duck_img , 'shad/anisotropic' ) self.path = BSpline( (-1,1) , (-1,1) ) self.light = np.array( (0,2,0) ) self.water.drop_rnd()
def __init__( self , fovy , ratio , near , far ) : self.fovy = fovy self.near = near self.far = far self.ratio = ratio self.camera = None self.mesh = Mesh('plane.mesh') self.x = 0.0 self.last_time = timer() self.plane_alpha = 65.0 / 180.0 * m.pi self.lpos = [ 1 ,-1 , 0 ]
def line (nb_segments) : """Create a 1D mesh along a single line made of nb segments """ #create mesh m = Mesh() #create points pids = [] for i in range(nb_segments + 1) : pid = m.add_dart(0) m.set_position(pid, float(i) ) pids.append(pid) #create segments for i in range(nb_segments) : did = m.add_dart(1) m.link(did, pids[i]) m.link(did, pids[i + 1]) #return return m
class TexturePlane: ## Constructor def __init__(self, image): self._image = to8U(image) self._geometry = Mesh() self._initGeometry() self._texture_id = None def gl(self): glEnable( GL_TEXTURE_2D ) if self._texture_id is None: self._texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._texture_id) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, self._image.shape[1], self._image.shape[0], GL_RGBA, GL_UNSIGNED_BYTE, self._image) self._geometry.gl() def boundingBox(self): return self._geometry.boundingBox() @timing_func def _initGeometry(self): h, w = self._image.shape[:2] points = np.array([(0.0, 0.0, 0.0), (w - 1.0, 0.0, 0.0), (w - 1.0, h - 1.0, 0.0), (0.0, h - 1.0, 0.0)]) index_array = np.array([(0, 1, 2, 3)]) tex_coords = np.array([(0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]) self._geometry.setPositions(points) self._geometry.setInexArray(index_array) self._geometry.setTexCoords(tex_coords)
def from_conf(conf, init_fields=True, init_equations=True, init_solvers=True): if conf.options.get_default_attr('absolute_mesh_path', False): conf_dir = None else: conf_dir = op.dirname(conf.funmod.__file__) functions = Functions.from_conf(conf.functions) mesh = Mesh.from_file(conf.filename_mesh, prefix_dir=conf_dir) trans_mtx = conf.options.get_default_attr('mesh_coors_transform', None) if trans_mtx is not None: mesh.transform_coors(trans_mtx) domain = Domain(mesh.name, mesh) if get_default_attr(conf.options, 'ulf', False): domain.mesh.coors_act = domain.mesh.coors.copy() obj = ProblemDefinition('problem_from_conf', conf=conf, functions=functions, domain=domain, auto_conf=False, auto_solvers=False) obj.set_regions(conf.regions, obj.functions) obj.clear_equations() if init_fields: obj.set_fields( conf.fields ) if init_equations: obj.set_equations(conf.equations, user={'ts' : obj.ts}) if init_solvers: obj.set_solvers( conf.solvers, conf.options ) return obj
def save_state(self, filename, state=None, out=None, fill_value=None, post_process_hook=None, linearization=None, file_per_var=False, **kwargs): """ Parameters ---------- file_per_var : bool or None If True, data of each variable are stored in a separate file. If None, it is set to the application option value. linearization : Struct or None The linearization configuration for higher order approximations. If its kind is 'adaptive', `file_per_var` is assumed True. """ linearization = get_default(linearization, self.linearization) if linearization.kind != 'adaptive': file_per_var = get_default(file_per_var, self.file_per_var) else: file_per_var = True extend = not file_per_var if (out is None) and (state is not None): out = state.create_output_dict(fill_value=fill_value, extend=extend, linearization=linearization) if post_process_hook is not None: out = post_process_hook(out, self, state, extend=extend) if linearization.kind == 'adaptive': for key, val in out.iteritems(): mesh = val.get('mesh', self.domain.mesh) aux = io.edit_filename(filename, suffix='_' + val.var_name) mesh.write(aux, io='auto', out={key : val}, float_format=self.float_format, **kwargs) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) elif file_per_var: meshes = {} if self.equations is None: varnames = {} for key, val in out.iteritems(): varnames[val.var_name] = 1 varnames = varnames.keys() outvars = self.create_variables(varnames) itervars = outvars.__iter__ else: itervars = self.equations.variables.iter_state for var in itervars(): rname = var.field.region.name if meshes.has_key( rname ): mesh = meshes[rname] else: mesh = Mesh.from_region(var.field.region, self.domain.mesh, localize=True, is_surface=var.is_surface) meshes[rname] = mesh vout = {} for key, val in out.iteritems(): try: if val.var_name == var.name: vout[key] = val except AttributeError: msg = 'missing var_name attribute in output!' raise ValueError(msg) aux = io.edit_filename(filename, suffix='_' + var.name) mesh.write(aux, io='auto', out=vout, float_format=self.float_format, **kwargs) else: self.domain.mesh.write(filename, io='auto', out=out, float_format=self.float_format, **kwargs)