def hex1(params, document): key = params["key"] d1 = params["d1"] k = params["k"] s = params["s"] h = params["h"] if h is None: h = 0.0 l = params["l"] name = params["name"] part = document.addObject("Part::Feature", name) # head a = s / math.tan(math.pi / 3.0) box1 = makeBox(a, s, k) box1.translate(Vector(-0.5 * a, -0.5 * s, 0)) box1.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 30) box2 = makeBox(a, s, k) box2.translate(Vector(-0.5 * a, -0.5 * s, 0)) box2.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 150) box3 = makeBox(a, s, k) box3.translate(Vector(-0.5 * a, -0.5 * s, 0)) box3.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 270) head = box1.fuse(box2).fuse(box3) shaft_unthreaded = Part.makeCylinder(0.5 * d1, h + k) shaft_threaded = Part.makeCylinder(0.5 * d1, l - h) shaft_threaded.translate(Vector(0, 0, h + k)) part.Shape = head.fuse(shaft_unthreaded).fuse(shaft_threaded).removeSplitter()

def makeRef(p1, p2, p3, border): p4 = p1 + (p3 - p2) lines = linesFromPoints([p1, p2, p3, p4], True) w = Part.Wire(lines) p = w.extrude(border) Part.show(p)

def getShapeFromMesh(mesh): import Part, MeshPart if mesh.isSolid() and (mesh.countComponents() == 1): # 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])) faces.append(Part.Face(Part.makePolygon(pts))) shell = Part.makeShell(faces) solid = Part.Solid(shell) solid = solid.removeSplitter() return solid faces = [] segments = mesh.getPlanarSegments(0.001) # use rather strict tolerance here for i in segments: if len(i) > 0: wires = MeshPart.wireFromSegment(mesh, i) if wires: faces.append(makeFace(wires)) try: se = Part.makeShell(faces) except: return None else: try: solid = Part.Solid(se) except: return se else: return solid

def execute(self, fp): edges = fp.Edges if edges < 3: edges = 3 length = fp.Length radius = fp.Radius height = fp.Height m=Base.Matrix() m.rotateZ(math.radians(360.0/edges)) # create polygon polygon = [] v=Base.Vector(length,0,0) for i in range(edges): polygon.append(v) v = m.multiply(v) polygon.append(v) wire = Part.makePolygon(polygon) # create circle circ=Part.makeCircle(radius) # Create the face with the polygon as outline and the circle as hole face=Part.Face([wire,Part.Wire(circ)]) # Extrude in z to create the final solid extrude=face.extrude(Base.Vector(0,0,height)) fp.Shape = extrude

def areaOpShapes(self, obj): '''areaOpShapes(obj) ... return shapes representing the solids to be removed.''' PathLog.track() if obj.Base: PathLog.debug("base items exist. Processing...") removalshapes = [] for b in obj.Base: PathLog.debug("Base item: {}".format(b)) for sub in b[1]: if "Face" in sub: shape = Part.makeCompound([getattr(b[0].Shape, sub)]) else: edges = [getattr(b[0].Shape, sub) for sub in b[1]] shape = Part.makeFace(edges, 'Part::FaceMakerSimple') env = PathUtils.getEnvelope(self.baseobject.Shape, subshape=shape, depthparams=self.depthparams) obj.removalshape = env.cut(self.baseobject.Shape) removalshapes.append((obj.removalshape, False)) else: # process the job base object as a whole PathLog.debug("processing the whole job base object") env = PathUtils.getEnvelope(self.baseobject.Shape, subshape=None, depthparams=self.depthparams) obj.removalshape = env.cut(self.baseobject.Shape) removalshapes = [(obj.removalshape, False)] return removalshapes

def servo(): """servo""" data = servo_data # approximate the servo body = Part.makeBox(data['x'], data['y'], data['z']) maintien1 = Part.makeBox(data['maintien x'], data['maintien y'], data['maintien z']) maintien1.translate(Vector(data['x'], 0, data['maintien offset z'])) maintien2 = Part.makeBox(data['maintien x'], data['maintien y'], data['maintien z']) maintien2.translate(Vector(-data['maintien x'], 0, data['maintien offset z'])) cylindre = Part.makeCylinder(data['cylindre r'], data['cylindre h']) cylindre.translate(Vector(data['cylindre offset x'], data['y'] / 2, data['cylindre offset z'])) taquet = Part.makeBox(data['taquet x'], data['taquet y'], data['taquet z']) taquet.translate(Vector(-data['taquet y'] / 2, -data['taquet y'] / 2, 0)) taquet.rotate(Vector(0, 0, 0), Vector(0, 0, 1), -90) taquet.translate(Vector(data['cylindre offset x'], data['y'] / 2, data['z'] + data['cylindre h'])) obj = body.fuse(maintien1) obj = obj.fuse(maintien2) obj = obj.fuse(cylindre) obj = obj.fuse(taquet) obj.translate(Vector(-data['x'] / 2, -data['y'] / 2, -data['z'] / 2)) return obj

def makeTube(outerRadius, innerRadius, height): outer_cylinder = Part.makeCylinder(outerRadius, height) shape = outer_cylinder if innerRadius > 0 and innerRadius < outerRadius: inner_cylinder = Part.makeCylinder(innerRadius, height) shape = outer_cylinder.cut(inner_cylinder) return shape

def areaOpShapes(self, obj): '''areaOpShapes(obj) ... return top face''' # Facing is done either against base objects if obj.Base: PathLog.debug("obj.Base: {}".format(obj.Base)) faces = [] for b in obj.Base: for sub in b[1]: shape = getattr(b[0].Shape, sub) if isinstance(shape, Part.Face): faces.append(shape) else: PathLog.debug('The base subobject is not a face') return planeshape = Part.makeCompound(faces) PathLog.debug("Working on a collection of faces {}".format(faces)) # If no base object, do planing of top surface of entire model else: planeshape = self.baseobject.Shape PathLog.debug("Working on a shape {}".format(self.baseobject.Name)) # Find the correct shape depending on Boundary shape. PathLog.debug("Boundary Shape: {}".format(obj.BoundaryShape)) bb = planeshape.BoundBox if obj.BoundaryShape == 'Boundbox': bbperim = Part.makeBox(bb.XLength, bb.YLength, 1, FreeCAD.Vector(bb.XMin, bb.YMin, bb.ZMin), FreeCAD.Vector(0, 0, 1)) env = PathUtils.getEnvelope(partshape=bbperim, depthparams=self.depthparams) elif obj.BoundaryShape == 'Stock': stock = PathUtils.findParentJob(obj).Stock.Shape env = stock else: env = PathUtils.getEnvelope(partshape=planeshape, depthparams=self.depthparams) return [(env, False)]

def __init__(self, doc, name='helix'): self.data = { 'len lo': 70., # mm 'len up': 120., # mm 'int diameter': 36., # mm 'thick': 1., # mm } len_lo = self.data['len lo'] # blocking thread (pas de vis de blocage) radius = self.data['int diameter'] / 2 helix = Part.makeHelix(4., 16., radius) p0 = (radius, 0, 0) p1 = (radius, 0, 3) p2 = (radius - 1, 0, 2) p3 = (radius - 1, 0, 1) e0 = Part.makeLine(p0, p1) e1 = Part.makeLine(p1, p2) e2 = Part.makeLine(p2, p3) e3 = Part.makeLine(p3, p0) section = Part.Wire([e0, e1, e2, e3]) helix = Part.Wire(helix).makePipeShell([section], 1, 1) helix.translate(Vector(0, 0, len_lo - 20)) helix = helix.fuse(helix) comp = helix MecaComponent.__init__(self, doc, comp, name, (1., 1., 0.))

def createGeometry(self,fp): if all((fp.Radius1,fp.Radius2,fp.FacesNumber,fp.Height)): import math import FreeCAD,Part #from draftlibs import fcgeo plm = fp.Placement wires=[] faces=[] for ir,r in enumerate((fp.Radius1,fp.Radius2)): angle = (math.pi*2)/fp.FacesNumber pts = [FreeCAD.Vector(r.Value,0,ir*fp.Height.Value)] for i in range(fp.FacesNumber-1): ang = (i+1)*angle pts.append(FreeCAD.Vector(r.Value*math.cos(ang),\ r.Value*math.sin(ang),ir*fp.Height.Value)) pts.append(pts[0]) shape = Part.makePolygon(pts) face = Part.Face(shape) if ir==1: #top face face.reverse() wires.append(shape) faces.append(face) #shellperi=Part.makeRuledSurface(*wires) shellperi=Part.makeLoft(wires) shell=Part.Shell(shellperi.Faces+faces) fp.Shape = Part.Solid(shell) fp.Placement = plm

def makeSurfaceVolume(filename): import FreeCAD,Part f1=open(filename) coords=[] miny=1 for line in f1.readlines(): sline=line.strip() if sline and not sline.startswith('#'): ycoord=len(coords) lcoords=[] for xcoord, num in enumerate(sline.split()): fnum=float(num) lcoords.append(FreeCAD.Vector(float(xcoord),float(ycoord),fnum)) miny=min(fnum,miny) coords.append(lcoords) s=Part.BSplineSurface() s.interpolate(coords) plane=Part.makePlane(len(coords[0])-1,len(coords)-1,FreeCAD.Vector(0,0,miny-1)) l1=Part.makeLine(plane.Vertexes[0].Point,s.value(0,0)) l2=Part.makeLine(plane.Vertexes[1].Point,s.value(1,0)) l3=Part.makeLine(plane.Vertexes[2].Point,s.value(0,1)) l4=Part.makeLine(plane.Vertexes[3].Point,s.value(1,1)) f0=plane.Faces[0] f0.reverse() f1=Part.Face(Part.Wire([plane.Edges[0],l1.Edges[0],s.vIso(0).toShape(),l2.Edges[0]])) f2=Part.Face(Part.Wire([plane.Edges[1],l3.Edges[0],s.uIso(0).toShape(),l1.Edges[0]])) f3=Part.Face(Part.Wire([plane.Edges[2],l4.Edges[0],s.vIso(1).toShape(),l3.Edges[0]])) f4=Part.Face(Part.Wire([plane.Edges[3],l2.Edges[0],s.uIso(1).toShape(),l4.Edges[0]])) f5=s.toShape().Faces[0] solid=Part.Solid(Part.Shell([f0,f1,f2,f3,f4,f5])) return solid,(len(coords[0])-1)/2.0,(len(coords)-1)/2.0

def ruled_surface(e1,e2): """ creates a ruled surface between 2 edges, with automatic orientation.""" # Automatic orientation # /src/Mod/Part/App/PartFeatures.cpp#171 p1 = e1.valueAt(e1.FirstParameter) p2 = e1.valueAt(e1.LastParameter) p3 = e2.valueAt(e2.FirstParameter) p4 = e2.valueAt(e2.LastParameter) if e1.Orientation == 'Reversed': p = p1 p1 = p2 p2 = p if e2.Orientation == 'Reversed': p = p3 p3 = p4 p4 = p v1 = p2 - p1 v2 = p3 - p1 n1 = v1.cross(v2) v3 = p3 - p4 v4 = p2 - p4 n2 = v3.cross(v4) if (n1.dot(n2) < 0): e = e2.copy() e.reverse() return(Part.makeRuledSurface(e1,e)) else: return(Part.makeRuledSurface(e1,e2))

def makeSquareTool(s, m): # makes a cylinder with an inner square hole, used as cutting tool # create square face msq = Base.Matrix() msq.rotateZ(math.radians(90.0)) polygon = [] vsq = Base.Vector(s / 2.0, s / 2.0, -m * 0.1) for i in range(4): polygon.append(vsq) vsq = msq.multiply(vsq) polygon.append(vsq) square = Part.makePolygon(polygon) square = Part.Face(square) # create circle face circ = Part.makeCircle(s * 3.0, Base.Vector(0.0, 0.0, -m * 0.1)) circ = Part.Face(Part.Wire(circ)) # Create the face with the circle as outline and the square as hole face=circ.cut(square) # Extrude in z to create the final cutting tool exSquare = face.extrude(Base.Vector(0.0, 0.0, m * 1.2)) # Part.show(exHex) return exSquare

def execute(self, obj): """Build the object""" #-- When length l is given, a vector with length = l and #-- orientation v is created if obj.l == 0: l = obj.v.Length else: l = obj.l.Value #-- Correct the length if (l < obj.arrow_l): arrow_l = l/2. else: arrow_l = obj.arrow_l.Value #--- Create the base vector base_vect = FreeCAD.Vector(obj.v) base_vect.Length = l - arrow_l #-- Build the object vectz = Part.makeCylinder(obj.d / 2.0, base_vect.Length, Vector(0,0,0), obj.v) base = Part.makeSphere(obj.d / 2.0) arrow = Part.makeCone(obj.d/2. + 2/3. * obj.d, 0.05, arrow_l, base_vect, base_vect) #-- Create the union of all the parts u = vectz.fuse(base) u = u.fuse(arrow) #-- Asign the shape obj.Shape = u

def arma8ptos(fi,recubrN,sepFi,radDobl,pto1,pto2,pto3,pto4,pto5,pto6,pto7,pto8,gap1,gap2): recubrG=recubrN+float(fi)/1000/2.0 v=pto6.sub(pto2) recArmPlano=(v.Length-2*recubrG-int((v.Length-2.0*recubrG)/sepFi)*sepFi)/2.0 v1=GeomUtils.vectorUnitario(pto2,pto1) v2=GeomUtils.vectorUnitario(pto2,pto3) v3=GeomUtils.vectorUnitario(pto3,pto4) v4=GeomUtils.vectorUnitario(pto2,pto6) v5=GeomUtils.vectorUnitario(pto3,pto7) v6=GeomUtils.vectorUnitario(pto6,pto5) v7=GeomUtils.vectorUnitario(pto6,pto7) v8=GeomUtils.vectorUnitario(pto7,pto8) pto1a=pto1.add(GeomUtils.escalarPorVector(recArmPlano,v4)).add(GeomUtils.escalarPorVector(recubrG,v2)).add(GeomUtils.escalarPorVector(gap1,v1)) pto2a=pto2.add(GeomUtils.escalarPorVector(recArmPlano,v4)).add(GeomUtils.escalarPorVector(recubrG,v2)).add(GeomUtils.escalarPorVector(recubrG,v1)) pto3a=pto3.add(GeomUtils.escalarPorVector(recArmPlano,v5)).sub(GeomUtils.escalarPorVector(recubrG,v2)).add(GeomUtils.escalarPorVector(recubrG,v3)) pto4a=pto4.add(GeomUtils.escalarPorVector(recArmPlano,v5)).sub(GeomUtils.escalarPorVector(recubrG,v2)).add(GeomUtils.escalarPorVector(gap2,v3)) pto5a=pto5.sub(GeomUtils.escalarPorVector(recArmPlano,v4)).add(GeomUtils.escalarPorVector(recubrG,v7)).add(GeomUtils.escalarPorVector(gap1,v6)) pto6a=pto6.sub(GeomUtils.escalarPorVector(recArmPlano,v4)).add(GeomUtils.escalarPorVector(recubrG,v7)).add(GeomUtils.escalarPorVector(recubrG,v6)) pto7a=pto7.sub(GeomUtils.escalarPorVector(recArmPlano,v5)).sub(GeomUtils.escalarPorVector(recubrG,v7)).add(GeomUtils.escalarPorVector(recubrG,v8)) pto8a=pto8.sub(GeomUtils.escalarPorVector(recArmPlano,v5)).sub(GeomUtils.escalarPorVector(recubrG,v7)).add(GeomUtils.escalarPorVector(gap2,v8)) cara1=Part.Face(Part.makePolygon([pto1a,pto2a,pto6a,pto5a,pto1a])) cara2=Part.Face(Part.makePolygon([pto2a,pto6a,pto7a,pto3a,pto2a])) cara3=Part.Face(Part.makePolygon([pto3a,pto4a,pto8a,pto7a,pto3a])) arma=cara1.fuse(cara2.fuse(cara3)) armadura=arma.makeFillet(radDobl,arma.Edges) return armadura

def __init__(self, doc, name='integ2'): self.data = { 'len lo': 20., # mm 'len hi': 100., # mm 'ext diameter': 36., # mm 'int diameter': 30., # mm } int_diam = self.data['int diameter'] ext_diam = self.data['ext diameter'] len_hi = self.data['len hi'] len_lo = self.data['len lo'] cone = Part.makeCone(int_diam / 2, ext_diam / 2, len_lo) trunk = Part.makeCylinder(ext_diam / 2, len_hi) trunk.translate(Vector(0, 0, len_lo)) comp = cone.fuse(trunk) cutter = Part.makeBox(ext_diam, ext_diam, len_hi + len_lo) cutter.translate(Vector(0, -ext_diam / 2, 0)) cutter.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 180) comp = comp.common(cutter) MecaComponent.__init__(self, doc, comp, name, (1., 1., 0.))

def execute(self, part): data = iso_4014_1979_partial_hex_screw["sizes"][part.size] # the calculations are based on the ACII art picture above, # with the points starting from the far right point, # and ending with the same point to close the polygon y_distance = 0.5 * data["s_max"] angle = math.pi / 3 head_radius = y_distance / math.sin(angle) x_distance = math.cos(angle) * head_radius points = [ Vector(head_radius, 0, 0), Vector(x_distance, y_distance, 0), Vector(-x_distance, y_distance, 0), Vector(-head_radius, 0, 0), Vector(-x_distance, -y_distance, 0), Vector(x_distance, -y_distance, 0), Vector(head_radius, 0, 0), ] # create a polygon and transform it to a face too: hexagon = Part.Face(Part.makePolygon(points)) # just an integer won't work here, must use units: k = data["k_nom"] * Units.MilliMetre head = hexagon.extrude(Vector(0, 0, k)) shaft = Part.makeCylinder( 0.5 * data["ds_max"], part.length + k, Vector(0, 0, 0), Vector(0, 0, 1) ) part.Shape = head.fuse(shaft)

def __init__(self, doc, tube, name='aero_clutch'): self.data = { 'len': 20., # mm 'width' : 15., # mm } data = self.data data['thick'] = tube['thick'] # mm data['ext diameter'] = tube['int diameter'] - tube['thick'] # mm data['int diameter'] = tube['int diameter'] - 3 * tube['thick'] # mm # rebuild a tube int_part = Part.makeCylinder(data['int diameter'] / 2, data['len']) ext_part = Part.makeCylinder(data['ext diameter'] / 2, data['len']) part = ext_part.cut(int_part) # cut the external shape shape = Part.makeBox(2 * data['ext diameter'], 2 * data['ext diameter'], data['len']) shape.translate(Vector(-data['ext diameter'], -data['ext diameter'], 0)) comp = part.common(shape) # cut the nerves nerv = Part.makeBox(data['ext diameter'] / 2 - 2 * data['thick'], 3., data['len'] / 2) nerv.translate(Vector(-data['ext diameter'] / 2 + data['thick'] / 2, -3. / 2, 0)) comp = comp.cut(nerv) MecaComponent.__init__(self, doc, comp, name, (1., 1., 0.))

def makeSnapshotWithGui(): from PyQt4 import QtGui import FreeCADGui def getMainWindow(): toplevel = QtGui.qApp.topLevelWidgets() for i in toplevel: if i.metaObject().className() == "Gui::MainWindow": return i raise Exception("No main window found") mw=getMainWindow() mw.hide() #mw.showMinimized() # Create a test geometry and add it to the document obj=Part.makeCone(10,8,10) doc = FreeCAD.newDocument() Part.show(obj) # switch off animation so that the camera is moved to the final position immediately view = FreeCADGui.getDocument(doc.Name).activeView() view.setAnimationEnabled(False) view.viewAxometric() view.fitAll() view.saveImage('crystal.png',800,600,'Current') FreeCAD.closeDocument(doc.Name) # close the application QtGui.qApp.quit()

def projectFace(self,face): "projects a single face on the WP" #print "VRM: projectFace start: ",len(face[0].Vertexes)," verts, ",len(face[0].Edges)," edges" wires = [] if not face[0].Wires: if DEBUG: print "Error: Unable to project face on the WP" return None norm = face[0].normalAt(0,0) for w in face[0].Wires: verts = [] edges = Part.__sortEdges__(w.Edges) #print len(edges)," edges after sorting" for e in edges: v = e.Vertexes[0].Point #print v v = self.wp.getLocalCoords(v) verts.append(v) verts.append(verts[0]) if len(verts) > 2: #print "new wire with ",len(verts) wires.append(Part.makePolygon(verts)) try: sh = ArchCommands.makeFace(wires) except: if DEBUG: print "Error: Unable to project face on the WP" return None else: # restoring flipped normals vnorm = self.wp.getLocalCoords(norm) if vnorm.getAngle(sh.normalAt(0,0)) > 1: sh.reverse() #print "VRM: projectFace end: ",len(sh.Vertexes)," verts" return [sh]+face[1:]

def update(self, draft, trim, ship): """ Update free surface 3D view @param traft Draft. @param trim Trim in degrees. """ # Destroy old object if exist self.clean() # Set free surface bounds bbox = ship.Shape.BoundBox L = 1.5 * bbox.XLength B = 3.0 * bbox.YLength # Create plane x = - 0.5 * L y = - 0.5 * B point = Base.Vector(x,y,0.0) plane = Part.makePlane(L,B, point, Base.Vector(0,0,1)) # Set position plane.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), trim) plane.translate(Base.Vector(0,0,draft)) # Create the FreeCAD object Part.show(plane) objs = FreeCAD.ActiveDocument.Objects self.obj = objs[len(objs)-1] self.obj.Label = 'FreeSurface' # Set properties of object guiObj = FreeCADGui.ActiveDocument.getObject(self.obj.Name) guiObj.ShapeColor = (0.4,0.8,0.85) guiObj.Transparency = 50

def make_surfaceShelves(self): # shelf for left work surface shelf_width = self.pos_support1[0]-self.pos_supportMini1[0]+self.thickness shelf_depth = self.depth - self.pos_support1[1] shelf_height = self.underside_height / 2. shelf = Part.makeBox(shelf_width, shelf_depth, self.thickness, self.pos_supportMini1 + Base.Vector(-self.thickness, 0, 0)) shelf = shelf.cut(self.parts_left['support1']) self.parts_left['shelf'] = shelf # shelf for right work surface shelf_width = self.pos_support3[0]-self.pos_supportMini2[0]+self.thickness shelf_depth = self.depth - self.pos_support3[1] shelf_height = self.underside_height / 2. shelf = Part.makeBox(shelf_width, shelf_depth, self.thickness, self.pos_supportMini2 + Base.Vector(-self.thickness, 0, 0)) shelf = shelf.cut(self.parts_right['support3']) self.parts_right['shelf'] = shelf

def hex2(params, document): key = params["key"] d1 = params["d1"] k = params["k"] s = params["s"] b1 = params["b1"] b2 = params["b2"] b3 = params["b3"] l = params["l"] b = b3 if l < 125: b = b1 elif l < 200: b = b2 name = params["name"] part = document.addObject("Part::Feature", name) # head a = s / math.tan(math.pi / 3.0) box1 = makeBox(a, s, k) box1.translate(Vector(-0.5 * a, -0.5 * s, 0)) box1.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 30) box2 = makeBox(a, s, k) box2.translate(Vector(-0.5 * a, -0.5 * s, 0)) box2.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 150) box3 = makeBox(a, s, k) box3.translate(Vector(-0.5 * a, -0.5 * s, 0)) box3.rotate(Vector(0, 0, 0), Vector(0, 0, 1), 270) head = box1.fuse(box2).fuse(box3) shaft_unthreaded = Part.makeCylinder(0.5 * d1, l - b + k) shaft_threaded = Part.makeCylinder(0.5 * d1, b) shaft_threaded.translate(Vector(0, 0, l - b + k)) part.Shape = head.fuse(shaft_unthreaded).fuse(shaft_threaded).removeSplitter()

def make_extrusion(self, name, points, invert_order): print 'make_extrusion', name, invert_order wires = [] for section in points: pts = [] if len(section) < 3: print "warning: cross section in make_extrusion() < 3 points" print "length:", len(section) continue if not invert_order: for pt in section: # print "%.2f %.2f %.2f" % (pt[0], pt[1], pt[2]) pts.append( Base.Vector(pt[0], pt[1], pt[2]) ) pt = section[0] pts.append( Base.Vector(pt[0], pt[1], pt[2]) ) else: for pt in section: # print "%.2f %.2f %.2f" % (pt[0], pt[1], pt[2]) pts.append( Base.Vector(pt[0], pt[1], pt[2]) ) pt = section[0] pts.append( Base.Vector(pt[0], pt[1], pt[2]) ) #pt = section[0] #Base.Vector(pt[0], pt[1], pt[2]) #for pt in reversed(section): # print "%.2f %.2f %.2f" % (pt[0], pt[1], pt[2]) #pts.append( Base.Vector(pt[0], pt[1], pt[2]) ) wire = Part.makePolygon(pts) wires.append(wire) loft = Part.makeLoft(wires, False) return loft

def p_polyhedron_action(p) : '''polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA faces EQ OSQUARE path_set ESQUARE COMMA keywordargument_list RPAREN SEMICOL | polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL''' if printverbose: print("Polyhedron Points") v = [] for i in p[6] : if printverbose: print(i) v.append(FreeCAD.Vector(float(i[0]),float(i[1]),float(i[2]))) if printverbose: print(v) print ("Polyhedron "+p[9]) print (p[12]) faces_list = [] mypolyhed = doc.addObject('Part::Feature',p[1]) for i in p[12] : if printverbose: print(i) v2 = FreeCAD.Vector pp =[v2(v[k]) for k in i] # Add first point to end of list to close polygon pp.append(pp[0]) print(pp) w = Part.makePolygon(pp) f = Part.Face(w) #f = make_face(v[int(i[0])],v[int(i[1])],v[int(i[2])]) faces_list.append(f) shell=Part.makeShell(faces_list) solid=Part.Solid(shell).removeSplitter() if solid.Volume < 0: solid.reverse() mypolyhed.Shape=solid p[0] = [mypolyhed]

def gen_haus(le,wi,hiall,hi,ang,midx=0.7,wx=0.5,midy=0.5,wy=0): h=gen_haus0(le,wi,hiall,hi,midx,wx,midy,wy) print h Part.show(h) p=FreeCAD.ActiveDocument.ActiveObject p.Placement.Rotation.Angle=ang*math.pi/180 return p

def FilletFlange(innerdia = 10,filletdia = 5,filletthick=10): ff = Part.makeCylinder(innerdia/2 + filletdia/2,filletthick) fi = Part.makeCylinder(innerdia/2,filletthick+filletdia) fi.translate(Vector(0,0,-filletdia/2)) ff=ff.fuse(fi) ff=ff.fuse(ff.makeFillet(filletdia/2-0.01,[ff.Edges[3],ff.Edges[5]])) return ff

def getArea(self,obj): "returns the horizontal area at the center of the space" import Part,DraftGeomUtils if not hasattr(obj.Shape,"CenterOfMass"): return 0 try: pl = Part.makePlane(1,1) pl.translate(obj.Shape.CenterOfMass) sh = obj.Shape.copy() cutplane,v1,v2 = ArchCommands.getCutVolume(pl,sh) e = sh.section(cutplane) e = Part.__sortEdges__(e.Edges) w = Part.Wire(e) f = Part.Face(w) except Part.OCCError: return 0 else: if hasattr(obj,"PerimeterLength"): if w.Length != obj.PerimeterLength.Value: obj.PerimeterLength = w.Length if hasattr(obj,"VerticalArea"): a = 0 for f in sh.Faces: ang = f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1)) if (ang > 1.57) and (ang < 1.571): a += f.Area if a != obj.VerticalArea.Value: obj.VerticalArea = a #print "area of ",obj.Label," : ",f.Area return f.Area

def mainFrameCoeff(ship, draft): """ Calculate main frame coefficient. @param ship Selected ship instance @param draft Draft. @return Main frame coefficient """ cm = 0.0 maxY = 0.0 minY = 0.0 # We will take a duplicate of ship shape in order to place it shape = ship.Shape.copy() shape.translate(Vector(0.0,0.0,-draft)) x = 0.0 area = 0.0 # Now we need to know the x range of values bbox = shape.BoundBox xmin = bbox.XMin xmax = bbox.XMax # Create the box L = xmax - xmin B = bbox.YMax - bbox.YMin p = Vector(-1.5*L, -1.5*B, bbox.ZMin - 1.0) box = Part.makeBox(1.5*L + x, 3.0*B, - bbox.ZMin + 1.0, p) maxY = bbox.YMin minY = bbox.YMax # Compute common part with ship for s in shape.Solids: # Get solids intersection try: common = box.common(s) except: continue if common.Volume == 0.0: continue # Recompute object adding it to the scene, when we have # computed desired data we can remove it. try: Part.show(common) except: continue # Divide by faces and compute only section placed ones faces = common.Faces for f in faces: faceBounds = f.BoundBox # Orientation filter if faceBounds.XMax - faceBounds.XMin > 0.00001: continue # Place filter if abs(faceBounds.XMax - x) > 0.00001: continue # Valid face, compute area area = area + f.Area maxY = max(maxY, faceBounds.YMax) minY = min(minY, faceBounds.YMin) # Destroy last object generated App.ActiveDocument.removeObject(App.ActiveDocument.Objects[-1].Name) dy = maxY - minY if dy*draft > 0.0: cm = area / (dy*draft) return cm

def linesFromPoints(points, closed=False): lines = [] for i in range(0, len(points) - 1): lines.append(Part.makeLine(points[i], points[(i + 1) % len(points)])) if closed: lines.append(Part.makeLine(points[len(points) - 1], points[0])) return lines