def test_remove_all_duplicate_polygons(): data = numpy.zeros(5, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) data['vectors'][1] = numpy.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]]) data['vectors'][2] = numpy.array([[2, 0, 0], [0, 0, 0], [0, 0, 0]]) data['vectors'][3] = numpy.array([[3, 0, 0], [0, 0, 0], [0, 0, 0]]) data['vectors'][4] = numpy.array([[3, 0, 0], [0, 0, 0], [0, 0, 0]]) mesh = Mesh(data, remove_duplicate_polygons=False) assert mesh.data.size == 5 Mesh.remove_duplicate_polygons(mesh.data, RemoveDuplicates.NONE) mesh = Mesh(data, remove_duplicate_polygons=RemoveDuplicates.ALL) assert mesh.data.size == 3 assert (mesh.vectors[0] == numpy.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])).all() assert (mesh.vectors[1] == numpy.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]])).all() assert (mesh.vectors[2] == numpy.array([[2, 0, 0], [0, 0, 0], [0, 0, 0]])).all()
def test_empty_areas(): data = numpy.zeros(3, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]]) data['vectors'][1] = numpy.array([[1, 0, 0], [0, 1, 0], [1, 0, 0]]) data['vectors'][2] = numpy.array([[1, 0, 0], [0, 1, 0], [1, 0, 0]]) mesh = Mesh(data, calculate_normals=False, remove_empty_areas=False) assert mesh.data.size == 3 # Test the normals recalculation which also calculates the areas by default mesh.areas[1] = 1 mesh.areas[2] = 2 assert numpy.allclose(mesh.areas, [[0.5], [1.0], [2.0]]) mesh.update_normals(update_areas=False) assert numpy.allclose(mesh.areas, [[0.5], [1.0], [2.0]]) mesh.update_normals(update_areas=True) assert numpy.allclose(mesh.areas, [[0.5], [0.0], [0.0]]) mesh = Mesh(data, remove_empty_areas=True) assert mesh.data.size == 1
def gen_stl(self): vertices = [] faces = [] for l in self.lines: for v in l: vertices.append(v) faces = [] for n, l in enumerate(self.lines[:-1]): for i, p in enumerate(l[:-1]): p0 = self.index(n, i) p1 = self.index(n, i + 1) p2 = self.index(n + 1, i) faces.append([p1, p0, p2]) p0 = self.index(n + 1, i) p1 = self.index(n + 1, i + 1) p2 = self.index(n, i + 1) faces.append([p0, p1, p2]) vertices = np.array(vertices) faces = np.array(faces) cube = Mesh( np.zeros(faces.shape[0], dtype=Mesh.dtype), remove_duplicate_polygons=RemoveDuplicates.NONE, ) for i, f in enumerate(faces): for j in range(3): cube.vectors[i][j] = vertices[f[j], :] return cube
def create_figure(path_dict, figure_path, path_dict2=None, pair_mapping=None, transp_backg=False): assert ((path_dict2 is None) + (pair_mapping is None)) != 1, \ 'please specify all kwargs or none of them' if pair_mapping is not None: # for k in tqdm(pair_mapping): # mesh= Mesh.from_file(path_dict[k[0]]) # mesh2 = Mesh.from_file(path_dict2[k[1]]) for k, values in tqdm(pair_mapping.items()): mesh = Mesh.from_file(path_dict[k]) mesh = _add_normalizing_vector_point(mesh, 300, -300) fig = vpl.figure() fig.background_color = 'black' vpl.mesh_plot(mesh, color='pink', opacity=0.3) #make dendrite translucent for v in values: # add second, third,.. .stl to same plot mesh2 = Mesh.from_file(path_dict2[str(v)]) vpl.mesh_plot(mesh2) save_path = figure_path + str(k) + '.png' vpl.save_fig( save_path, magnification=5, off_screen=True, ) if transp_backg == True: #make black background transparent _transparent_background(save_path) fig.close() else: for k in tqdm(path_dict): # Read the STL using numpy-stl mesh = Mesh.from_file(path_dict[k]) if debug == True: mesh = _add_normalizing_vector_point(mesh, 300, -300) fig = vpl.figure() fig.background_color = 'black' vpl.mesh_plot(mesh) save_path = figure_path + str(k) + '.png' vpl.save_fig( save_path, magnification=5, off_screen=True, ) if transp_backg == True: #make black background transparent _transparent_background(save_path) fig.close()
def build_stl(name, points): ''' Given a set point points, make a STL file of the convex hull. ''' points = np.array(points) points -= np.min(points, axis=0) # Move bound to origin hull = ConvexHull(points) shape = Mesh(np.zeros(len(hull.vertices), dtype=Mesh.dtype)) for i, vertex in enumerate(hull.vertices): shape.vectors[i] = hull.points[vertex][::-1] # Turn it inside out size = np.max(hull.points, axis=0) return shape, size
def gen_stl(self, fname): vertices = [] faces = [] cube = Mesh( np.concatenate([b.gen_stl().data.copy() for b in self.blocks]), remove_duplicate_polygons=RemoveDuplicates.NONE, ) cube.save(fname)
def test_units_1d(): data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [2, 0, 0]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert mesh.areas == 0 assert (mesh.normals == [0, 0, 0]).all() assert (mesh.units == [0, 0, 0]).all()
def test_rotation_over_point(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) mesh.rotate([1, 0, 0], math.radians(180), point=[1, 2, 3]) utils.array_equals( mesh.vectors, numpy.array([[[1., 4., 6.], [0., 3., 6.], [0., 4., 5.]]])) mesh.rotate([1, 0, 0], math.radians(-180), point=[1, 2, 3]) utils.array_equals( mesh.vectors, numpy.array([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]])) mesh.rotate([1, 0, 0], math.radians(180), point=0.0) utils.array_equals( mesh.vectors, numpy.array([[[1., 0., -0.], [0., -1., -0.], [0., 0., -1.]]])) with pytest.raises(TypeError): mesh.rotate([1, 0, 0], math.radians(180), point='x')
def test_units_1d(): data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [2, 0, 0]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert mesh.areas == 0 utils.array_equals(mesh.normals, [0, 0, 0]) utils.array_equals(mesh.units, [0, 0, 0]) utils.array_equals(mesh.get_unit_normals(), [0, 0, 0])
def test_empty_areas(): data = numpy.zeros(3, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]]) data['vectors'][1] = numpy.array([[1, 0, 0], [0, 1, 0], [1, 0, 0]]) data['vectors'][2] = numpy.array([[1, 0, 0], [0, 1, 0], [1, 0, 0]]) mesh = Mesh(data, remove_empty_areas=False) assert mesh.data.size == 3 mesh = Mesh(data, remove_empty_areas=True) assert mesh.data.size == 1
def test_units_2d(): data = numpy.zeros(2, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]]) data['vectors'][1] = numpy.array([[1, 0, 0], [0, 1, 0], [1, 1, 0]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert numpy.allclose(mesh.areas, [.5, .5]) assert numpy.allclose(mesh.normals, [[0, 0, 1.], [0, 0, -1.]]) assert numpy.allclose(mesh.units, [[0, 0, 1], [0, 0, -1]])
def test_units_3d(): data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 1.]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert (mesh.areas - 2 ** .5) < 0.0001 assert numpy.allclose(mesh.normals, [0.0, -0.70710677, 0.70710677]) assert numpy.allclose(mesh.units[0], [0.0, -0.5, 0.5])
def test_remove_all_duplicate_polygons(): mesh = Mesh(your_mesh, remove_duplicate_polygons=False) assert mesh.data.size == 9 Mesh.remove_duplicate_polygons(mesh.data, RemoveDuplicates.NONE) mesh = Mesh(your_mesh, remove_duplicate_polygons=RemoveDuplicates.ALL) assert mesh.data.size == 9 assert (your_mesh.points[0][0:3] == your_mesh.v0[0]).all() assert (your_mesh.points[0][3:6] == your_mesh.v1[0]).all() assert (your_mesh.points[0][6:9] == your_mesh.v2[0]).all()
def test_rotation(): # Create 6 faces of a cube data = numpy.zeros(6, dtype=Mesh.dtype) # Top of the cube data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) data['vectors'][1] = numpy.array([[1, 0, 1], [0, 1, 1], [1, 1, 1]]) # Right face data['vectors'][2] = numpy.array([[1, 0, 0], [1, 0, 1], [1, 1, 0]]) data['vectors'][3] = numpy.array([[1, 1, 1], [1, 0, 1], [1, 1, 0]]) # Left face data['vectors'][4] = numpy.array([[0, 0, 0], [1, 0, 0], [1, 0, 1]]) data['vectors'][5] = numpy.array([[0, 0, 0], [0, 0, 1], [1, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) # Since the cube faces are from 0 to 1 we can move it to the middle by # substracting .5 data['vectors'] -= .5 # Rotate 90 degrees over the X axis followed by the Y axis followed by the # X axis mesh.rotate([0.5, 0.0, 0.0], math.radians(90)) mesh.rotate([0.0, 0.5, 0.0], math.radians(90)) mesh.rotate([0.5, 0.0, 0.0], math.radians(90)) # Since the cube faces are from 0 to 1 we can move it to the middle by # substracting .5 data['vectors'] += .5 # We use a slightly higher absolute tolerance here, for ppc64le # https://github.com/WoLpH/numpy-stl/issues/78 assert numpy.allclose(mesh.vectors, numpy.array([ [[1, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 1, 0], [1, 0, 0], [1, 1, 0]], [[0, 1, 1], [0, 1, 0], [1, 1, 1]], [[1, 1, 0], [0, 1, 0], [1, 1, 1]], [[0, 0, 1], [0, 1, 1], [0, 1, 0]], [[0, 0, 1], [0, 0, 0], [0, 1, 0]], ]), atol=1e-07)
def test_translation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert numpy.allclose(mesh.vectors, numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])) # Translate mesh with vector [1, 2, 3] mesh.translate([1.0, 2.0, 3.0]) assert numpy.allclose(mesh.vectors, numpy.array([[[1, 3, 4], [2, 2, 4], [1, 2, 4]]]))
def test_no_translation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Translate mesh with a zero vector mesh.translate([0.0, 0.0, 0.0]) assert (mesh.vectors == numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all()
def test_rotation_over_point(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) mesh.rotate([1, 0, 0], math.radians(180), point=[1, 2, 3]) assert (mesh.vectors == numpy.array([[1, -4, -6], [0, -5, -6], [0, -4, -7]])).all()
def test_rotation(): # Create 6 faces of a cube data = numpy.zeros(6, dtype=Mesh.dtype) # Top of the cube data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) data['vectors'][1] = numpy.array([[1, 0, 1], [0, 1, 1], [1, 1, 1]]) # Right face data['vectors'][2] = numpy.array([[1, 0, 0], [1, 0, 1], [1, 1, 0]]) data['vectors'][3] = numpy.array([[1, 1, 1], [1, 0, 1], [1, 1, 0]]) # Left face data['vectors'][4] = numpy.array([[0, 0, 0], [1, 0, 0], [1, 0, 1]]) data['vectors'][5] = numpy.array([[0, 0, 0], [0, 0, 1], [1, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) # Since the cube faces are from 0 to 1 we can move it to the middle by # substracting .5 data['vectors'] -= .5 # Rotate 90 degrees over the X axis followed by the Y axis followed by the # X axis mesh.rotate([0.5, 0.0, 0.0], math.radians(90)) mesh.rotate([0.0, 0.5, 0.0], math.radians(90)) mesh.rotate([0.5, 0.0, 0.0], math.radians(90)) # Since the cube faces are from 0 to 1 we can move it to the middle by # substracting .5 data['vectors'] += .5 assert (mesh.vectors == numpy.array([ [[1, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 1, 0], [1, 0, 0], [1, 1, 0]], [[0, 1, 1], [0, 1, 0], [1, 1, 1]], [[1, 1, 0], [0, 1, 0], [1, 1, 1]], [[0, 0, 1], [0, 1, 1], [0, 1, 0]], [[0, 0, 1], [0, 0, 0], [0, 1, 0]], ])).all()
def test_no_transformation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Transform mesh with identity matrix mesh.transform(numpy.eye(4)) assert (mesh.vectors == numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() assert numpy.all(mesh.areas == 0.5)
def test_translation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert numpy.allclose(mesh.vectors, numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])) # Translate mesh with vector [1, 2, 3] mesh.translate([1.0, 2.0, 3.0]) assert numpy.allclose(mesh.vectors, numpy.array([ [[1, 3, 4], [2, 2, 4], [1, 2, 4]]]))
def test_no_translation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Translate mesh with a zero vector mesh.translate([0.0, 0.0, 0.0]) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all()
def test_units_3d(): data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 1.]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert (mesh.areas - 2**.5) < 0.0001 assert (mesh.normals == [0, -1, 1]).all() units = mesh.units[0] assert units[0] == 0 # Due to floating point errors assert (units[1] + .5 * 2**.5) < 0.0001 assert (units[2] - .5 * 2**.5) < 0.0001
def test_double_rotation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) rotation_matrix = mesh.rotation_matrix([1, 0, 0], math.radians(180)) combined_rotation_matrix = numpy.dot(rotation_matrix, rotation_matrix) mesh.rotate_using_matrix(combined_rotation_matrix) utils.array_equals( mesh.vectors, numpy.array([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]]))
def create_ctm(zip): """ Convert an uploaded model file to a ctm file """ app.logger.warn('create ctm from zip') if not zip: return None app.logger.warn('extract zip') with ZipFile(zip.getAbsolutePath(), 'r', ZIP_DEFLATED) as zipFile: uploadFileName = zipFile.infolist()[0].filename app.logger.warn('read zip file') uploadFileData = zipFile.read(uploadFileName) filename, fileExt = os.path.splitext(uploadFileName) with tempfile.NamedTemporaryFile(suffix=fileExt) as uploadFile: app.logger.warn('created temp file, now write') uploadFile.write(uploadFileData) # Convert to bin if ascii uploadFile.seek(0) if uploadFile.read(5) == b'solid': app.logger.warn('Solid Ascii, convert to binary') Mesh.from_file(uploadFile.name).save(uploadFile.name) # Convert to ctm in uploads storage ctmFile = File.fromName(filename + '.ctm') ctmFile.mime_type = 'application/octet-stream' app.logger.warn('run ctm conv') ctmConvert = subprocess.run( ["ctmconv", uploadFile.name, ctmFile.getAbsolutePath()], stderr=subprocess.PIPE) if ctmConvert.returncode > 0: # TODO: Deal with this error properly app.logger.error(ctmConvert.stderr) app.logger.warn('ctm conv done, set size') ctmFile.size = os.stat(ctmFile.getAbsolutePath()).st_size app.logger.warn('ctmCreated') return ctmFile
def test_mesh(self): import time fig = vpl.gcf() path = vpl.data.get_rabbit_stl() _mesh = Mesh.from_file(path) self = vpl.mesh_plot(_mesh.vectors) fig.show(False) t0 = time.time() for i in range(100): # self.color = np.random.random(3) # print(self.color) self.set_tri_scalars((_mesh.x[:, 0] + 3 * i) % 20) _mesh.rotate(np.ones(3), .1, np.mean(_mesh.vectors, (0, 1))) fig.update() self.update_points() # time.sleep(.01) if (time.time() - t0) > 1: break fig.show()
def test_no_transformation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Transform mesh with identity matrix mesh.transform(numpy.eye(4)) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() assert numpy.all(mesh.areas == 0.5)
def test_no_rotation(): # Create 3 faces of a cube data = numpy.zeros(3, dtype=Mesh.dtype) # Top of the cube data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) # Rotate by 0 degrees mesh.rotate([0.5, 0.0, 0.0], math.radians(0)) # Use a zero rotation matrix mesh.rotate([0.0, 0.0, 0.0], math.radians(90))
def toSTL(self): """ Exports the current laminate as an STL file """ from stl.mesh import Mesh #Requires numpy-stl layerdef = self.layerdef laminate_verts = [] for layer in layerdef.layers: shapes = self.geoms[layer] #TODO Add it in for other shapes zvalue = layerdef.z_values[layer] thickness = layer.thickness if (len(shapes) == 0): #In case there are no shapes. print("No shapes skipping") continue for s in shapes: shape_verts = s.extrudeVertices(thickness, z0=zvalue) laminate_verts.extend(shape_verts) laminate_verts = [ point / popupcad.SI_length_scaling for point in laminate_verts ] # Or creating a new mesh (make sure not to overwrite the `mesh` import by # naming it `mesh`): VERTICE_COUNT = len(laminate_verts) // 3 #Number of verticies data = numpy.zeros( VERTICE_COUNT, dtype=Mesh.dtype ) #We create an array full of zeroes. Will edit it later. #Creates a mesh from the specified set of points for dtype, points in zip(data, numpy.array(laminate_verts).reshape(-1, 9)): points = points.reshape(-1, 3) #Splits each triangle into points numpy.copyto(dtype[1], points) #Copies the list of points into verticies index data = Mesh.remove_duplicate_polygons(data) #This constructs the mesh objects, generates the normals and all your_mesh = Mesh(data, remove_empty_areas=True) filename = str(self.id) + '.stl' old_path = os.getcwd() #Save old directory new_path = popupcad.exportdir + os.path.sep #Load export directory os.chdir(new_path) #Change to export directory print("Saving in " + str(new_path)) your_mesh.save(filename) #Apparently save does not like absolute paths print(filename + " has been saved") os.chdir(old_path) #Change back to old directory
def test_transformation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([[[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Transform mesh with identity matrix tr = numpy.zeros((4, 4)) tr[0:3, 0:3] = Mesh.rotation_matrix([0, 0, 1], 0.5 * numpy.pi) tr[0:3, 3] = [1, 2, 3] mesh.transform(tr) assert (mesh.vectors == numpy.array([[[0, 2, 4], [1, 3, 4], [1, 2, 4]]])).all() assert numpy.all(mesh.areas == 0.5)
def dimensions(infile): """Accepts a 3D mesh file as infile, and returns the x,y,z dimensions of the object in mm""" mesh = Mesh.from_file(infile) return [ float(mesh.x.max()) - float(mesh.x.min()), float(mesh.y.max()) - float(mesh.y.min()), float(mesh.z.max()) - float(mesh.z.min()) ]
def test_units_3d(): data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 1.]]) mesh = Mesh(data, remove_empty_areas=False) mesh.update_units() assert (mesh.areas - 2 ** .5) < 0.0001 assert (mesh.normals == [0, -1, 1]).all() units = mesh.units[0] assert units[0] == 0 # Due to floating point errors assert (units[1] + .5 * 2 ** .5) < 0.0001 assert (units[2] - .5 * 2 ** .5) < 0.0001
def generate_thumbnail(infile, outfile, size=None): """Generate a thumbnail or previewfile into 'outfile' using the design file in 'infile'""" mesh = Mesh.from_file(infile) vpl.mesh_plot(mesh) # Front of design and slightly up vpl.view(camera_position=[0, -1, 0.5]) vpl.save_fig(outfile, pixels=size or [1280, 1280], off_screen=True)
def test_doc_03(self): import vtkplotlib as vpl from stl.mesh import Mesh mesh = Mesh.from_file(vpl.data.get_rabbit_stl()) vertices = mesh.vectors vpl.plot(vertices, join_ends=True, color="dark red")
def set_from_path(self, path, ignore_numpystl=False): # Ideally let numpy-stl open the file if it is installed. if NUMPY_STL_AVAILABLE and not ignore_numpystl: self.vectors = NumpyMesh.from_file(path).vectors return # Otherwise try vtk's STL reader - however it's not as reliable. self.polydata = vtk_read_stl(path) self.connect()
def test(): from stl.mesh import Mesh import vtkplotlib as vpl mesh = Mesh.from_file(vpl.data.get_rabbit_stl()) plot = vpl.mesh_plot(mesh, scalars=mesh.x) vpl.scalar_bar(plot) vpl.show()
def test_no_rotation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) # Rotate by 0 degrees mesh.rotate([0.5, 0.0, 0.0], math.radians(0)) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Use a zero rotation matrix mesh.rotate([0.0, 0.0, 0.0], math.radians(90)) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all()
def test_transformation(): # Create a single face data = numpy.zeros(1, dtype=Mesh.dtype) data['vectors'][0] = numpy.array([[0, 1, 1], [1, 0, 1], [0, 0, 1]]) mesh = Mesh(data, remove_empty_areas=False) assert (mesh.vectors == numpy.array([ [[0, 1, 1], [1, 0, 1], [0, 0, 1]]])).all() # Transform mesh with identity matrix tr = numpy.zeros((4, 4)) tr[0:3, 0:3] = Mesh.rotation_matrix([0, 0, 1], 0.5 * numpy.pi) tr[0:3, 3] = [1, 2, 3] mesh.transform(tr) assert (mesh.vectors == numpy.array([ [[0, 2, 4], [1, 3, 4], [1, 2, 4]]])).all() assert numpy.all(mesh.areas == 0.5)
def toSTL(self): """ Exports the current laminate as an STL file """ from stl.mesh import Mesh #Requires numpy-stl layerdef = self.layerdef laminate_verts = [] for layer in layerdef.layers: shapes = self.geoms[layer]#TODO Add it in for other shapes zvalue = layerdef.zvalue[layer] thickness = layer.thickness if (len(shapes) == 0) : #In case there are no shapes. print("No shapes skipping") continue for s in shapes: shape_verts = s.extrudeVertices(thickness, z0=zvalue) laminate_verts.extend(shape_verts) laminate_verts = [point/popupcad.SI_length_scaling for point in laminate_verts] # Or creating a new mesh (make sure not to overwrite the `mesh` import by # naming it `mesh`): VERTICE_COUNT = len(laminate_verts)//3 #Number of verticies data = numpy.zeros(VERTICE_COUNT, dtype=Mesh.dtype) #We create an array full of zeroes. Will edit it later. #Creates a mesh from the specified set of points for dtype, points in zip(data, numpy.array(laminate_verts).reshape(-1,9)): points = points.reshape(-1, 3) #Splits each triangle into points numpy.copyto(dtype[1], points) #Copies the list of points into verticies index data = Mesh.remove_duplicate_polygons(data) #This constructs the mesh objects, generates the normals and all your_mesh = Mesh(data, remove_empty_areas=True) filename = str(self.id) + '.stl' old_path = os.getcwd() #Save old directory new_path = popupcad.exportdir + os.path.sep #Load export directory os.chdir(new_path) #Change to export directory print("Saving in " + str(new_path)) your_mesh.save(filename)#Apparently save does not like absolute paths print(filename + " has been saved") os.chdir(old_path) #Change back to old directory
def _add_normalizing_vector_point(mesh, minpt, maxpt): """ This function allows you to visualize all meshes in their size relative to each other It is a quick simple hack: by adding 2 vector points at the same x coordinates at the extreme left and extreme right of the largest .stl mesh, all the meshes are displayed with the same scale. input: [mesh], minpoint coordinates, maxpoint coordinates output: [mesh] with 2 added coordinate points """ newmesh = Mesh(np.zeros(mesh.vectors.shape[0] + 2, dtype=Mesh.dtype)) # newmesh.vectors = np.vstack([mesh.vectors, # np.array([ [[0,maxpt,0], [0,maxpt,0], [0,maxpt,0]], # [[0,minpt,0], [0,minpt,0], [0,minpt,0]] ], float) ]) newmesh.vectors = np.vstack([ mesh.vectors, np.array([[[0, 0, maxpt], [0, 0, maxpt], [0, 0, maxpt]], [[0, 0, minpt], [0, 0, minpt], [0, 0, minpt]]], float) ]) return newmesh
def test_doc_05(self): import vtkplotlib as vpl from stl.mesh import Mesh # path = "if you have an STL file then put it's path here." # Otherwise vtkplotlib comes with a small STL file for demos/testing. path = vpl.data.get_rabbit_stl() # Read the STL using numpy-stl mesh = Mesh.from_file(path) # Plot the mesh vpl.mesh_plot(mesh)
def load(self, scene, filename): #open zipfile with ZipFile(filename, 'r') as openedZipfile: tree = ET.fromstring(openedZipfile.read(self.xmlFilename)) version = tree.find('version').text if self.get_version() == version: logging.debug( "Ano, soubor je stejna verze jako knihovna pro jeho nacitani. Pokracujeme" ) else: logging.debug("Problem, tuto verzi neumim nacitat.") return False models = tree.find('models') models_data = [] for model in models.findall('model'): model_data = {} model_data['file_name'] = model.get('name') model_data['normalization'] = ast.literal_eval( model.find('normalization').text) model_data['position'] = ast.literal_eval( model.find('position').text) model_data['rotation'] = ast.literal_eval( model.find('rotation').text) model_data['scale'] = ast.literal_eval( model.find('scale').text) models_data.append(model_data) #scene.models = [] for m in models_data: logging.debug("Jmeno souboru je: " + m['file_name']) tmp = scene.controller.app_config.tmp_place model_filename = tmp + m['file_name'] openedZipfile.extract(m['file_name'], tmp) mesh = Mesh.from_file(filename=model_filename) os.remove(model_filename) #mesh = Mesh.from_file(filename="", fh=openedZipfile.open(m['file_name'])) model = ModelTypeStl.load_from_mesh( mesh, filename=m['file_name'], normalize=not m['normalization']) model.rot = numpy.array(m['rotation']) model.pos = numpy.array(m['position']) model.pos *= 0.1 model.scale = numpy.array(m['scale']) model.update_min_max() model.parent = scene scene.models.append(model)
def get_stl_object(obj): name, data = Mesh.load(obj) return Mesh(data, calculate_normals=True, name=name)
def get_stl_object_by_name(file_name): return Mesh.from_file(file_name)