|
| 1 | +import gzip |
| 2 | + |
| 3 | +import moderngl |
| 4 | +import numpy |
| 5 | +import trimesh |
| 6 | + |
| 7 | +from demosys.loaders.scene.base import SceneLoader |
| 8 | +from demosys.opengl.vao import VAO |
| 9 | +from demosys.resources.meta import SceneDescription |
| 10 | +from demosys.scene import Material, MaterialTexture, Mesh, Node, Scene |
| 11 | + |
| 12 | + |
| 13 | +class STLLoader(SceneLoader): |
| 14 | + file_extensions = [ |
| 15 | + ['.stl'], |
| 16 | + ['.stl', '.gz'], |
| 17 | + ] |
| 18 | + |
| 19 | + def load(self): |
| 20 | + path = self.find_scene(self.meta.path) |
| 21 | + if not path: |
| 22 | + raise ValueError("Scene '{}' not found".format(self.meta.path)) |
| 23 | + |
| 24 | + file_obj = str(path) |
| 25 | + if file_obj.endswith('.gz'): |
| 26 | + file_obj = gzip.GzipFile(file_obj) |
| 27 | + |
| 28 | + stl_mesh = trimesh.load(file_obj, file_type='stl') |
| 29 | + scene = Scene(self.meta.resolved_path) |
| 30 | + scene_mesh = Mesh("mesh") |
| 31 | + scene_mesh.material = Material("default") |
| 32 | + |
| 33 | + vao = VAO("mesh", mode=moderngl.TRIANGLES) |
| 34 | + vao.buffer(numpy.array(stl_mesh.vertices, dtype='f4'), '3f', ['in_position']) |
| 35 | + vao.buffer(numpy.array(stl_mesh.vertex_normals, dtype='f4'), '3f', ['in_normal']) |
| 36 | + vao.index_buffer(numpy.array(stl_mesh.faces, dtype='u4')) |
| 37 | + scene_mesh.vao = vao |
| 38 | + scene_mesh.add_attribute('POSITION', 'in_position', 3) |
| 39 | + scene_mesh.add_attribute('NORMAL', 'in_normal', 3) |
| 40 | + |
| 41 | + scene.meshes.append(scene_mesh) |
| 42 | + scene.root_nodes.append(Node(mesh=scene_mesh)) |
| 43 | + scene.prepare() |
| 44 | + |
| 45 | + return scene |
0 commit comments