本文整理汇总了Python中MeshPart类的典型用法代码示例。如果您正苦于以下问题:Python MeshPart类的具体用法?Python MeshPart怎么用?Python MeshPart使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MeshPart类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: freecad_mesh
def freecad_mesh(geometry):
mesh = MeshPart.meshFromShape(geometry, Fineness=2, SecondOrder=0,
Optimize=1, AllowQuad=0)
result = {}
# Point IDs might be in arbitrary order, so create a lookup to be sure
# that we have the correct point ids
point_ids = {}
points = []
for point_count, point in enumerate(mesh.Points):
points.append([point.x, point.y, point.z])
point_ids[point.Index] = point_count
result['nodes'] = np.array(points, dtype=np.float64)
triangles = []
for facet_count, facet in enumerate(mesh.Facets):
if len(facet.PointIndices) != 3:
raise NotImplementedError("Only triangles currently supported")
triangles.append([point_ids[n] for n in facet.PointIndices])
result['triangles'] = np.array(triangles)
return result
示例2: process3D_ObjectsViaOpenSCADShape
def process3D_ObjectsViaOpenSCADShape(ObjList, Operation, maxmeshpoints=None):
import FreeCAD, Mesh, Part
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD")
if False: # disabled due to issue 1292
import MeshPart
meshes = [
MeshPart.meshFromShape(
obj.Shape,
params.GetFloat("meshmaxlength", 1.0),
params.GetFloat("meshmaxarea", 0.0),
params.GetFloat("meshlocallen", 0.0),
params.GetFloat("meshdeflection", 0.0),
)
for obj in ObjList
]
else:
meshes = [Mesh.Mesh(obj.Shape.tessellate(params.GetFloat("meshmaxlength", 1.0))) for obj in ObjList]
if max(mesh.CountPoints for mesh in meshes) < (maxmeshpoints or params.GetInt("tempmeshmaxpoints", 5000)):
stlmesh = meshoptempfile(Operation, meshes)
sh = Part.Shape()
sh.makeShapeFromMesh(stlmesh.Topology, 0.1)
solid = Part.Solid(sh)
solid = solid.removeSplitter()
if solid.Volume < 0:
solid.complement()
return solid
示例3: meshoponobjs
def meshoponobjs(opname,inobjs):
"""
takes a string (operation name) and a list of Feature Objects
returns a mesh and a list of objects that were used
Part Objects will be meshed
"""
objs=[]
meshes=[]
for obj in inobjs:
if obj.isDerivedFrom('Mesh::Feature'):
objs.append(obj)
meshes.append(obj.Mesh)
elif obj.isDerivedFrom('Part::Feature'):
#mesh the shape
import FreeCAD
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD")
objs.append(obj)
if False: # disabled due to issue 1292
import MeshPart
meshes.append(MeshPart.meshFromShape(obj.Shape,params.GetFloat(\
'meshmaxlength',1.0), params.GetFloat('meshmaxarea',0.0),\
params.GetFloat('meshlocallen',0.0),\
params.GetFloat('meshdeflection',0.0)))
else:
import Mesh
meshes.append(Mesh.Mesh(obj.Shape.tessellate(params.GetFloat(\
'meshmaxlength',1.0))))
else:
pass #neither a mesh nor a part
if len(objs) > 0:
return (meshoptempfile(opname,meshes),objs)
else:
return (None,[])
示例4: shape2polyhedron
def shape2polyhedron(shape):
import MeshPart
fa = params.GetFloat('exportFa',12.0)
return mesh2polyhedron(MeshPart.meshFromShape(shape,params.GetFloat(\
'meshmaxlength',1.0), params.GetFloat('meshmaxarea',0.0),\
params.GetFloat('meshlocallen',0.0),\
params.GetFloat('meshdeflection',0.0)))
示例5: process3D_ObjectsViaOpenSCAD
def process3D_ObjectsViaOpenSCAD(doc,ObjList,Operation):
import FreeCAD,Mesh,Part
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD")
if False: # disabled due to issue 1292
import MeshPart
meshes = [MeshPart.meshFromShape(obj.Shape,params.GetFloat(\
'meshmaxlength',1.0), params.GetFloat('meshmaxarea',0.0),\
params.GetFloat('meshlocallen',0.0),\
params.GetFloat('meshdeflection',0.0)) for obj in ObjList]
else:
meshes = [Mesh.Mesh(obj.Shape.tessellate(params.GetFloat(\
'meshmaxlength',1.0))) for obj in ObjList]
if max(mesh.CountPoints for mesh in meshes) < \
params.GetInt('tempmeshmaxpoints',5000):
stlmesh = meshoptempfile(Operation,meshes)
sh=Part.Shape()
sh.makeShapeFromMesh(stlmesh.Topology,0.1)
solid = Part.Solid(sh)
obj=doc.addObject('Part::Feature',Operation) #non parametric objec
solid=solid.removeSplitter()
if solid.Volume < 0:
solid.complement()
obj.Shape=solid#.removeSplitter()
if FreeCAD.GuiUp:
for index in ObjList :
index.ViewObject.hide()
return(obj)
示例6: getShapeFromMesh
def getShapeFromMesh(mesh,fast=True,tolerance=0.001,flat=False,cut=True):
import Part, MeshPart, DraftGeomUtils
if mesh.isSolid() and (mesh.countComponents() == 1) and fast:
# use the best method
faces = []
for f in mesh.Facets:
p=f.Points+[f.Points[0]]
pts = []
for pp in p:
pts.append(FreeCAD.Vector(pp[0],pp[1],pp[2]))
try:
f = Part.Face(Part.makePolygon(pts))
except:
pass
else:
faces.append(f)
shell = Part.makeShell(faces)
solid = Part.Solid(shell)
solid = solid.removeSplitter()
return solid
faces = []
segments = mesh.getPlanarSegments(tolerance)
#print len(segments)
for i in segments:
if len(i) > 0:
wires = MeshPart.wireFromSegment(mesh, i)
if wires:
if flat:
nwires = []
for w in wires:
nwires.append(DraftGeomUtils.flattenWire(w))
wires = nwires
try:
faces.append(makeFace(wires,method=int(cut)+1))
except:
return None
try:
se = Part.makeShell(faces)
se = se.removeSplitter()
if flat:
return se
except Part.OCCError:
try:
cp = Part.makeCompound(faces)
except Part.OCCError:
return None
else:
return cp
else:
try:
solid = Part.Solid(se)
except Part.OCCError:
return se
else:
return solid
示例7: opExecute
def opExecute(self, obj):
'''opExecute(obj) ... process engraving operation'''
PathLog.track()
output = ""
if obj.Comment != "":
output += '(' + str(obj.Comment)+')\n'
output += "(" + obj.Label + ")"
output += "(Compensated Tool Path. Diameter: " + str(obj.ToolController.Tool.Diameter) + ")"
parentJob = PathUtils.findParentJob(obj)
if parentJob is None:
return
print("base object: " + self.baseobject.Name)
if obj.Algorithm in ['OCL Dropcutter', 'OCL Waterline']:
try:
import ocl
except:
FreeCAD.Console.PrintError(
translate("Path_Surface", "This operation requires OpenCamLib to be installed.\n"))
return
if self.baseobject.TypeId.startswith('Mesh'):
mesh = self.baseobject.Mesh
else:
# try/except is for Path Jobs created before GeometryTolerance
try:
deflection = parentJob.GeometryTolerance
except AttributeError:
from PathScripts.PathPreferences import PathPreferences
deflection = PathPreferences.defaultGeometryTolerance()
self.baseobject.Shape.tessellate(0.5)
mesh = MeshPart.meshFromShape(self.baseobject.Shape, Deflection=deflection)
bb = mesh.BoundBox
s = ocl.STLSurf()
for f in mesh.Facets:
p = f.Points[0]
q = f.Points[1]
r = f.Points[2]
t = ocl.Triangle(ocl.Point(p[0], p[1], p[2]), ocl.Point(
q[0], q[1], q[2]), ocl.Point(r[0], r[1], r[2]))
s.addTriangle(t)
if obj.Algorithm == 'OCL Dropcutter':
output = self._dropcutter(obj, s, bb)
elif obj.Algorithm == 'OCL Waterline':
output = self._waterline(obj, s, bb)
self.commandlist.extend(output)
示例8: triangulate
def triangulate(shape):
"triangulates the given face"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
mesher = p.GetInt("ColladaMesher",0)
tessellation = p.GetFloat("ColladaTessellation",1.0)
grading = p.GetFloat("ColladaGrading",0.3)
segsperedge = p.GetInt("ColladaSegsPerEdge",1)
segsperradius = p.GetInt("ColladaSegsPerRadius",2)
secondorder = p.GetBool("ColladaSecondOrder",False)
optimize = p.GetBool("ColladaOptimize",True)
allowquads = p.GetBool("ColladaAllowQuads",False)
if mesher == 0:
return shape.tessellate(tessellation)
elif mesher == 1:
return MeshPart.meshFromShape(Shape=shape,MaxLength=tessellation).Topology
else:
return MeshPart.meshFromShape(Shape=shape,GrowthRate=grading,SegPerEdge=segsperedge,
SegPerRadius=segsperradius,SecondOrder=secondorder,Optimize=optimize,
AllowQuad=allowquads).Topology
示例9: shape2polyhedron
def shape2polyhedron(shape):
import MeshPart
fa = params.GetFloat("exportFa", 12.0)
return mesh2polyhedron(
MeshPart.meshFromShape(
shape,
params.GetFloat("meshmaxlength", 1.0),
params.GetFloat("meshmaxarea", 0.0),
params.GetFloat("meshlocallen", 0.0),
params.GetFloat("meshdeflection", 0.0),
)
)
示例10: meshToShape
def meshToShape(obj,mark=True):
'''meshToShape(object,[mark]): turns a mesh into a shape, joining coplanar facets. If
mark is True (default), non-solid objects will be marked in red'''
name = obj.Name
import Part,MeshPart
from draftlibs import fcgeo
if "Mesh" in obj.PropertiesList:
faces = []
mesh = obj.Mesh
plac = obj.Placement
segments = mesh.getPlanes(0.001) # use rather strict tolerance here
print len(segments)," segments ",segments
for i in segments:
print "treating",segments.index(i),i
if len(i) > 0:
wires = MeshPart.wireFromSegment(mesh, i)
print "wire done"
print wires
if wires:
faces.append(makeFace(wires))
print "done facing"
print "faces",faces
try:
se = Part.makeShell(faces)
solid = Part.Solid(se)
except:
pass
else:
if solid.isClosed():
FreeCAD.ActiveDocument.removeObject(name)
newobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
newobj.Shape = solid
newobj.Placement = plac
if not solid.isClosed():
if mark:
newobj.ViewObject.ShapeColor = (1.0,0.0,0.0,1.0)
return newobj
return None
示例11: tuple
pointstr=','.join(['[%f,%f,%f]' % tuple(vec) for vec in mesh.Topology[0]])
trianglestr=','.join(['[%d,%d,%d]' % tuple(tri) for tri in mesh.Topology[1]])
return 'polyhedron ( points = [%s], triangles = [%s]);' % (pointstr,trianglestr)
def vector2d(v):
return [v[0],v[1]]
def vertexs2polygon(vertex):
pointstr=','.join(['[%f, %f]' % tuple(vector2d(v.Point)) for v in vertex])
return 'polygon ( points = [%s], paths = undef, convexity = 1);}' % pointstr
def shape2polyhedron(shape):
import MeshPart
fa = params.GetFloat('exportFa',12.0)
return mesh2polyhedron(MeshPart.meshFromShape(shape,params.GetFloat(\
'meshmaxlength',1.0), params.GetFloat('meshmaxarea',0.0),\
params.GetFloat('meshlocallen',0.0),\
params.GetFloat('meshdeflection',0.0)))
def process_object(csg,ob):
print "Placement"
print "Pos : "+str(ob.Placement.Base)
print "axis : "+str(ob.Placement.Rotation.Axis)
print "angle : "+str(ob.Placement.Rotation.Angle)
if ob.Type == "Part::Sphere" :
print "Sphere Radius : "+str(ob.Radius)
check_multmatrix(csg,ob,0,0,0)
global fafs
csg.write("sphere($fn = 0, "+fafs+", r = "+str(ob.Radius)+");\n")
示例12: len
# FreeCAD TemplatePyMod module
# (c) 2010 Werner Mayer LGPL
import Mesh,Part,MeshPart
faces = []
mesh = App.ActiveDocument.ActiveObject.Mesh
segments = mesh.getPlanarSegments(0.00001) # use rather strict tolerance here
for i in segments:
if len(i) > 0:
# a segment can have inner holes
wires = MeshPart.wireFromSegment(mesh, i)
# we assume that the exterior boundary is that one with the biggest bounding box
if len(wires) > 0:
ext=None
max_length=0
for i in wires:
if i.BoundBox.DiagonalLength > max_length:
max_length = i.BoundBox.DiagonalLength
ext = i
wires.remove(ext)
# all interior wires mark a hole and must reverse their orientation, otherwise Part.Face fails
for i in wires:
i.reverse()
# make sure that the exterior wires comes as first in the list
wires.insert(0, ext)
faces.append(Part.Face(wires))
示例13: execute
def execute(self, obj):
import MeshPart
FreeCAD.Console.PrintWarning(
translate("PathSurface", "Hold on. This might take a minute.\n"))
output = ""
if obj.Comment != "":
output += '(' + str(obj.Comment)+')\n'
toolLoad = PathUtils.getLastToolLoad(obj)
if toolLoad is None or toolLoad.ToolNumber == 0:
self.vertFeed = 100
self.horizFeed = 100
self.vertRapid = 100
self.horizRapid = 100
self.radius = 0.25
obj.ToolNumber = 0
obj.ToolDescription = "UNDEFINED"
else:
self.vertFeed = toolLoad.VertFeed.Value
self.horizFeed = toolLoad.HorizFeed.Value
self.vertRapid = toolLoad.VertRapid.Value
self.horizRapid = toolLoad.HorizRapid.Value
tool = PathUtils.getTool(obj, toolLoad.ToolNumber)
if tool.Diameter == 0:
self.radius = 0.25
else:
self.radius = tool.Diameter/2
obj.ToolNumber = toolLoad.ToolNumber
obj.ToolDescription = toolLoad.Name
if obj.UserLabel == "":
obj.Label = obj.Name + " :" + obj.ToolDescription
else:
obj.Label = obj.UserLabel + " :" + obj.ToolDescription
output += "(" + obj.Label + ")"
output += "(Compensated Tool Path. Diameter: " + str(self.radius * 2) + ")"
# if obj.Base:
# for b in obj.Base:
parentJob = PathUtils.findParentJob(obj)
if parentJob is None:
return
mesh = parentJob.Base
if mesh is None:
return
print "base object: " + mesh.Name
if obj.Algorithm in ['OCL Dropcutter', 'OCL Waterline']:
try:
import ocl
except:
FreeCAD.Console.PrintError(translate(
"PathSurface", "This operation requires OpenCamLib to be installed.\n"))
return
#mesh = b[0]
if mesh.TypeId.startswith('Mesh'):
mesh = mesh.Mesh
bb = mesh.BoundBox
else:
bb = mesh.Shape.BoundBox
mesh = MeshPart.meshFromShape(mesh.Shape, MaxLength=2)
s = ocl.STLSurf()
for f in mesh.Facets:
p = f.Points[0]
q = f.Points[1]
r = f.Points[2]
t = ocl.Triangle(ocl.Point(p[0], p[1], p[2]), ocl.Point(
q[0], q[1], q[2]), ocl.Point(r[0], r[1], r[2]))
s.addTriangle(t)
if obj.Algorithm == 'OCL Dropcutter':
output = self._dropcutter(obj, s, bb)
elif obj.Algorithm == 'OCL Waterline':
output = self._waterline(obj, s, bb)
if obj.Active:
path = Path.Path(output)
obj.Path = path
obj.ViewObject.Visibility = True
else:
path = Path.Path("(inactive operation)")
obj.Path = path
obj.ViewObject.Visibility = False
示例14: opExecute
def opExecute(self, obj):
'''opExecute(obj) ... process surface operation'''
PathLog.track()
# OCL must be installed
try:
import ocl
except:
FreeCAD.Console.PrintError(
translate("Path_Surface", "This operation requires OpenCamLib to be installed.") + "\n")
return
print("StepOver is " + str(obj.StepOver))
if obj.StepOver > 100:
obj.StepOver = 100
if obj.StepOver < 1:
obj.StepOver = 1
output = ""
if obj.Comment != "":
output += '(' + str(obj.Comment) + ')\n'
output += "(" + obj.Label + ")"
output += "(Compensated Tool Path. Diameter: " + str(obj.ToolController.Tool.Diameter) + ")"
parentJob = PathUtils.findParentJob(obj)
if parentJob is None:
return
for base in self.model:
print("base object: " + base.Name)
if base.TypeId.startswith('Mesh'):
mesh = base.Mesh
else:
# try/except is for Path Jobs created before GeometryTolerance
try:
deflection = parentJob.GeometryTolerance
except AttributeError:
import PathScripts.PathPreferences as PathPreferences
deflection = PathPreferences.defaultGeometryTolerance()
base.Shape.tessellate(0.5)
mesh = MeshPart.meshFromShape(base.Shape, Deflection=deflection)
if obj.BoundBox == "BaseBoundBox":
bb = mesh.BoundBox
else:
bb = parentJob.Stock.Shape.BoundBox
s = ocl.STLSurf()
for f in mesh.Facets:
p = f.Points[0]
q = f.Points[1]
r = f.Points[2]
# offset the triangle in Z with DepthOffset
t = ocl.Triangle(ocl.Point(p[0], p[1], p[2] + obj.DepthOffset.Value),
ocl.Point(q[0], q[1], q[2] + obj.DepthOffset.Value),
ocl.Point(r[0], r[1], r[2] + obj.DepthOffset.Value))
s.addTriangle(t)
if obj.Algorithm == 'OCL Dropcutter':
output = self._dropcutter(obj, s, bb)
elif obj.Algorithm == 'OCL Waterline':
output = self._waterline(obj, s, bb)
self.commandlist.extend(output)
示例15: execute
def execute(self, obj):
import MeshPart
FreeCAD.Console.PrintWarning(
translate("Path_Surface", "Hold on. This might take a minute.\n"))
output = ""
if obj.Comment != "":
output += '(' + str(obj.Comment)+')\n'
toolLoad = obj.ToolController
if toolLoad is None or toolLoad.ToolNumber == 0:
FreeCAD.Console.PrintError("No Tool Controller is selected. We need a tool to build a Path.")
else:
self.vertFeed = toolLoad.VertFeed.Value
self.horizFeed = toolLoad.HorizFeed.Value
self.vertRapid = toolLoad.VertRapid.Value
self.horizRapid = toolLoad.HorizRapid.Value
tool = toolLoad.Proxy.getTool(toolLoad)
if not tool or tool.Diameter == 0:
FreeCAD.Console.PrintError("No Tool found or diameter is zero. We need a tool to build a Path.")
return
else:
self.radius = tool.Diameter/2
output += "(" + obj.Label + ")"
output += "(Compensated Tool Path. Diameter: " + str(self.radius * 2) + ")"
# if obj.Base:
# for b in obj.Base:
parentJob = PathUtils.findParentJob(obj)
if parentJob is None:
return
mesh = parentJob.Base
if mesh is None:
return
print("base object: " + mesh.Name)
if obj.Algorithm in ['OCL Dropcutter', 'OCL Waterline']:
try:
import ocl
except:
FreeCAD.Console.PrintError(
translate("Path_Surface", "This operation requires OpenCamLib to be installed.\n"))
return
if mesh.TypeId.startswith('Mesh'):
mesh = mesh.Mesh
else:
# try/except is for Path Jobs created before GeometryTolerance
try:
deflection = parentJob.GeometryTolerance
except AttributeError:
from PathScripts.PathPreferences import PathPreferences
deflection = PathPreferences.defaultGeometryTolerance()
mesh = MeshPart.meshFromShape(mesh.Shape, Deflection=deflection)
bb = mesh.BoundBox
s = ocl.STLSurf()
for f in mesh.Facets:
p = f.Points[0]
q = f.Points[1]
r = f.Points[2]
t = ocl.Triangle(ocl.Point(p[0], p[1], p[2]), ocl.Point(
q[0], q[1], q[2]), ocl.Point(r[0], r[1], r[2]))
s.addTriangle(t)
if obj.Algorithm == 'OCL Dropcutter':
output = self._dropcutter(obj, s, bb)
elif obj.Algorithm == 'OCL Waterline':
output = self._waterline(obj, s, bb)
if obj.Active:
path = Path.Path(output)
obj.Path = path
obj.ViewObject.Visibility = True
else:
path = Path.Path("(inactive operation)")
obj.Path = path
obj.ViewObject.Visibility = False