def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): hashed_file_name = hashlib.md5( (''.join(obj_files) + 'load_meshes' + str(recalculate_normals)).encode('utf-8')).hexdigest() + '.npy' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) if os.path.exists(out_file): return np.load(out_file, allow_pickle=True) else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = [] for face in mesh.faces: vertices.extend([ mesh.vertices[face[0]], mesh.vertices[face[1]], mesh.vertices[face[2]] ]) vertices = np.array(vertices) # vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) if not os.path.exists(vertex_tmp_store_folder): os.makedirs(vertex_tmp_store_folder) np.save(out_file, attributes) return attributes
def load_model(self, path, postprocess=None): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene)
def loadModel(self): # Separates model data from loaded file and processed into a usable format if self.model: logger.info(self.fileMain + " is already loaded.") return logger.info("Loading model:" + self.fileMain + "...") model = None if self.postprocess: model = pyassimp.load(self.fileMain, self.postprocess) else: model = pyassimp.load(self.fileMain) if self.fileReplace: aux = pyassimp.load(self.fileReplace) for i in range(len(model.meshes)): replaced = model.meshes[i].bones model.meshes[i].bones = aux.meshes[i].bones.copy( ) # replaces the bones with those from the secondary file del replaced pyassimp.release(aux) logger.info("Done.") scene = model for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene) self.model = model
def main(): global scene print('Reading \'{}\'...'.format(path)) t = Timer(doImport) secs = t.timeit(1) print('> On AssimpCy Took {:0.4f} seconds.'.format(secs)) print('\tHas {} meshes, {} textures, {} materials, {} animations'.format( scene.mNumMeshes, scene.mNumTextures, scene.mNumMaterials, scene.mNumAnimations)) if scene.HasMeshes and scene.mMeshes[0].HasPositions: print('\tand {} vertices on mesh 0'.format( int(scene.mMeshes[0].mNumVertices))) v = int(scene.mMeshes[0].mNumVertices / 2) print('\tVertex {} = {}'.format(v, scene.mMeshes[0].mVertices[v])) print() # print(scene.mRootNode.mTransformation) t = Timer(doImportPy) secs = t.timeit(1) print('> On PyAssimp Took {:0.4f} seconds.'.format(secs)) print('\tHas {} meshes, {} textures, {} materials, {} animations'.format( scene.mNumMeshes, scene.mNumTextures, scene.mNumMaterials, scene.mNumAnimations)) if len(scene.meshes) and len(scene.meshes[0].vertices): print('\tand {} vertices on mesh 0'.format( len(scene.meshes[0].vertices))) v = int(len(scene.meshes[0].vertices) / 2) print('\tVertex {} = {}'.format(v, scene.meshes[0].vertices[v])) # print(scene.rootnode.transformation) release(scene)
def main(): global scene print('Reading \'{}\'...'.format(path)) t = Timer(doImport) secs = t.timeit(1) print('> On AssimpCy Took {:0.4f} seconds.'.format(secs)) print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes, scene.mNumTextures, scene.mNumMaterials, scene.mNumAnimations)) if scene.HasMeshes and scene.mMeshes[0].HasPositions: print('\tand {} vertices on mesh 0'.format(int(scene.mMeshes[0].mNumVertices))) v = int(scene.mMeshes[0].mNumVertices / 2) print('\tVertex {} = {}'.format(v, scene.mMeshes[0].mVertices[v])) print() # print(scene.mRootNode.mTransformation) t = Timer(doImportPy) secs = t.timeit(1) print('> On PyAssimp Took {:0.4f} seconds.'.format(secs)) print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes, scene.mNumTextures, scene.mNumMaterials, scene.mNumAnimations)) if len(scene.meshes) and len(scene.meshes[0].vertices): print('\tand {} vertices on mesh 0'.format(len(scene.meshes[0].vertices))) v = int(len(scene.meshes[0].vertices) / 2) print('\tVertex {} = {}'.format(v, scene.meshes[0].vertices[v])) # print(scene.rootnode.transformation) release(scene)
def make_mesh(name, pose, filename, scale=(1, 1, 1)): ''' returns a CollisionObject with the mesh defined in the path. mostly copied from https://github.com/ros-planning/moveit_commander/blob/kinetic-devel/src/moveit_commander/planning_scene_interface.py ''' print("Creating mesh with file from", filename) co = CollisionObject() scene = pyassimp.load(filename) if not scene.meshes: raise MoveItCommanderException("There are no meshes in the file") co.operation = CollisionObject.ADD co.id = name co.header = pose.header mesh = Mesh() for face in scene.meshes[0].faces: triangle = MeshTriangle() if len(face) == 3: triangle.vertex_indices = [face[0], face[1], face[2]] mesh.triangles.append(triangle) for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) co.meshes = [mesh] co.mesh_poses = [pose.pose] pyassimp.release(scene) return co
def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): md5_string = str(''.join(obj_files) + 'load_meshes' + str(recalculate_normals)) md5_string = md5_string.encode('utf-8') # ('utf-8') hashed_file_name = hashlib.md5(md5_string).hexdigest() + '.pickle' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) print(md5_string) print(hashed_file_name) if os.path.exists(out_file): loaded_obj = ae_utils.load_pickled_data(out_file) return loaded_obj else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) ae_utils.save_pickled_data(attributes, out_file) return attributes
def main(filename=None): filename = filename or DEFAULT_MODEL scene = pyassimp.load(filename) #the model we load print "MODEL:", filename print #write some statistics print "SCENE:" print " meshes:", len(scene.meshes) print " materials:", len(scene.materials) print " textures:", len(scene.textures) print print "NODES:" recur_node(scene.rootnode) print print "MESHES:" for index, mesh in enumerate(scene.meshes): print " MESH", index+1 print " material id:", mesh.materialindex+1 print " vertices:", len(mesh.vertices) print " first 3 verts:", mesh.vertices[:3] if mesh.normals: print " first 3 normals:", mesh.normals[:3] else: print " no normals" print " colors:", len(mesh.colors) tc = mesh.texturecoords if tc: print " texture-coords 1:", len(tc[0]), "first3:", tc[0][:3] print " texture-coords 2:", len(tc[1]), "first3:", tc[1][:3] print " texture-coords 3:", len(tc[2]), "first3:", tc[2][:3] print " texture-coords 4:", len(tc[3]), "first3:", tc[3][:3] else: print " no texture coordinates" print " uv-component-count:", len(mesh.numuvcomponents) print " faces:", len(mesh.faces), "first:", [f.indices for f in mesh.faces[:3]] print " bones:", len(mesh.bones), "first:", [str(b) for b in mesh.bones[:3]] print print "MATERIALS:" for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print " %s: %s" % (key, value) print print "TEXTURES:" for index, texture in enumerate(scene.textures): print " TEXTURE", index+1 print " width:", texture.width print " height:", texture.height print " hint:", texture.achformathint print " data (size):", len(texture.data) # Finally release the model pyassimp.release(scene)
def load_model(self, path, postprocess = aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): """convert the vertice and face in the original mesh, and also give a color in there""" self.c = mestTest.Convert(mesh, path) self.c.convert() modifyVertices, modifyTri, color, triangleSelected = self.c.surfaceDisplay(5,True) mesh.vertices = numpy.array(modifyVertices) mesh.color = numpy.array(color) mesh.faces = numpy.array(modifyTri, dtype = 'int32') self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def load(self, filePath): self.geo = Mesh() scene = pyassimp.load(filePath, processing=import_flags) norms = None uvs = None for mesh in scene.meshes: offset = self.geo.getNumVertexes() self.geo.addVertices(mesh.vertices) for vts in mesh.faces: self.geo.mesh.add_face([self.geo.mesh.vertex_handle(i + offset) for i in vts if i >= 0]) normals = mesh.normals if normals.shape[0] > 0: if norms is None: norms = [normals] else: norms.append(normals) elif norms is not None: norms.append(np.zeros((len(mesh.vertices), 3))) texcoords = mesh.texturecoords if texcoords.shape[0] > 0: if uvs is None: uvs = [texcoords[0]] else: uvs.append(texcoords[0]) elif uvs is not None: uvs.append(np.zeros((len(mesh.vertices), 3))) if norms is not None: self.geo.setVertexAttribData('normal', np.vstack(norms), attribType='vector3', defaultValue=[0, 0, 0]) if uvs is not None: self.geo.setVertexAttribData('uv', np.vstack(uvs), attribType='vector3', defaultValue=[0, 0, 0]) pyassimp.release(scene)
def load_model(self, path, postprocess=aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, processing=postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene # log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) self.glize(scene, scene.rootnode) # Finally release the model pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): from utils.sundermeyer.gl_utils import inout hashed_file_name = hashlib.md5( (''.join(obj_files) + 'load_meshes' + str(recalculate_normals)).encode('utf-8')).hexdigest() + '.npy' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) if os.path.exists(out_file): print("loading file...") return np.load(out_file) else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) #np.save(out_file, attributes) return attributes
def make_mesh(self, co, pose, filename, scale=(1.0, 1.0, 1.0)): try: scene = pyassimp.load(filename) except AssimpError as e: rospy.logerr("Assimp error: %s", e) return False if not scene.meshes: raise MoveItCommanderException("There are no meshes in the file") mesh = Mesh() for face in scene.meshes[0].faces: triangle = MeshTriangle() if len(face.indices) == 3: triangle.vertex_indices = [ face.indices[0], face.indices[1], face.indices[2] ] mesh.triangles.append(triangle) for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) if not isinstance(co.meshes, list): co.meshes = [] co.meshes += [mesh] if not isinstance(co.mesh_poses, list): co.mesh_poses = [] co.mesh_poses += [pose.pose] pyassimp.release(scene) return co
def load(file): """ load resources from file using pyassimp, return list of ColorMesh """ try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list # reorganize and keep only first material properties of each for mat in scene.materials: mat.tokens = dict(reversed(list(mat.properties.items()))) # prepare mesh nodes meshes = [] for mesh in scene.meshes: mat = scene.materials[mesh.materialindex].tokens node = Node(Kd=mat.get('diffuse', (1, 1, 1)), Ka=mat.get('ambient', (0, 0, 0)), Ks=mat.get('specular', (1, 1, 1)), s=mat.get('shininess', 16.)) node.add(PhongMesh([mesh.vertices, mesh.normals], mesh.faces)) meshes.append(node) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def convert_mesh(from_filename, to_filename, library='pyassimp', binary=False): """ Convert the given file containing the original mesh to the other specified format using the `pyassimp` library. Args: from_filename (str): filename of the mesh to convert. to_filename (str): filename of the converted mesh. library (str): library to use to convert the meshes. Select between 'pyassimp' and 'trimesh'. binary (bool): if True, it will be in a binary format. This is only valid for some formats such as STL where you have the ASCII version 'stl' and the binary version 'stlb'. """ if library == 'pyassimp': scene = pyassimp.load(from_filename) extension = to_filename.split('.')[-1].lower() if binary: # for binary add 'b' as a suffix. Ex: '<file>.stlb' pyassimp.export(scene, to_filename, file_type=extension + 'b') else: pyassimp.export(scene, to_filename, file_type=extension) pyassimp.release(scene) elif library == 'trimesh': export_mesh(trimesh.load(from_filename), to_filename) else: raise NotImplementedError( "The given library '{}' is currently not supported, select between 'pyassimp' and " "'trimesh'".format(library))
def stl_to_mesh(filename, scale=(1, 1, 1)): mesh = Mesh() scene = pyassimp.load(filename) first_face = scene.meshes[0].faces[0] if hasattr(first_face, '__len__'): for face in scene.meshes[0].faces: if len(face) == 3: triangle = MeshTriangle() triangle.vertex_indices = [face[0], face[1], face[2]] mesh.triangles.append(triangle) elif hasattr(first_face, 'indices'): for face in scene.meshes[0].faces: if len(face.indices) == 3: triangle = MeshTriangle() triangle.vertex_indices = [ face.indices[0], face.indices[1], face.indices[2] ] mesh.triangles.append(triangle) else: raise MoveItCommanderException( "Unable to build triangles from mesh due to mesh object structure") for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) pyassimp.release(scene) return mesh
def main(filename=None): scene = pyassimp.load(filename, pyassimp.postprocess.aiProcess_Triangulate) #the model we load print("MODEL:" + filename) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print print("NODES:") recur_node(scene.rootnode) print print("MESHES:") for index, mesh in enumerate(scene.meshes): print(" MESH" + str(index+1)) print(" material id:" + str(mesh.materialindex+1)) print(" vertices:" + str(len(mesh.vertices))) print(" first 3 verts:\n" + str(mesh.vertices[:3])) if mesh.normals.any(): print(" first 3 normals:\n" + str(mesh.normals[:3])) else: print(" no normals") print(" colors:" + str(len(mesh.colors))) tcs = mesh.texturecoords if tcs.any(): for index, tc in enumerate(tcs): print(" texture-coords "+ str(index) + ":" + str(len(tcs[index])) + "first3:" + str(tcs[index][:3])) else: print(" no texture coordinates") print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces)) + " -> first:\n" + str(mesh.faces[:3])) print(" bones:" + str(len(mesh.bones)) + " -> first:" + str([str(b) for b in mesh.bones[:3]])) print print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print(" %s: %s" % (key, value)) print print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) # Finally release the model pyassimp.release(scene)
def main(filename=None): scene = pyassimp.load(filename, processing=pyassimp.postprocess.aiProcess_Triangulate) #the model we load print("MODEL:" + filename) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print print("NODES:") recur_node(scene.rootnode) print print("MESHES:") for index, mesh in enumerate(scene.meshes): print(" MESH" + str(index+1)) print(" material id:" + str(mesh.materialindex+1)) print(" vertices:" + str(len(mesh.vertices))) print(" first 3 verts:\n" + str(mesh.vertices[:3])) if mesh.normals.any(): print(" first 3 normals:\n" + str(mesh.normals[:3])) else: print(" no normals") print(" colors:" + str(len(mesh.colors))) tcs = mesh.texturecoords if tcs.any(): for tc_index, tc in enumerate(tcs): print(" texture-coords "+ str(tc_index) + ":" + str(len(tcs[tc_index])) + "first3:" + str(tcs[tc_index][:3])) else: print(" no texture coordinates") print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces)) + " -> first:\n" + str(mesh.faces[:3])) print(" bones:" + str(len(mesh.bones)) + " -> first:" + str([str(b) for b in mesh.bones[:3]])) print print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print(" %s: %s" % (key, value)) print print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) # Finally release the model pyassimp.release(scene)
def load_textured(file): """ load resources using pyassimp, return list of TexturedMeshes """ try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list # Note: embedded textures not supported at the moment path = os.path.dirname(file) path = os.path.join('.', '') if path == '' else path for mat in scene.materials: mat.tokens = dict(reversed(list(mat.properties.items()))) if 'file' in mat.tokens: # texture file token tname = mat.tokens['file'].split('/')[-1].split('\\')[-1] # search texture in file's whole subdir since path often screwed up tname = [ os.path.join(d[0], f) for d in os.walk(path) for f in d[2] if tname.startswith(f) or f.startswith(tname) ] if tname: mat.texture = tname[0] else: print('Failed to find texture:', tname) # prepare textured mesh meshes = [] for mesh in scene.meshes: try: texture = scene.materials[mesh.materialindex].texture # tex coords in raster order: compute 1 - y to follow OpenGL convention tex_uv = ((0, 1) + mesh.texturecoords[0][:, :2] * (1, -1) if mesh.texturecoords.size else None) # create the textured mesh object from texture, attributes, and indices meshes.append( TexturedMesh(texture, [mesh.vertices, tex_uv], mesh.faces)) except: print("Error, no texture found") mat = scene.materials[mesh.materialindex].tokens node = Node(K_d=mat.get('diffuse', (1, 1, 1)), K_a=mat.get('ambient', (0, 0, 0)), K_s=mat.get('specular', (1, 1, 1)), s=mat.get('shininess', 16.)) node.add(PhongMesh([mesh.vertices, mesh.normals], mesh.faces)) meshes.append(node) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def getSizes(scene, verbose=False): if verbose: print("Meshes") print(len(scene.meshes)) print("Vertices") print(len(scene.meshes[0].vertices)) minX = np.inf maxX = -np.inf minY = np.inf maxY = -np.inf minZ = np.inf maxZ = -np.inf for mesh in scene.meshes: for vertex in mesh.vertices: x = vertex[0] y = vertex[1] z = vertex[2] minX = challenge(x, minX, "<") maxX = challenge(x, maxX, ">") minY = challenge(y, minY, "<") maxY = challenge(y, maxY, ">") minZ = challenge(z, minZ, "<") maxZ = challenge(z, maxZ, ">") # # print maxX, minX # print maxY, minY # print maxZ, minZ # /100 to convert from cm to m width = (maxX - minX) / 100.0 height = (maxY - minY) / 100.0 depth = (maxZ - minZ) / 100.0 if verbose: print(" Min | Max ") print("X: {0: <8.2f} | {1: >8.2f}".format(minX, maxX)) print("Y: {0: <8.2f} | {1: >8.2f}".format(minY, maxY)) print("Z: {0: <8.2f} | {1: >8.2f}".format(minZ, maxZ)) print("\nSizes: {0:.2f} x {1:.2f} x {2:.2f}\n".format( width, height, depth)) # don't forget this one, or you will leak! pyassimp.release(scene) return width, height, depth
def init_all_buffers(): global vbuffer, nbuffer, ibuffer, count scene = assimp.load(fname) mesh = scene.meshes[0] assimp.release(scene) vbuffer = init_buffer(GL_ARRAY_BUFFER, scale * mesh.vertices) nbuffer = init_buffer(GL_ARRAY_BUFFER, mesh.normals) ibuffer = init_buffer(GL_ELEMENT_ARRAY_BUFFER, mesh.faces) count = len(mesh.faces.flatten())
def explore(fbx_carPath): scene = pyassimp.load(fbx_carPath) MODEL = fbx_carPath #the model we load print "MODEL:", MODEL print #write some statistics print "SCENE:" print " meshes:", len(scene.meshes) print " materials:", len(scene.materials) print " textures:", len(scene.textures) print print "MESHES:" for index, mesh in enumerate(scene.meshes): print " MESH", index + 1 print " material:", mesh.mMaterialIndex + 1 print " vertices:", len(mesh.vertices) print " first:", mesh.vertices[:3] print " colors:", len(mesh.colors) tc = mesh.texcoords print " texture-coords 1:", len(tc[0]), "first:", tc[0][:3] print " texture-coords 2:", len(tc[1]), "first:", tc[1][:3] print " texture-coords 3:", len(tc[2]), "first:", tc[2][:3] print " texture-coords 4:", len(tc[3]), "first:", tc[3][:3] print " uv-component-count:", len(mesh.mNumUVComponents) print " faces:", len( mesh.faces), "first:", [f.indices for f in mesh.faces[:3]] print " bones:", len( mesh.bones), "first:", [b.mName for b in mesh.bones[:3]] print print "MATERIALS:" for index, material in enumerate(scene.materials): print " MATERIAL", index + 1 properties = pyassimp.GetMaterialProperties(material) for key in properties: print " %s: %s" % (key, properties[key]) print print "TEXTURES:" for index, texture in enumerate(scene.textures): print " TEXTURE", index + 1 print " width:", texture.mWidth print " height:", texture.mHeight print " hint:", texture.achFormatHint print " data (size):", texture.mWidth * texture.mHeight # Finally release the model pyassimp.release(scene)
def load_model(self, path): """Load model from the specified path @param path : Location of the model in the directory """ self.__scene = pyassimp.load(path) scene = self.__scene for index, mesh in enumerate(scene.meshes): self.__prepare_gl_buffers(mesh) pyassimp.release(scene) pass
def load_textured(file, obj_name): """ load resources using pyassimp, return list of TexturedMeshes """ # try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) # except pyassimp.errors.AssimpError: # except Exception as e: # print('pyassimp unable to load', file) # print('ERROR: ', e) # # print('Is mesh triangulated?') # return [] # error reading => return empty list # Note: embedded textures not supported at the moment path = os.path.dirname(file) path = os.path.join('.', '') if path == '' else path for mat in scene.materials: mat.tokens = dict(reversed(list(mat.properties.items()))) if 'file' in mat.tokens: # texture file token tname = mat.tokens['file'].split('/')[-1].split('\\')[-1] # search texture in file's whole subdir since path often screwed up tname = [ os.path.join(d[0], f) for d in os.walk(path) for f in d[2] if tname.startswith(f) or f.startswith(tname) ] if tname: mat.texture = tname[0] else: print('Failed to find texture:', tname) # prepare textured mesh meshes = [] for mesh in scene.meshes: texture = scene.materials[mesh.materialindex].texture # tex coords in raster order: compute 1 - y to follow OpenGL convention tex_uv = ((0, 1) + mesh.texturecoords[0][:, :2] * (1, -1) if mesh.texturecoords.size else None) # create the textured mesh object from texture, attributes, and indices # TODO: currently only support single mesh objects in pose logic meshes.append( TexturedMesh(obj_name, mesh, texture, [mesh.vertices, tex_uv], mesh.faces)) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def load(file): """ load resources from file using pyassimp, return list of ColorMesh """ try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list meshes = [ColorMesh([m.vertices, m.normals], m.faces) for m in scene.meshes] size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def load_model(self,path): """Load model from the specified path @param path : Location of the model in the directory """ self.__scene = pyassimp.load(path) scene = self.__scene for index, mesh in enumerate(scene.meshes): self.__prepare_gl_buffers(mesh) pyassimp.release(scene) pass
def loadModel(self, path): scene = assimp.load( path, processing=(assimp.postprocess.aiProcess_Triangulate | assimp.postprocess.aiProcess_FlipUVs | assimp.postprocess.aiProcess_CalcTangentSpace)) if not scene: raise Exception("ASSIMP can't load model") self.directory = os.path.dirname(path) for mesh in scene.meshes: self.meshes.append(Mesh(mesh, self.directory)) assimp.release(scene)
def dumpVerticesToPickle(filenames, output_filename='all_obj.pickle'): import pyassimp vertices = np.zeros((0, ), dtype=np.float32) indices = np.zeros((len(filenames), 4), dtype=np.uint32) offset = 0 for i, file in enumerate(filenames): scene = pyassimp.load(file) mesh = scene.meshes[0] indices[i, :] = np.array((mesh.vertices.shape[0], 1, offset, 0), dtype=np.uint32) vertices = np.hstack((vertices, np.hstack( (mesh.vertices, mesh.normals)).reshape(-1))) offset += mesh.vertices.shape[0] pyassimp.release(scene) with open(output_filename, 'w') as f: pickle.dump((vertices, indices), f)
def add_model(self, name, path, texture_path=None, offset=None, color=None, parent=None, postprocess = aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model " + name + ":" + path + "...") if postprocess: scene = pyassimp.load(path, postprocess) else: scene = pyassimp.load(path) logger.info("Done.") #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) bb_min, bb_max = get_bounding_box(scene) for i in range(3): self.bb_min[i] = min(self.bb_min[i], bb_min[i]) self.bb_max[i] = max(self.bb_max[i], bb_max[i]) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) logger.info(" textures: %d" % len(scene.textures)) scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) logger.info(" mesh %d: tex coords %d, uv components %d" % (index, len(mesh.texturecoords), len(mesh.numuvcomponents))) # Finally release the model pyassimp.release(scene) # and load texture if texture_path: print "TEXTURE LOADED" texture = self.TexFromPNG(texture_path) else: texture = None logger.info("Done loading model " + name + "!") if offset is None: offset = [0,0,0,0,0,0] if color is None: color = [1.0,1.0,1.0,1.0] self.models[name] = [scene, texture, offset, parent, color, color] #second color is defualt oclor
def __enter__(self): scene = pyassimp.load(self._path) mesh = scene.meshes[0] self._vao = glGenVertexArrays(1) self._vbo = glGenBuffers(1) self._ebo = glGenBuffers(1) glBindVertexArray(self._vao) vertices = array( 'f', [component for vertex in mesh.vertices for component in vertex], ) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) glBufferData( GL_ARRAY_BUFFER, vertices.tostring(), GL_STATIC_DRAW, ) indices = array( 'L', [component for face in mesh.faces for component in face], ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._ebo) glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.tostring(), GL_STATIC_DRAW, ) self._length = len(indices) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) # free resources pyassimp.release(scene) return self._draw
def _make_mesh(self, c, scale=(1, 1, 1)): ''' This was taken from moveit commander and slightly modified. ''' filename = c.geometry.filename if pyassimp is False: raise RuntimeError( "Pyassimp needs patch https://launchpadlibrarian.net/319496602/patchPyassim.txt" ) scene = pyassimp.load(filename) if not scene.meshes or len(scene.meshes) == 0: raise MoveItCommanderException("There are no meshes in the file") if len(scene.meshes[0].faces) == 0: raise MoveItCommanderException("There are no faces in the mesh") mesh = Mesh() first_face = scene.meshes[0].faces[0] if hasattr(first_face, '__len__'): for face in scene.meshes[0].faces: if len(face) == 3: triangle = MeshTriangle() triangle.vertex_indices = [face[0], face[1], face[2]] mesh.triangles.append(triangle) elif hasattr(first_face, 'indices'): for face in scene.meshes[0].faces: if len(face.indices) == 3: triangle = MeshTriangle() triangle.vertex_indices = [ face.indices[0], face.indices[1], face.indices[2] ] mesh.triangles.append(triangle) else: raise RuntimeError( "Unable to build triangles from mesh due to mesh object structure") for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) pyassimp.release(scene) return mesh
def load_mesh(filename): """Load mesh from file and triangulate it""" try: scene = pyassimp.load(filename, processing=aiProcess_JoinIdenticalVertices | aiProcess_Triangulate) except pyassimp.AssimpError as error: raise IOError(error.message) mesh = scene.mMeshes[0].contents vertices = np.array([ _make_vector_array(mesh.mVertices[i]) for i in xrange(mesh.mNumVertices) ]) faces = np.array( [_make_face_array(mesh.mFaces[i]) for i in xrange(mesh.mNumFaces)]) pyassimp.release(scene) return Mesh(vertices, faces)
def save(self, basepath): """ Save the outline to a obj file :param str basepath: the base path of output :return: """ path = os.path.join(basepath, 'meshes') if not os.path.exists(path): os.makedirs(path) _obj_filename = os.path.join(path, '_outline_.obj') self._save_to_obj(_obj_filename, BOARD_HEIGHT) # standardize the obj file by pyassimp scene = pyassimp.load(_obj_filename) pyassimp.export(scene, os.path.join(path, 'outline.obj'), file_type='obj') pyassimp.release(scene) # compatible with Assimp 3 and 4 if os.path.isfile(os.path.join(path, 'outline.mtl')): shutil.copyfile(os.path.join(path, 'outline.mtl'), os.path.join(path, 'outline.obj.mtl'))
def read_obj(filename): scene = pyassimp.load(filename) vertices = [] faces = [] vertex_count = 0 for m in scene.meshes: f = m.faces v = m.vertices faces.append(f + vertex_count) vertices.append(v) num_vertices = v.shape[0] vertex_count += num_vertices faces = np.concatenate(faces, axis=0) vertices = np.concatenate(vertices, axis=0) fv = {'v': vertices, 'f': faces} pyassimp.release(scene) return fv
def loadModel(self, path): scene = assimp.load(path, processing=(assimp.postprocess.aiProcess_Triangulate | assimp.postprocess.aiProcess_FlipUVs | assimp.postprocess.aiProcess_CalcTangentSpace)) if not scene: raise Exception("ASSIMP can't load model") self.directory = os.path.dirname(path) for mesh in scene.meshes: self.meshes.append(Mesh(mesh, self.directory)) assimp.release(scene) # self.__processNode(scene) # # def __processNode(self, scene): # for mesh in scene.meshes: # self.meshes.append(Mesh(mesh)) # # assimp.release(scene)
def loadMesh(self, path, postprocess=None): logger.info("Loading Model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, processing=postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" metarials: %d" % len(scene.materials)) for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffer(mesh) pyassimp.release(scene)
def loadColorMesh(file): try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list meshes = [] for mesh in scene.meshes: color = scene.materials[mesh.materialindex].properties["diffuse"] # create the textured mesh object from texture, attributes, and indices meshes.append( ColorMesh([mesh.vertices, mesh.normals], color, index=mesh.faces)) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def load_model(self, path, postprocess=aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, processing=postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene # for member in dir(scene): # try: # print member + ': ' + str(getattr(scene, member)) # except AttributeError: # continue # log some statistics # print dir(scene.meshes[0]) logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) self.glize(scene, scene.rootnode) # Finally release the model pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def load_model(self, path, postprocess=aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene # log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) self.putTextures(scene.meshes, scene.materials) pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def release(self): if self.aiModel != None: imp.release(self.aiModel) for buff in self.meshBuffers: buff.delete()
def convert(self, obj, options): processing = (aiProcess_Triangulate|aiProcessPreset_TargetRealtime_MaxQuality|aiProcess_FlipUVs) if obj.GetStaticBatch(): processing = (aiProcess_Triangulate|aiProcessPreset_TargetRealtime_MaxQuality|aiProcess_FlipUVs|aiProcess_PreTransformVertices) scene = pyassimp.load(obj.GetPath( True ), processing = processing) #the model we load print print("MODEL:" + str(obj)) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print materials = [] print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") path = "" matName = "" for key, value in material.properties.items(): print(" %s: %s" % (key, value)) if key == "file": path = value elif key == "name": matName = value mat = { "id" : index+1, "file" : os.path.basename(path), "path" : path, "name" : matName, } materials.append(mat) print signals.emitNow( 'mesh.assimp_materials', materials ) print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) print("MESHES:") meshCount = len(scene.meshes) for index, mesh in enumerate(scene.meshes): if meshCount == 1: mesh.name = obj.GetExportName() else: mesh.name = "{}{}".format(obj.GetExportName(),index+1) print(" MESH id: " + str(index+1) + " (" + str(mesh.name) + ")") print(" material id: " + str(mesh.materialindex+1)) print(" vertices: " + str(len(mesh.vertices))) print(" normals: " + str(len(mesh.normals))) print(" colors: " + str(len(mesh.colors))) print(" uv channels: " + str(len(mesh.texturecoords))) print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces))) print(" bones:" + str(len(mesh.bones))) print bonesNames = [] for bone in mesh.bones: bonesNames.append(bone.name) meshDict = { 'name' : mesh.name or index, 'materialID' : mesh.materialindex+1, 'vertices' : mesh.vertices, 'verticesCount' : len(mesh.vertices), 'texturecoords' : mesh.texturecoords, 'uvcounts' : len(mesh.texturecoords), 'faces' : mesh.faces, 'facesCount' : len(mesh.faces), 'bones' : mesh.bones, 'bonesNames' : bonesNames, 'normals' : mesh.normals } signals.emitNow( 'mesh.assimp_mesh', meshDict, obj, options ) print print("NODES:") transforms = [] self.searchNode(scene.rootnode, transforms) size = obj.GetPerPixel() for tr in transforms: pos = tr['pos'] for i, v in enumerate(pos): pos[i] = v * size signals.emitNow( 'mesh.assimp_transforms', obj, transforms ) # Finally release the model pyassimp.release(scene)
def __del__(self): scene = self.scene assimp.release(scene)
def unload(self): assimp.release(self.OBJmodel)