本文整理汇总了Python中UM.Mesh.MeshBuilder.MeshBuilder.calculateNormals方法的典型用法代码示例。如果您正苦于以下问题:Python MeshBuilder.calculateNormals方法的具体用法?Python MeshBuilder.calculateNormals怎么用?Python MeshBuilder.calculateNormals使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UM.Mesh.MeshBuilder.MeshBuilder
的用法示例。
在下文中一共展示了MeshBuilder.calculateNormals方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_render
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def test_render():
mocked_shader = MagicMock()
with patch("UM.View.GL.OpenGL.OpenGL.getInstance"):
render_batch = RenderBatch(mocked_shader)
# Render without a camera shouldn't cause any effect.
render_batch.render(None)
assert mocked_shader.bind.call_count == 0
# Rendering with a camera should cause the shader to be bound and released (even if the batch is empty)
mocked_camera = MagicMock()
mocked_camera.getWorldTransformation = MagicMock(return_value = Matrix())
mocked_camera.getViewProjectionMatrix = MagicMock(return_value=Matrix())
with patch("UM.View.GL.OpenGLContext.OpenGLContext.properties"):
render_batch.render(mocked_camera)
assert mocked_shader.bind.call_count == 1
assert mocked_shader.release.call_count == 1
# Actualy render with an item in the batch
mb = MeshBuilder()
mb.addPyramid(10, 10, 10, color=Color(0.0, 1.0, 0.0, 1.0))
mb.calculateNormals()
mesh_data = mb.build()
render_batch.addItem(Matrix(), mesh_data, {})
with patch("UM.View.GL.OpenGL.OpenGL.getInstance"):
with patch("UM.View.GL.OpenGLContext.OpenGLContext.properties"):
render_batch.render(mocked_camera)
assert mocked_shader.bind.call_count == 2
assert mocked_shader.release.call_count == 2
示例2: read
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def read(self, file_name):
mesh_builder = MeshBuilder()
scene_node = SceneNode()
if use_numpystl:
self._loadWithNumpySTL(file_name, mesh_builder)
else:
f = open(file_name, "rb")
if not self._loadBinary(mesh_builder, f):
f.close()
f = open(file_name, "rt")
try:
self._loadAscii(mesh_builder, f)
except UnicodeDecodeError:
return None
f.close()
Job.yieldThread() # Yield somewhat to ensure the GUI has time to update a bit.
mesh_builder.calculateNormals(fast = True)
mesh = mesh_builder.build()
Logger.log("d", "Loaded a mesh with %s vertices", mesh_builder.getVertexCount())
scene_node.setMeshData(mesh)
return scene_node
示例3: read
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def read(self, file_name):
try:
self.defs = {}
self.shapes = []
tree = ET.parse(file_name)
xml_root = tree.getroot()
if xml_root.tag != "X3D":
return None
scale = 1000 # Default X3D unit it one meter, while Cura's is one millimeters
if xml_root[0].tag == "head":
for head_node in xml_root[0]:
if head_node.tag == "unit" and head_node.attrib.get("category") == "length":
scale *= float(head_node.attrib["conversionFactor"])
break
xml_scene = xml_root[1]
else:
xml_scene = xml_root[0]
if xml_scene.tag != "Scene":
return None
self.transform = Matrix()
self.transform.setByScaleFactor(scale)
self.index_base = 0
# Traverse the scene tree, populate the shapes list
self.processChildNodes(xml_scene)
if self.shapes:
builder = MeshBuilder()
builder.setVertices(numpy.concatenate([shape.verts for shape in self.shapes]))
builder.setIndices(numpy.concatenate([shape.faces for shape in self.shapes]))
builder.calculateNormals()
builder.setFileName(file_name)
mesh_data = builder.build()
# Manually try and get the extents of the mesh_data. This should prevent nasty NaN issues from
# leaving the reader.
mesh_data.getExtents()
node = SceneNode()
node.setMeshData(mesh_data)
node.setSelectable(True)
node.setName(file_name)
else:
return None
except Exception:
Logger.logException("e", "Exception in X3D reader")
return None
return node
示例4: test_readBinary
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def test_readBinary(application):
reader = STLReader.STLReader()
binary_path = os.path.join(test_path, "simpleTestCubeBinary.stl")
result = reader.read(binary_path)
if STLReader.use_numpystl:
# If the system the test runs on supporst numpy stl, we should also check the non numpy stl option.
f = open(binary_path, "rb")
mesh_builder = MeshBuilder()
reader._loadBinary(mesh_builder, f)
mesh_builder.calculateNormals(fast=True)
assert mesh_builder.getVertexCount() != 0
assert result
示例5: test_readASCII
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def test_readASCII(application):
reader = STLReader.STLReader()
ascii_path = os.path.join(test_path, "simpleTestCubeASCII.stl")
result = reader.read(ascii_path)
assert result
if STLReader.use_numpystl:
# If the system the test runs on supports numpy stl, we should also check the non numpy stl option.
f = open(ascii_path, "rt", encoding = "utf-8")
mesh_builder = MeshBuilder()
reader._loadAscii(mesh_builder, f)
mesh_builder.calculateNormals(fast=True)
assert mesh_builder.getVertexCount() != 0
示例6: _createCube
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def _createCube(self, size):
mesh = MeshBuilder()
# Can't use MeshBuilder.addCube() because that does not get per-vertex normals
# Per-vertex normals require duplication of vertices
s = size / 2
verts = [ # 6 faces with 4 corners each
[-s, -s, s], [-s, s, s], [ s, s, s], [ s, -s, s],
[-s, s, -s], [-s, -s, -s], [ s, -s, -s], [ s, s, -s],
[ s, -s, -s], [-s, -s, -s], [-s, -s, s], [ s, -s, s],
[-s, s, -s], [ s, s, -s], [ s, s, s], [-s, s, s],
[-s, -s, s], [-s, -s, -s], [-s, s, -s], [-s, s, s],
[ s, -s, -s], [ s, -s, s], [ s, s, s], [ s, s, -s]
]
mesh.setVertices(numpy.asarray(verts, dtype=numpy.float32))
indices = []
for i in range(0, 24, 4): # All 6 quads (12 triangles)
indices.append([i, i+2, i+1])
indices.append([i, i+3, i+2])
mesh.setIndices(numpy.asarray(indices, dtype=numpy.int32))
mesh.calculateNormals()
return mesh
示例7: _convertSavitarNodeToUMNode
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def _convertSavitarNodeToUMNode(self, savitar_node):
self._object_count += 1
node_name = "Object %s" % self._object_count
active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
um_node = CuraSceneNode() # This adds a SettingOverrideDecorator
um_node.addDecorator(BuildPlateDecorator(active_build_plate))
um_node.setName(node_name)
transformation = self._createMatrixFromTransformationString(savitar_node.getTransformation())
um_node.setTransformation(transformation)
mesh_builder = MeshBuilder()
data = numpy.fromstring(savitar_node.getMeshData().getFlatVerticesAsBytes(), dtype=numpy.float32)
vertices = numpy.resize(data, (int(data.size / 3), 3))
mesh_builder.setVertices(vertices)
mesh_builder.calculateNormals(fast=True)
mesh_data = mesh_builder.build()
if len(mesh_data.getVertices()):
um_node.setMeshData(mesh_data)
for child in savitar_node.getChildren():
child_node = self._convertSavitarNodeToUMNode(child)
if child_node:
um_node.addChild(child_node)
if um_node.getMeshData() is None and len(um_node.getChildren()) == 0:
return None
settings = savitar_node.getSettings()
# Add the setting override decorator, so we can add settings to this node.
if settings:
global_container_stack = Application.getInstance().getGlobalContainerStack()
# Ensure the correct next container for the SettingOverride decorator is set.
if global_container_stack:
default_stack = ExtruderManager.getInstance().getExtruderStack(0)
if default_stack:
um_node.callDecoration("setActiveExtruder", default_stack.getId())
# Get the definition & set it
definition_id = getMachineDefinitionIDForQualitySearch(global_container_stack.definition)
um_node.callDecoration("getStack").getTop().setDefinition(definition_id)
setting_container = um_node.callDecoration("getStack").getTop()
for key in settings:
setting_value = settings[key]
# Extruder_nr is a special case.
if key == "extruder_nr":
extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
if extruder_stack:
um_node.callDecoration("setActiveExtruder", extruder_stack.getId())
else:
Logger.log("w", "Unable to find extruder in position %s", setting_value)
continue
setting_container.setProperty(key, "value", setting_value)
if len(um_node.getChildren()) > 0 and um_node.getMeshData() is None:
group_decorator = GroupDecorator()
um_node.addDecorator(group_decorator)
um_node.setSelectable(True)
if um_node.getMeshData():
# Assuming that all nodes with mesh data are printable objects
# affects (auto) slicing
sliceable_decorator = SliceableObjectDecorator()
um_node.addDecorator(sliceable_decorator)
return um_node
示例8: read
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def read(self, file_name):
result = SceneNode()
# The base object of 3mf is a zipped archive.
archive = zipfile.ZipFile(file_name, "r")
try:
root = ET.parse(archive.open("3D/3dmodel.model"))
# There can be multiple objects, try to load all of them.
objects = root.findall("./3mf:resources/3mf:object", self._namespaces)
if len(objects) == 0:
Logger.log("w", "No objects found in 3MF file %s, either the file is corrupt or you are using an outdated format", file_name)
return None
for entry in objects:
mesh_builder = MeshBuilder()
node = SceneNode()
vertex_list = []
#for vertex in entry.mesh.vertices.vertex:
for vertex in entry.findall(".//3mf:vertex", self._namespaces):
vertex_list.append([vertex.get("x"), vertex.get("y"), vertex.get("z")])
Job.yieldThread()
triangles = entry.findall(".//3mf:triangle", self._namespaces)
mesh_builder.reserveFaceCount(len(triangles))
#for triangle in object.mesh.triangles.triangle:
for triangle in triangles:
v1 = int(triangle.get("v1"))
v2 = int(triangle.get("v2"))
v3 = int(triangle.get("v3"))
mesh_builder.addFaceByPoints(vertex_list[v1][0], vertex_list[v1][1], vertex_list[v1][2],
vertex_list[v2][0], vertex_list[v2][1], vertex_list[v2][2],
vertex_list[v3][0], vertex_list[v3][1], vertex_list[v3][2])
Job.yieldThread()
# Rotate the model; We use a different coordinate frame.
rotation = Matrix()
rotation.setByRotationAxis(-0.5 * math.pi, Vector(1,0,0))
#TODO: We currently do not check for normals and simply recalculate them.
mesh_builder.calculateNormals()
node.setMeshData(mesh_builder.build().getTransformed(rotation))
node.setSelectable(True)
transformations = root.findall("./3mf:build/3mf:item[@objectid='{0}']".format(entry.get("id")), self._namespaces)
transformation = transformations[0] if transformations else None
if transformation is not None and transformation.get("transform"):
splitted_transformation = transformation.get("transform").split()
## Transformation is saved as:
## M00 M01 M02 0.0
## M10 M11 M12 0.0
## M20 M21 M22 0.0
## M30 M31 M32 1.0
## We switch the row & cols as that is how everyone else uses matrices!
temp_mat = Matrix()
# Rotation & Scale
temp_mat._data[0,0] = splitted_transformation[0]
temp_mat._data[1,0] = splitted_transformation[1]
temp_mat._data[2,0] = splitted_transformation[2]
temp_mat._data[0,1] = splitted_transformation[3]
temp_mat._data[1,1] = splitted_transformation[4]
temp_mat._data[2,1] = splitted_transformation[5]
temp_mat._data[0,2] = splitted_transformation[6]
temp_mat._data[1,2] = splitted_transformation[7]
temp_mat._data[2,2] = splitted_transformation[8]
# Translation
temp_mat._data[0,3] = splitted_transformation[9]
temp_mat._data[1,3] = splitted_transformation[10]
temp_mat._data[2,3] = splitted_transformation[11]
node.setTransformation(temp_mat)
result.addChild(node)
Job.yieldThread()
#If there is more then one object, group them.
if len(objects) > 1:
group_decorator = GroupDecorator()
result.addDecorator(group_decorator)
except Exception as e:
Logger.log("e" ,"exception occured in 3mf reader: %s" , e)
return result
示例9: _generateSceneNode
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
#.........这里部分代码省略.........
height_data += copy[2:, 1:-1]
height_data += copy[:-2, 1:-1]
height_data += copy[2:, 2:]
height_data += copy[:-2, 2:]
height_data += copy[2:, :-2]
height_data += copy[:-2, :-2]
height_data /= 9
Job.yieldThread()
height_data *= scale_vector.y
height_data += base_height
heightmap_face_count = 2 * height_minus_one * width_minus_one
total_face_count = heightmap_face_count + (width_minus_one * 2) * (height_minus_one * 2) + 2
mesh.reserveFaceCount(total_face_count)
# initialize to texel space vertex offsets.
# 6 is for 6 vertices for each texel quad.
heightmap_vertices = numpy.zeros((width_minus_one * height_minus_one, 6, 3), dtype = numpy.float32)
heightmap_vertices = heightmap_vertices + numpy.array([[
[0, base_height, 0],
[0, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, 0],
[0, base_height, 0]
]], dtype = numpy.float32)
offsetsz, offsetsx = numpy.mgrid[0: height_minus_one, 0: width - 1]
offsetsx = numpy.array(offsetsx, numpy.float32).reshape(-1, 1) * texel_width
offsetsz = numpy.array(offsetsz, numpy.float32).reshape(-1, 1) * texel_height
# offsets for each texel quad
heightmap_vertex_offsets = numpy.concatenate([offsetsx, numpy.zeros((offsetsx.shape[0], offsetsx.shape[1]), dtype=numpy.float32), offsetsz], 1)
heightmap_vertices += heightmap_vertex_offsets.repeat(6, 0).reshape(-1, 6, 3)
# apply height data to y values
heightmap_vertices[:, 0, 1] = heightmap_vertices[:, 5, 1] = height_data[:-1, :-1].reshape(-1)
heightmap_vertices[:, 1, 1] = height_data[1:, :-1].reshape(-1)
heightmap_vertices[:, 2, 1] = heightmap_vertices[:, 3, 1] = height_data[1:, 1:].reshape(-1)
heightmap_vertices[:, 4, 1] = height_data[:-1, 1:].reshape(-1)
heightmap_indices = numpy.array(numpy.mgrid[0:heightmap_face_count * 3], dtype=numpy.int32).reshape(-1, 3)
mesh._vertices[0:(heightmap_vertices.size // 3), :] = heightmap_vertices.reshape(-1, 3)
mesh._indices[0:(heightmap_indices.size // 3), :] = heightmap_indices
mesh._vertex_count = heightmap_vertices.size // 3
mesh._face_count = heightmap_indices.size // 3
geo_width = width_minus_one * texel_width
geo_height = height_minus_one * texel_height
# bottom
mesh.addFaceByPoints(0, 0, 0, 0, 0, geo_height, geo_width, 0, geo_height)
mesh.addFaceByPoints(geo_width, 0, geo_height, geo_width, 0, 0, 0, 0, 0)
# north and south walls
for n in range(0, width_minus_one):
x = n * texel_width
nx = (n + 1) * texel_width
hn0 = height_data[0, n]
hn1 = height_data[0, n + 1]
hs0 = height_data[height_minus_one, n]
hs1 = height_data[height_minus_one, n + 1]
mesh.addFaceByPoints(x, 0, 0, nx, 0, 0, nx, hn1, 0)
mesh.addFaceByPoints(nx, hn1, 0, x, hn0, 0, x, 0, 0)
mesh.addFaceByPoints(x, 0, geo_height, nx, 0, geo_height, nx, hs1, geo_height)
mesh.addFaceByPoints(nx, hs1, geo_height, x, hs0, geo_height, x, 0, geo_height)
# west and east walls
for n in range(0, height_minus_one):
y = n * texel_height
ny = (n + 1) * texel_height
hw0 = height_data[n, 0]
hw1 = height_data[n + 1, 0]
he0 = height_data[n, width_minus_one]
he1 = height_data[n + 1, width_minus_one]
mesh.addFaceByPoints(0, 0, y, 0, 0, ny, 0, hw1, ny)
mesh.addFaceByPoints(0, hw1, ny, 0, hw0, y, 0, 0, y)
mesh.addFaceByPoints(geo_width, 0, y, geo_width, 0, ny, geo_width, he1, ny)
mesh.addFaceByPoints(geo_width, he1, ny, geo_width, he0, y, geo_width, 0, y)
mesh.calculateNormals(fast=True)
scene_node.setMeshData(mesh.build())
return scene_node
示例10: _createNodeFromObject
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def _createNodeFromObject(self, object, name = ""):
node = SceneNode()
node.setName(name)
mesh_builder = MeshBuilder()
vertex_list = []
components = object.find(".//3mf:components", self._namespaces)
if components:
for component in components:
id = component.get("objectid")
new_object = self._root.find("./3mf:resources/3mf:object[@id='{0}']".format(id), self._namespaces)
new_node = self._createNodeFromObject(new_object, self._base_name + "_" + str(id))
node.addChild(new_node)
transform = component.get("transform")
if transform is not None:
new_node.setTransformation(self._createMatrixFromTransformationString(transform))
# for vertex in entry.mesh.vertices.vertex:
for vertex in object.findall(".//3mf:vertex", self._namespaces):
vertex_list.append([vertex.get("x"), vertex.get("y"), vertex.get("z")])
Job.yieldThread()
xml_settings = list(object.findall(".//cura:setting", self._namespaces))
# Add the setting override decorator, so we can add settings to this node.
if xml_settings:
node.addDecorator(SettingOverrideDecorator())
global_container_stack = Application.getInstance().getGlobalContainerStack()
# Ensure the correct next container for the SettingOverride decorator is set.
if global_container_stack:
multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
# Ensure that all extruder data is reset
if not multi_extrusion:
default_stack_id = global_container_stack.getId()
else:
default_stack = ExtruderManager.getInstance().getExtruderStack(0)
if default_stack:
default_stack_id = default_stack.getId()
else:
default_stack_id = global_container_stack.getId()
node.callDecoration("setActiveExtruder", default_stack_id)
# Get the definition & set it
definition = QualityManager.getInstance().getParentMachineDefinition(global_container_stack.getBottom())
node.callDecoration("getStack").getTop().setDefinition(definition)
setting_container = node.callDecoration("getStack").getTop()
for setting in xml_settings:
setting_key = setting.get("key")
setting_value = setting.text
# Extruder_nr is a special case.
if setting_key == "extruder_nr":
extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
if extruder_stack:
node.callDecoration("setActiveExtruder", extruder_stack.getId())
else:
Logger.log("w", "Unable to find extruder in position %s", setting_value)
continue
setting_container.setProperty(setting_key,"value", setting_value)
if len(node.getChildren()) > 0:
group_decorator = GroupDecorator()
node.addDecorator(group_decorator)
triangles = object.findall(".//3mf:triangle", self._namespaces)
mesh_builder.reserveFaceCount(len(triangles))
for triangle in triangles:
v1 = int(triangle.get("v1"))
v2 = int(triangle.get("v2"))
v3 = int(triangle.get("v3"))
mesh_builder.addFaceByPoints(vertex_list[v1][0], vertex_list[v1][1], vertex_list[v1][2],
vertex_list[v2][0], vertex_list[v2][1], vertex_list[v2][2],
vertex_list[v3][0], vertex_list[v3][1], vertex_list[v3][2])
Job.yieldThread()
# TODO: We currently do not check for normals and simply recalculate them.
mesh_builder.calculateNormals()
mesh_builder.setFileName(name)
mesh_data = mesh_builder.build()
if len(mesh_data.getVertices()):
node.setMeshData(mesh_data)
node.setSelectable(True)
return node
示例11: rebuild
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def rebuild(self):
if not self._width or not self._height or not self._depth:
return
min_w = -self._width / 2
max_w = self._width / 2
min_h = 0.0
max_h = self._height
min_d = -self._depth / 2
max_d = self._depth / 2
z_fight_distance = 0.2 # Distance between buildplate and disallowed area meshes to prevent z-fighting
if self._shape != "elliptic":
# Outline 'cube' of the build volume
mb = MeshBuilder()
mb.addLine(Vector(min_w, min_h, min_d), Vector(max_w, min_h, min_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, max_h, min_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, max_h, min_d), Vector(max_w, max_h, min_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, max_h, min_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, min_h, max_d), Vector(max_w, min_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, min_h, max_d), Vector(min_w, max_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, max_h, max_d), Vector(max_w, max_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(max_w, min_h, max_d), Vector(max_w, max_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, min_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, min_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(min_w, max_h, min_d), Vector(min_w, max_h, max_d), color = self.VolumeOutlineColor)
mb.addLine(Vector(max_w, max_h, min_d), Vector(max_w, max_h, max_d), color = self.VolumeOutlineColor)
self.setMeshData(mb.build())
# Build plate grid mesh
mb = MeshBuilder()
mb.addQuad(
Vector(min_w, min_h - z_fight_distance, min_d),
Vector(max_w, min_h - z_fight_distance, min_d),
Vector(max_w, min_h - z_fight_distance, max_d),
Vector(min_w, min_h - z_fight_distance, max_d)
)
for n in range(0, 6):
v = mb.getVertex(n)
mb.setVertexUVCoordinates(n, v[0], v[2])
self._grid_mesh = mb.build()
else:
# Bottom and top 'ellipse' of the build volume
aspect = 1.0
scale_matrix = Matrix()
if self._width != 0:
# Scale circular meshes by aspect ratio if width != height
aspect = self._height / self._width
scale_matrix.compose(scale = Vector(1, 1, aspect))
mb = MeshBuilder()
mb.addArc(max_w, Vector.Unit_Y, center = (0, min_h - z_fight_distance, 0), color = self.VolumeOutlineColor)
mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self.VolumeOutlineColor)
self.setMeshData(mb.build().getTransformed(scale_matrix))
# Build plate grid mesh
mb = MeshBuilder()
mb.addVertex(0, min_h - z_fight_distance, 0)
mb.addArc(max_w, Vector.Unit_Y, center = Vector(0, min_h - z_fight_distance, 0))
sections = mb.getVertexCount() - 1 # Center point is not an arc section
indices = []
for n in range(0, sections - 1):
indices.append([0, n + 2, n + 1])
mb.addIndices(numpy.asarray(indices, dtype = numpy.int32))
mb.calculateNormals()
for n in range(0, mb.getVertexCount()):
v = mb.getVertex(n)
mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
self._grid_mesh = mb.build().getTransformed(scale_matrix)
# Indication of the machine origin
if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
else:
origin = Vector(min_w, min_h, max_d)
mb = MeshBuilder()
mb.addCube(
width = self._origin_line_length,
height = self._origin_line_width,
depth = self._origin_line_width,
center = origin + Vector(self._origin_line_length / 2, 0, 0),
color = self.XAxisColor
)
mb.addCube(
width = self._origin_line_width,
height = self._origin_line_length,
depth = self._origin_line_width,
center = origin + Vector(0, self._origin_line_length / 2, 0),
color = self.YAxisColor
)
mb.addCube(
width = self._origin_line_width,
height = self._origin_line_width,
#.........这里部分代码省略.........
示例12: read
# 需要导入模块: from UM.Mesh.MeshBuilder import MeshBuilder [as 别名]
# 或者: from UM.Mesh.MeshBuilder.MeshBuilder import calculateNormals [as 别名]
def read(self, file_name):
scene_node = None
extension = os.path.splitext(file_name)[1]
if extension.lower() in self._supported_extensions:
vertex_list = []
normal_list = []
uv_list = []
face_list = []
scene_node = SceneNode()
mesh_builder = MeshBuilder()
mesh_builder.setFileName(file_name)
f = open(file_name, "rt")
for line in f:
parts = line.split()
if len(parts) < 1:
continue
if parts[0] == "v":
vertex_list.append([float(parts[1]), float(parts[3]), -float(parts[2])])
if parts[0] == "vn":
normal_list.append([float(parts[1]), float(parts[3]), -float(parts[2])])
if parts[0] == "vt":
uv_list.append([float(parts[1]), float(parts[2])])
if parts[0] == "f":
parts = [i for i in map(lambda p: p.split("/"), parts)]
for idx in range(1, len(parts)-2):
data = [int(parts[1][0]), int(parts[idx+1][0]), int(parts[idx+2][0])]
if len(parts[1]) > 2:
data += [int(parts[1][2]), int(parts[idx+1][2]), int(parts[idx+2][2])]
if parts[1][1] and parts[idx+1][1] and parts[idx+2][1]:
data += [int(parts[1][1]), int(parts[idx+1][1]), int(parts[idx+2][1])]
face_list.append(data)
Job.yieldThread()
f.close()
mesh_builder.reserveVertexCount(3 * len(face_list))
num_vertices = len(vertex_list)
num_normals = len(normal_list)
for face in face_list:
# Substract 1 from index, as obj starts counting at 1 instead of 0
i = face[0] - 1
j = face[1] - 1
k = face[2] - 1
if len(face) > 3:
ni = face[3] - 1
nj = face[4] - 1
nk = face[5] - 1
else:
ni = -1
nj = -1
nk = -1
if len(face) > 6:
ui = face[6] - 1
uj = face[7] - 1
uk = face[8] - 1
else:
ui = -1
uj = -1
uk = -1
#TODO: improve this handling, this can cause weird errors (negative indexes are relative indexes, and are not properly handled)
if i < 0 or i >= num_vertices:
i = 0
if j < 0 or j >= num_vertices:
j = 0
if k < 0 or k >= num_vertices:
k = 0
if ni != -1 and nj != -1 and nk != -1:
mesh_builder.addFaceWithNormals(vertex_list[i][0], vertex_list[i][1], vertex_list[i][2], normal_list[ni][0], normal_list[ni][1], normal_list[ni][2], vertex_list[j][0], vertex_list[j][1], vertex_list[j][2], normal_list[nj][0], normal_list[nj][1], normal_list[nj][2], vertex_list[k][0], vertex_list[k][1], vertex_list[k][2],normal_list[nk][0], normal_list[nk][1], normal_list[nk][2])
else:
mesh_builder.addFaceByPoints(vertex_list[i][0], vertex_list[i][1], vertex_list[i][2], vertex_list[j][0], vertex_list[j][1], vertex_list[j][2], vertex_list[k][0], vertex_list[k][1], vertex_list[k][2])
if ui != -1:
mesh_builder.setVertexUVCoordinates(mesh_builder.getVertexCount() - 3, uv_list[ui][0], uv_list[ui][1])
if uj != -1:
mesh_builder.setVertexUVCoordinates(mesh_builder.getVertexCount() - 2, uv_list[uj][0], uv_list[uj][1])
if uk != -1:
mesh_builder.setVertexUVCoordinates(mesh_builder.getVertexCount() - 1, uv_list[uk][0], uv_list[uk][1])
Job.yieldThread()
if not mesh_builder.hasNormals():
mesh_builder.calculateNormals(fast = True)
scene_node.setMeshData(mesh_builder.build())
return scene_node