Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #these import statements are always good:
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- #make a line
- l1 = Part.makeLine((0,1,0),(0,0,0))
- Part.show(l1)
- #do it with one line:
- Part.show(Part.makeLine((10,10,0),(0,0,0)))
- #make a simple circle:
- c1 = Part.makeCircle(3,Base.Vector(0,1,0))
- Part.show(c1)
- #make an arc with radius,center point, direction vector, start and end angle
- c1 = Part.makeCircle(10, Base.Vector(0,0,0), Base.Vector(0,0,1),0,90)
- Part.show(c1)
- #make it a one liner:
- Part.show(Part.makeCircle(10, Base.Vector(0,0,0), Base.Vector(0,0,1),0,90))
- #make a simple circle that is rotated about Y axis:
- c2 = Part.makeCircle(3,Base.Vector(0,1,0),Base.Vector(0,1,0))
- Part.show(c2)
- #create an arc along points:
- arc = Part.Arc(Base.Vector(5,0,0),Base.Vector(0,5,0),Base.Vector(-5,0,0))
- arc_edge = arc.toShape()
- Part.show(arc_edge)
- #creation of elements from lines and arcs:
- from FreeCAD import Base
- V1 = Base.Vector(0,10,0)
- V2 = Base.Vector(30,10,0)
- V3 = Base.Vector(30,-10,0)
- V4 = Base.Vector(0,-10,0)
- #create arc
- VC1 = Base.Vector(-10,0,0)
- C1 = Part.Arc(V1,VC1,V4)
- # and the second one
- VC2 = Base.Vector(40,0,0)
- C2 = Part.Arc(V2,VC2,V3)
- #two lines
- L1 = Part.Line(V1,V2)
- # and the second one
- L2 = Part.Line(V4,V3)
- S1 = Part.Shape([C1,C2,L1,L2])
- W = Part.Wire(S1.Edges)
- f = Part.Face(W)
- P = f.extrude(Base.Vector(0,0,2))
- Part.show(P)
- v5 = Base.Vector(0,0,0)
- v6 = Base.Vector(30,0,0)
- l3 = Part.Line(V1,v5)
- l4 = Part.Line(v5,v6)
- l5 = Part.Line(v6,V2)
- s2 = Part.Shape([L1,l3,l4,l5])
- Part.show(s2)
- w2 = Part.Wire(s2.Edges)
- f2 = Part.Face(w2)
- #revolve a profile:
- p2 = f2.revolve(Base.Vector(0,0,0),Base.Vector(1,0,0),360) #revolve a closed shape 360 degrees
- #select an object in the gui and use python to do something with it:
- s1 = Gui.Selection.getSelectionEx()
- box = s1.extrude(Base.Vector(0,0,2))
- #select two objects and give the python console access to them:
- s=FreeCADGui.Selection.getSelection()
- try:
- shape1=s[0].Shape
- shape2=s[1].Shape
- except:
- print "Wrong selection"
- #select an object in the gui and parse it in python:
- for o in Gui.Selection.getSelectionEx():
- print o.ObjectName
- for s in o.SubElementNames:
- print "name: ",s
- for s in o.SubObjects:
- print "object: ",s
- #select an object in the gui and parse it in python:
- length = 0.0
- for o in Gui.Selection.getSelectionEx() :
- for s in o.SubObjects:
- length = s.Length
- print "Length of the selected edges:" ,length
- s.Vertexes[0].X, s.Vertexes[0].Y, s.Vertexes[0].Z
- s.Vertexes[1].X, s.Vertexes[1].Y, s.Vertexes[1].Z
- for o in Gui.Selection.getSelectionEx():
- for s in o.SubObjects:
- print s.Vertexes[0].X, s.Vertexes[0].Y, s.Vertexes[0].Z
- print s.Vertexes[1].X, s.Vertexes[1].Y, s.Vertexes[1].Z
- for obj in FreeCAD.ActiveDocument.Objects:
- if hasattr(obj,"Shape"):
- print "Object: ", obj, "Shape type: ", obj.Shape.Type
- for o in Gui.Selection.getSelectionEx():
- print o.ObjectName, o.Type
- #selection stuff again:
- import FreeCAD,FreeCADGui,Part
- sel = FreeCADGui.Selection.getSelection()
- if not sel:
- FreeCAD.Console.PrintWarning("Select something first!")
- else:
- elist = []
- for obj in sel:
- if hasattr(obj,"Shape"):
- elist.append(obj.Shape.Edges[0])
- print obj
- #make a pipe:
- z=theWire.makePipe(myFaceProfile)
- from FreeCAD import Base
- V1 = Base.Vector(0,10,0)
- V2 = Base.Vector(30,10,0)
- V3 = Base.Vector(30,-10,0)
- V4 = Base.Vector(0,-10,0)
- VC1 = Base.Vector(-10,0,0)
- C1 = Part.Arc(V1,VC1,V4)
- # and the second one
- VC2 = Base.Vector(40,0,0)
- C2 = Part.Arc(V2,VC2,V3)
- L1 = Part.Line(V1,V2)
- # and the second one
- L2 = Part.Line(V4,V3)
- S1 = Part.Shape([C1,C2,L1,L2])
- W = Part.Wire(S1.Edges)
- Part.show(W)
- V5 = Base.Vector(0,10,10)
- V6 = Base.Vector(0,10,20)
- L3 = Part.Line(V1,V5)
- L4 = Part.Line(V5,V6)
- S2 = Part.Shape([L3,L4])
- W2 = Part.Wire(S2.Edges)
- Part.show(W2)
- pipe1=W2.makePipe(W)
- Part.show(pipe1)
- makeSolid=1 #change to 1 to make a solid, but it will take a while
- isFrenet=1
- pipe2 = Part.Wire(W2).makePipeShell([W],makeSolid,isFrenet)
- Part.show(pipe2)
- #DXF manipulation:
- #open a *dxf file:
- import Part,importDXF
- s = Part.Shape([importDXF.insert("/home/danfalck/Documents/My Drawings/rect_freecad_test14.dxf","Unnamed")])
- import importDXF
- importDXF.insert("/home/danfalck/Documents/My Drawings/rect_freecad_test14.dxf","Unnamed")
- importDXF.open("/home/danfalck/Documents/My Drawings/rect_freecad_test14.dxf") #opens a new document with the dxf in it
- import os
- import importDXF
- #sub class insert from importDXF
- def insert(filename,docname):
- "called when freecad imports a file"
- groupname = os.path.splitext(os.path.basename(filename))[0]
- try:
- doc=FreeCAD.getDocument(docname)
- except:
- doc=FreeCAD.newDocument(docname)
- importgroup = doc.addObject("App::DocumentObjectGroup",groupname)
- importgroup.Label = importDXF.decodeName(groupname)
- importDXF.processdxf(doc,filename)
- for l in importDXF.layers:
- importgroup.addObject(l)
- insert("/home/danfalck/Documents/My Drawings/rect_freecad_test14.dxf","Unnamed")
- #open a *step file:
- import Part
- s = Part.Shape()
- s.read("test.stp")
- #lofting
- #make two closed wires- one raised up in Z from the other
- #fill in the names of the two wires (Wire and Wire001)
- topWireOut = Part.Wire(App.ActiveDocument.Wire.Shape.Edges)
- botWireOut = Part.Wire(App.ActiveDocument.Wire001.Shape.Edges)
- loftOut = Part.makeLoft([topWireOut,botWireOut],True)
- Part.show(loftOut)
- App.activeDocument().addObject('Drawing::FeaturePage','Page')
- App.activeDocument().Page.Template = App.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg'
- App.activeDocument().addObject('Drawing::FeatureViewPart','View02')
- App.activeDocument().View.Source = App.activeDocument().Shape #change Shape by your object name, or pass it directly one of your created objects
- App.activeDocument().View.Direction = (0.0,0.0,1.0) # this is where you define the projection direction
- App.activeDocument().View.X = 150.0 # the x offset
- App.activeDocument().View.Y = 150.0 # the y offset
- App.activeDocument().Page.addObject(App.activeDocument().View)
- App.activeDocument().recompute()
- App.activeDocument().addObject('Drawing::FeaturePage','Page')
- App.activeDocument().Page.Template = App.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg'
- App.activeDocument().addObject('Drawing::FeatureViewPart','ViewIso')
- App.activeDocument().ViewIso.Source = App.activeDocument().Fillet002
- App.activeDocument().ViewIso.Direction = (1.0,.75,.75)
- App.activeDocument().ViewIso.X = 300.0
- App.activeDocument().ViewIso.Y = 140.0
- App.activeDocument().ViewIso.ShowHiddenLines = True
- App.activeDocument().Page.addObject(App.activeDocument().ViewIso)
- App.activeDocument().ViewIso.Scale = 8.0
- App.activeDocument().recompute()
- l=App.ActiveDocument.addObject("App::AnnotationLabel","Annotation")
- l.LabelText=["Hello","World!"]
- l.TextPosition = (3.0,0,0)
- l.BasePosition = (-3,-3,0)
- l.LabelText = ['changed']
- import Mesh
- s = Gui.Selection.getSelectionEx()
- Mesh.export(s,"/home/danfalck/Documents/My Drawings/sphere_test.stl")
- FreeCAD.ActiveDocument.getObject("Mesh").Mesh.write("/home/danfalck/Documents/sphere_test.stl","STL")
- #One way to make a non parametric copy of any Part-based object (change MyObjectName by the name of your object)
- import Part
- myShape = FreeCAD.ActiveDocument.MyObjectName.Shape
- Part.show(myShape)
- import Part
- myShape = FreeCAD.ActiveDocument.Box.Shape
- Part.show(myShape)
- transfMatrix = FreeCAD.Matrix()
- scaleVector = FreeCAD.Vector(2,2,2)
- transfMatrix.scale(scaleVector)
- myShape = myShape.transformGeometry(transfMatrix)
- Part.show(myShape)
- p0 = Base.Vector(0,0,-10)
- b1 = Part.makeBox ( 50,50,10,p0 )
- Part.show(b1)
- p1 = Base.Vector(15,15,-12)
- d1 = Base.Vector(0,0,1)
- c1 = Part.makeCylinder(2.5,12,p1)
- Part.show(c1)
- diff = b1.cut(c1)
- Part.show(diff)
- App.activeDocument().recompute()
- App.ActiveDocument.Shape001.ViewObject.Visibility = False #turn off visibility of an object
- FreeCADGui.addIcon()#add icon with absolute path to it
- FreeCADGui.addIcon("test", "/home/danfalck/git/heekscad/icons/HeeksCAD.svg")
- len(App.ActiveDocument.ObjectName.Shape.Vertexes)
- len(App.ActiveDocument.Circle.Shape.Vertexes)
- App.ActiveDocument.ObjectName.Shape.Vertexes
- App.ActiveDocument.Circle.Shape.Vertexes
- App.ActiveDocument.ObjectName.Shape.Edges[0].Curve
- App.ActiveDocument.Circle.Shape.Edges[0].Curve
- App.ActiveDocument.Sketch.Shape.Vertexes
- App.ActiveDocument.Sketch.Shape.Edges[0].Curve
- import Part
- from draftlibs import fcgeo
- edgeslist = []
- for obj in App.ActiveDocument.Objects:
- edgeslist.append(obj.Shape.Edges[0])
- w = fcgeo.superWire(edgeslist)
- Part.show(w)
- for obj in Gui.Selection.getSelectionEx():
- edgeslist.append(obj.Shape.Edges[0])
- #to make splines:
- import Part
- from FreeCAD import Base
- nodes=[]
- nodes.append(Base.Vector(-2.08299, 1.5702, 0))
- nodes.append(Base.Vector(-0.381617, 1.68945, 0))
- nodes.append(Base.Vector(0.882489, 1.6974, 0))
- nodes.append(Base.Vector(1.48672, 0.162982, 0))
- nodes.append(Base.Vector(0.946093, -0.878514, 0))
- nodes.append(Base.Vector(-0.628078, -0.950068, 0))
- nodes.append(Base.Vector(-0.954043, 0.043727, 0))
- nodes.append(Base.Vector(-2.50436, -0.465096, 0))
- nodes.append(Base.Vector(-2.49641, -1.30783, 0))
- nodes.append(Base.Vector(-3.19604, -0.862614, 0))
- nodes.append(Base.Vector(-3.18809, 0.99777, 0))
- b=Part.BezierCurve()
- b.setPoles(nodes)
- Part.show(b.toShape())
- Part.show(Part.makePolygon(nodes))
- spline=Part.BSplineCurve()
- spline.buildFromPoles(nodes)
- Part.show(spline.toShape())
- >>> spline.getPoles()
- [Vector (-2.08299, 1.5702, 0), Vector (-0.381617, 1.68945, 0), Vector (0.882489, 1.6974, 0), Vector (1.48672, 0.162982, 0), Vector (0.946093, -0.878514, 0), Vector (-0.628078, -0.950068, 0), Vector (-0.954043, 0.043727, 0), Vector (-2.50436, -0.465096, 0), Vector (-2.49641, -1.30783, 0), Vector (-3.19604, -0.862614, 0), Vector (-3.18809, 0.99777, 0)]
- >>>
- >>> spline.getKnots()
- [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]
- >>> spline.getKnot(1)
- 0.0
- >>> spline.getKnot(2)
- 0.125
- >>> spline.getPole(3)
- Vector (0.882489, 1.6974, 0)
- >>>
- >>> spline.tangent(2)
- (Vector (0.323401, 0.946262, 0),)
- >>> spline.tangent(0)
- (Vector (0.997553, 0.0699189, 0),)
- #look at operations available with from different functions:
- dir(FreeCAD)
- ['ActiveDocument', 'Base', 'BoundBox', 'ConfigDump', 'ConfigGet', 'ConfigSet', 'Console', 'DraftWorkingPlane', 'EndingAdd', 'EndingGet', 'Gui', 'GuiUp', 'Matrix', 'ParamGet', 'Placement', 'Rotation', 'Units', 'Vector', 'Version', '__doc__', '__name__', '__package__', '__path__', 'activeDocument', 'activeDraftCommand', 'addDocumentObserver', 'addExportType', 'addImportType', 'closeDocument', 'getDocument', 'getExportType', 'getHomePath', 'getImportType', 'getResourceDir', 'listDocuments', 'loadFile', 'newDocument', 'open', 'openDocument', 'removeDocumentObserver', 'setActiveDocument', 'svgpatterns']
- dir(Part)
- ['Arc', 'ArcOfCircle', 'BSplineCurve', 'BSplineSurface', 'BezierCurve', 'BezierSurface', 'Circle', 'CompSolid', 'Compound', 'Cone', 'Cylinder', 'Edge', 'Ellipse', 'Face', 'Feature', 'Hyperbola', 'Line', 'OffsetCurve', 'OffsetSurface', 'Parabola', 'Plane', 'RectangularTrimmedSurface', 'Shape', 'Shell', 'Solid', 'Sphere', 'SurfaceOfExtrusion', 'SurfaceOfRevolution', 'Toroid', 'Vertex', 'Wire', '__doc__', '__file__', '__fromPythonOCC__', '__name__', '__package__', '__sortEdges__', '__toPythonOCC__', 'cast_to_shape', 'export', 'getSortedClusters', 'insert', 'makeBox', 'makeCircle', 'makeCompound', 'makeCone', 'makeCylinder', 'makeFilledFace', 'makeHelix', 'makeLine', 'makeLoft', 'makePlane', 'makePolygon', 'makeRevolution', 'makeRuledSurface', 'makeShell', 'makeSolid', 'makeSphere', 'makeSweepSurface', 'makeTorus', 'makeTube', 'makeWedge', 'open', 'read', 'show']
- dir(Part.BSplineCurve)
- ['Construction', 'Degree', 'EndPoint', 'FirstParameter', 'FirstUKnotIndex', 'KnotSequence', 'LastParameter', 'LastUKnotIndex', 'MaxDegree', 'NbKnots', 'NbPoles', 'StartPoint', '__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'approximate', 'buildFromPoles', 'discretize', 'getKnot', 'getKnots', 'getMultiplicities', 'getMultiplicity', 'getPole', 'getPoles', 'getResolution', 'getWeight', 'getWeights', 'increaseDegree', 'increaseMultiplicity', 'incrementMultiplicity', 'insertKnot', 'insertKnots', 'interpolate', 'isClosed', 'isPeriodic', 'isRational', 'join', 'makeC1Continuous', 'makeRuledSurface', 'mirror', 'movePoint', 'parameter', 'removeKnot', 'rotate', 'scale', 'segment', 'setKnot', 'setKnots', 'setNotPeriodic', 'setOrigin', 'setPeriodic', 'setPole', 'setWeight', 'tangent', 'toBezier', 'toShape', 'transform', 'translate', 'value']
- >>> dir(Part.BezierCurve)
- ['Construction', 'Degree', 'EndPoint', 'FirstParameter', 'LastParameter', 'MaxDegree', 'NbPoles', 'StartPoint', '__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'discretize', 'getPole', 'getPoles', 'getResolution', 'getWeight', 'getWeights', 'increase', 'insertPoleAfter', 'insertPoleBefore', 'isClosed', 'isPeriodic', 'isRational', 'makeRuledSurface', 'mirror', 'parameter', 'removePole', 'rotate', 'scale', 'segment', 'setPole', 'setPoles', 'setWeight', 'tangent', 'toShape', 'transform', 'translate', 'value']
- >>> dir(Part.Edge)
- ['Area', 'BoundBox', 'CenterOfMass', 'Closed', 'CompSolids', 'Compounds', 'Content', 'Curve', 'Degenerated', 'Edges', 'Faces', 'Length', 'Matrix', 'MemSize', 'Module', 'Orientation', 'ParameterRange', 'Placement', 'ShapeType', 'Shells', 'Solids', 'Type', 'Vertexes', 'Volume', 'Wires', '__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'centerOfCurvatureAt', 'check', 'common', 'complement', 'copy', 'curvatureAt', 'cut', 'derivative1At', 'derivative2At', 'derivative3At', 'exportBrep', 'exportIges', 'exportStep', 'exportStl', 'extrude', 'fix', 'fuse', 'getAllDerivedFrom', 'hashCode', 'isClosed', 'isDerivedFrom', 'isEqual', 'isInside', 'isNull', 'isSame', 'isValid', 'makeChamfer', 'makeFillet', 'makeOffsetShape', 'makeShapeFromMesh', 'makeThickness', 'mirror', 'normalAt', 'nullify', 'oldFuse', 'project', 'read', 'removeInternalWires', 'removeShape', 'replaceShape', 'reverse', 'revolve', 'rotate', 'scale', 'section', 'setTolerance', 'sewShape', 'slice', 'slices', 'tangentAt', 'tessellate', 'toNurbs', 'transformGeometry', 'transformShape', 'translate', 'valueAt', 'writeInventor']
- >>>
- >>> dir(Part.Edge.Curve)
- ['__class__', '__delattr__', '__delete__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__name__', '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
- >>>
- >>> dir(Part.Edge.Vertexes)
- ['__class__', '__delattr__', '__delete__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__name__', '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
- >>>
- >>> sel = FreeCADGui.Selection.getSelection()
- >>> sel = sel[0]
- >>> name = sel.Name
- >>> shape = sel.Shape
- >>> name
- 'Fillet'
- >>> shape
- <Compound object at 0x137e830>
- #using my modified ProjectionAlgos routines:
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- filename = "/home/danfalck/Documents/freecad/test100904.dxf"
- FILE = open(filename,"w")
- sel = FreeCADGui.Selection.getSelection()
- sel = sel[0]
- shape = sel.Shape
- dxf_output = Drawing.projectToDXF(shape,Base.Vector(0,0,1))
- FILE.write(dxf_output)
- FILE.close()
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- filename = "/home/danfalck/Documents/freecad/test102801.dxf"#change the file name and directory here
- FILE = open(filename,"w")
- sel = FreeCADGui.Selection.getSelection()
- sel = sel[0]
- shape = sel.Shape
- dxf_output = Drawing.projectToDXF(shape,Base.Vector(0,0,1)) #change direction of the projection here
- FILE.write(dxf_output)
- FILE.close()
- #to make a helical thread
- import Part, FreeCAD, math
- from FreeCAD import Base
- helix = Part.makeHelix(1,10,3)
- edge1 = Part.makeLine((2.5,0,-0.125), (2.5,0,0.125))
- edge2 = Part.makeLine((2.5,0,0.125), (3.1,0,0.419))
- edge3 = Part.makeLine((3.1,0,0.419), (3.1,0,-0.419))
- edge4 = Part.makeLine((3.1,0,-0.419), (2.5,0,-0.125))
- section = Part.Wire([edge1,edge2,edge3,edge4])
- makeSolid=0 #change to 1 to make a solid, but it will take a while
- isFrenet=1
- pipe = Part.Wire(helix).makePipeShell([section],makeSolid,isFrenet)
- Part.show(pipe)
- helix = Part.makeHelix(1,10,3)
- edge1 = Part.makeLine((3.1,0,-0.125), (3.1,0,0.125))
- edge2 = Part.makeLine((3.1,0,0.125), (2.5,0,0.419))
- edge3 = Part.makeLine((2.5,0,0.419), (2.5,0,-0.419))
- edge4 = Part.makeLine((2.5,0,-0.419), (3.1,0,-0.125))
- section = Part.Wire([edge1,edge2,edge3,edge4])
- makeSolid=1 #change to 1 to make a solid, but it will take a while
- isFrenet=1
- pipe = Part.Wire(helix).makePipeShell([section],makeSolid,isFrenet)
- Part.show(pipe)
- helix = Part.makeHelix(1,-10,3)
- edge1 = Part.makeLine((3.1,0,-0.125), (3.1,0,0.125))
- edge2 = Part.makeLine((3.1,0,0.125), (2.5,0,0.419))
- edge3 = Part.makeLine((2.5,0,0.419), (2.5,0,-0.419))
- edge4 = Part.makeLine((2.5,0,-0.419), (3.1,0,-0.125))
- section = Part.Wire([edge1,edge2,edge3,edge4])
- makeSolid=1 #change to 1 to make a solid, but it will take a while
- isFrenet=1
- pipe = Part.Wire(helix).makePipeShell([section],makeSolid,isFrenet)
- Part.show(pipe)
- #pythonOCC stuff:
- #For instance you can create a box and convert that into the pythonOCC wrapper class like:
- import Part
- from OCC import TopoDS
- s=Part.makeBox(10,10,10)
- occ=Part.__toPythonOCC__(s)
- # now you can use all classes/functions which are wrapped in pythonOCC
- s=Part.__fromPythonOCC__(occ)
- Part.show(s)
- import Part, FreeCAD, math, PartGui, FreeCADGui
- from FreeCAD import Base
- #from Norman's twisted bar example:
- # pick selected objects, whre 1st selection is the trajectory and the 2nd is the section to sweep
- s = FreeCADGui.Selection.getSelection()
- try:
- shape1=s[0].Shape
- shape2=s[1].Shape
- except:
- print "Wrong selection"
- traj = Part.Wire([shape1])
- section = Part.Wire([shape2])
- # create a Part object into the active document
- myObject=App.ActiveDocument.addObject("Part::Feature","Sweep")
- makeSolid = 1
- isFrenet = 1
- # Create the 3D shape and set it to the Part object
- Sweep = Part.Wire(traj).makePipeShell([section],makeSolid,isFrenet)
- myObject.Shape = Sweep
- #slicing objects to look at cross sections:
- #That's correct but it is a bit inconvenient when making many slices because then you must for #each slice prepare an own plane object. With the latest sources I have added two commands.
- #slices -- which accepts a Vector (the normal of the plane) and a list of doubles. The doubles #mark the distances of the current plane to the origin. The returned object is a compound #containing all slices.
- #slice -- which accepts a Vector and a single double to make only one slice. The returned
- #object is a list of wires.
- from FreeCAD import Base
- shape=Part.makeCylinder(5,15)
- slices=shape.slices(Base.Vector(0,0,1),[0,0.5,1.0])
- slice=shape.slice(Base.Vector(0,1,0),1.5)
- Part.show(slices)
- comp=Part.Compound(slice)
- Part.show(comp)
- #name your object:
- import Part
- doc = App.activeDocument()
- c = Part.Circle()
- c.Radius=10.0
- f = doc.addObject("Part::Feature", "Name_of_Circle_here") # create a document with a circle feature
- f.Shape = c.toShape() # Assign the circle shape to the shape property
- doc.recompute()
- #hide it:
- Gui.activeDocument().hide('Name_of_Circle_here')
- #show it:
- Gui.activeDocument().show('Name_of_Circle_here')
- #Adding and removing an object to a group
- doc=App.activeDocument()
- grp=doc.addObject("App::DocumentObjectGroup", "Group1")
- grp.addObject(f) # adds the circle (f) object to the group grp
- grp.removeObject(f) # removes the circle object from the group grp
- #in draft mode, create and select an arc
- for o in Gui.Selection.getSelectionEx():
- for s in o.SubObjects:
- print s.Vertexes[0].X, s.Vertexes[0].Y, s.Vertexes[0].Z
- print s.Vertexes[1].X, s.Vertexes[1].Y, s.Vertexes[1].Z
- print s.Curve.Center.x,s.Curve.Center.y, s.Curve.Center.z
- for o in Gui.Selection.getSelectionEx():
- for c in o.SubObjects:
- print c.Vertexes[0].X, c.Vertexes[0].Y, c.Vertexes[0].Z
- c.Curve.__class__
- #returns: <type 'Part.GeomCircle'>
- #select several arcs and lines (from a sketch element)
- sel= Gui.Selection.getSelectionEx()
- a = sel[0]
- b = sel[1]
- a.ObjectName
- #returns Name such as 'Arc'
- b.ObjectName
- #returns Name such as 'Line002'
- #sorting edges from wmayer:
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- #then you can see what the edges are:
- edges[0].Curve
- #might return:
- #Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- edges[0].Curve.Center.x
- edges[0].Curve.Center.y
- >>> edges[0].Vertexes[0].X
- 0.0
- >>> edges[0].Vertexes[0].Y
- 3.0000000000000004
- >>>
- edges2=[]
- k=Gui.Selection.getSelectionEx()
- for i in k:
- for e in i.SubElementNames:
- edges2.append(getattr(i.Object.Shape,e))
- edges2[0].Curve
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- #export a shape to a *.stl file
- #select it first
- from FreeCAD import Part
- s=Gui.Selection.getSelectionEx()
- s[0].Object.Shape.exportStl('/home/danfalck/test2.stl')
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- #might return:
- #Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- #<Line (10;0,0) (10;10,0) >
- #<Line (3;0,0) (10;0,0) >
- #<Line (0;3,0) (0;10,0) >
- #<Line (0;10,0) (10;10,0) >
- edges.reverse()
- # do this again:
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- #returns this:
- #<Line (0;10,0) (10;10,0) >
- #<Line (0;3,0) (0;10,0) >
- #<Line (3;0,0) (10;0,0) >
- #<Line (10;0,0) (10;10,0) >
- #Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- edges=[]
- s=Gui.Selection.getSelectionEx()
- s.sort() # <<<<<sorting edges
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- #returns:
- <Line (3;0,0) (10;0,0) >
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- <Line (0;3,0) (0;10,0) >
- <Line (0;10,0) (10;10,0) >
- <Line (10;0,0) (10;10,0) >
- s.pop() #<<<<<<<<<removes last item from list
- edges=[]
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- <Line (10;0,0) (10;10,0) >
- <Line (0;10,0) (10;10,0) >
- <Line (3;0,0) (10;0,0) >
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- s.reverse()
- edges=[]
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- #returns:
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- <Line (3;0,0) (10;0,0) >
- <Line (0;10,0) (10;10,0) >
- <Line (10;0,0) (10;10,0) >
- s.sort()
- edges=[]
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- inx = 0
- while (inx <len(edges)):
- print edges[inx].Curve
- inx = inx+1
- #returns:
- <Line (10;0,0) (10;10,0) >
- <Line (0;10,0) (10;10,0) >
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- <Line (3;0,0) (10;0,0) >
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- print type(s)
- for obj in FreeCAD.ActiveDocument.Objects:
- if hasattr(obj,"Shape"):
- print "Object: ", obj, "Shape type: ", obj.Shape.Type
- #sorting with __sortEdges__
- >>> edge1 = Part.makeLine((0,0,0), (10,0,0))
- >>> edge2 = Part.makeLine((10,0,0), (10,10,0))
- >>> wire1 = Part.Wire([edge1,edge2])
- >>> edge3 = Part.makeLine((10,10,0), (0,10,0))
- >>> edge4 = Part.makeLine((0,10,0), (0,0,0))
- >>> wire2 = Part.Wire([edge3,edge4])
- >>> wire3 = Part.Wire([wire1,wire2])
- >>> wire3.Edges
- [<Edge object at 0x17cb070>, <Edge object at 0x188b730>, <Edge object at 0xb16270>, <Edge object at 0x17ce970>]
- >>> face = Part.Face(wire3)
- >>> face2 = Part.__sortEdges__(wire3)
- Traceback (most recent call last):
- File "<input>", line 1, in <module>
- Exception: list of edges expected
- >>> face3 = Part.__sortEdges__(edge1,edge2,edge3,edge4)
- Traceback (most recent call last):
- File "<input>", line 1, in <module>
- Exception: list of edges expected
- >>> face3 = Part.__sortEdges__([edge1,edge2,edge3,edge4])
- >>> face3
- [<Edge object at 0x18ae080>, <Edge object at 0x17dc3d0>, <Edge object at 0x1888760>, <Edge object at 0xd045c0>]
- >>> face4 = Part.__sortEdges___([edge3,edge1,edge2,edge4])
- Traceback (most recent call last):
- File "<input>", line 1, in <module>
- AttributeError: 'module' object has no attribute '__sortEdges___'
- >>> face3 = Part.__sortEdges__([edge1,edge2,edge3,edge4])
- >>> face4 = Part.__sortEdges__([edge1,edge2,edge3,edge4])
- >>> face4 = Part.__sortEdges__([edge2,edge3,edge4,edge1])
- >>> face4
- [<Edge object at 0x18aa220>, <Edge object at 0x18b3c60>, <Edge object at 0x13fb670>, <Edge object at 0x18afa30>]
- >>> face4
- [<Edge object at 0x18aa220>, <Edge object at 0x18b3c60>, <Edge object at 0x13fb670>, <Edge object at 0x18afa30>]
- >>> face4[0]
- <Edge object at 0x18aa220>
- >>> face4[0].Curve
- <Line (10;0,0) (10;10,0) >
- >>> face4[1].Curve
- <Line (10;10,0) (0;10,0) >
- >>> face4[2].Curve
- <Line (0;10,0) (0;0,0) >
- >>> face4[3].Curve
- <Line (0;0,0) (10;0,0) >
- #select from the gui window- not the tree
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S1 = Part.Wire(edges)
- S2.__sortEdges__([edges[0], edges[1], edges[2], edges[3], edges[4]])
- [<Edge object at 0x18c9910>, <Edge object at 0x18a83d0>, <Edge object at 0x188be00>, <Edge object at 0x186e0e0>, <Edge object at 0x18bfd10>]
- S3.__sortEdges__(edges)
- >>> S3 =Part
- >>> S3.__sortEdges__(edges)
- [<Edge object at 0x13c3280>, <Edge object at 0x18c95c0>, <Edge object at 0x18659c0>, <Edge object at 0x18c9470>, <Edge object at 0x18a9090>]
- >>>
- S4 = S3.__sortEdges__(edges)
- S4[0].Curve
- <Line (3;0,0) (10;0,0) >
- >>> S4[1].Curve
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- >>> S4[2].Curve
- <Line (0;3,0) (0;10,0) >
- >>> S4[3].Curve
- <Line (0;10,0) (10;10,0) >
- >>> S4[4].Curve
- <Line (10;0,0) (10;10,0) >
- >>>
- inx = 0
- while (inx <len(S4)):
- print S4[inx].Curve
- inx = inx+1
- <Line (3;0,0) (10;0,0) >
- Circle (Radius : 3, Position : (3, 3, 0), Direction : (0, 0, 1))
- <Line (0;3,0) (0;10,0) >
- <Line (0;10,0) (10;10,0) >
- <Line (10;0,0) (10;10,0) >
- >>> S4[0].Curve.__class__
- <type 'Part.GeomLineSegment'>
- >>> S4[3].Curve.__class__
- <type 'Part.GeomLineSegment'>
- >>> S4[2].Curve.__class__
- <type 'Part.GeomLineSegment'>
- >>> S4[1].Curve.__class__
- <type 'Part.GeomCircle'>
- >>>
- >>> S4[1].Curve.__class__.__name__
- 'GeomCircle'
- >>> S4[0].Curve.__class__.__name__
- 'GeomLineSegment'
- >>> S4[0].Vertexes
- [<Vertex object at 0x18bf8d0>, <Vertex object at 0x18a3ab0>]
- >>> S4[0].Vertexes[0]
- <Vertex object at 0x18cac10>
- >>>
- >>> S4[0].Vertexes[0].X
- 3.0
- print S4[1].Curve.__class__.__name__, S4[1].Vertexes[0].X,S4[1].Vertexes[0].Y
- print S4[1].Curve.__class__.__name__, S4[1].Vertexes[1].X,S4[1].Vertexes[1].Y
- print S4[1].Curve.__class__.__name__, S4[1].Curve.Center.x,S4[1].Curve.Center.y
- GeomCircle3.03.0
- print S4[1].Curve.__class__.__name__
- print "start pt: X"+str(S4[1].Vertexes[0].X)+', Y'+str(S4[1].Vertexes[0].Y)
- print "center pt: X"+str(S4[1].Curve.Center.x)+', Y'+str(S4[1].Curve.Center.y)
- print "end pt: X"+str(S4[1].Vertexes[1].X)+', Y'+str(S4[1].Vertexes[1].Y)
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- #select from the gui window- not the tree
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S3 =Part
- S4 = S3.__sortEdges__(edges)
- inx = 0
- while (inx <len(S4)):
- if (S4[inx].Curve.__class__.__name__ == 'GeomCircle'):
- if S4[0].Closed:
- print '--Circle--'
- print "center pt: X "+str(S4[inx].Curve.Center.x)+', Y '+str(S4[inx].Curve.Center.y)\
- +" Radius: "+str(S4[inx].Curve.Radius)
- else:
- print '--Arc--'
- print "start pt: X "+str(S4[inx].Vertexes[0].X)+', Y '+str(S4[inx].Vertexes[0].Y)\
- +" center pt: X "+str(S4[inx].Curve.Center.x)+', Y '+str(S4[inx].Curve.Center.y)\
- +" end pt: X "+str(S4[inx].Vertexes[inx].X)+', Y '+str(S4[inx].Vertexes[1].Y)\
- +" Radius: "+str(S4[inx].Curve.Radius)
- else:
- print '--Line--'
- print "start pt: X "+str(S4[inx].Vertexes[0].X)+', Y '+str(S4[inx].Vertexes[0].Y)\
- +" end pt: X "+str(S4[inx].Vertexes[1].X)+', Y '+str(S4[inx].Vertexes[1].Y)
- inx = inx+1
- S4[0].Curve.Radius #get the radius of a circle or arc
- #check to see if Circle is really a 'Circle' or an 'Arc'
- >>> edges=[]
- >>> s=Gui.Selection.getSelectionEx()
- >>> for i in s:
- ... for e in i.SubElementNames:
- ... edges.append(getattr(i.Object.Shape,e))
- ...
- >>> S3 =Part
- >>> S4 = S3.__sortEdges__(edges)
- >>>
- >>> S4
- [<Edge object at 0x18e9620>]
- >>> S4[0].Closed
- True #<<<<<<<<<<<it's a circle because it's closed
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- #select from the gui window- not the tree
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S3 =Part
- S4 = S3.__sortEdges__(edges)
- inx = 0
- while (inx <len(S4)):
- if (S4[inx].Curve.__class__.__name__ == 'GeomCircle'):
- if S4[0].Closed:
- print '--Circle--'
- print "center pt: X "+str(S4[inx].Curve.Center.x)+', Y '+str(S4[inx].Curve.Center.y)\
- +" Radius: "+str(S4[inx].Curve.Radius)
- else:
- print '--Arc--'
- print "start pt: X "+str(S4[inx].Vertexes[0].X)+', Y '+str(S4[inx].Vertexes[0].Y)\
- +" center pt: X "+str(S4[inx].Curve.Center.x)+', Y '+str(S4[inx].Curve.Center.y)\
- +" end pt: X "+str(S4[inx].Vertexes[1].X)+', Y '+str(S4[inx].Vertexes[1].Y)\
- +" Radius: "+str(S4[inx].Curve.Radius)\
- +" Direction: "+str(S4[inx].Curve.Axis)
- else:
- print '--Line--'
- print "start pt: X "+str(S4[inx].Vertexes[0].X)+', Y '+str(S4[inx].Vertexes[0].Y)\
- +" end pt: X "+str(S4[inx].Vertexes[1].X)+', Y '+str(S4[inx].Vertexes[1].Y)
- inx = inx+1
- --Line--
- start pt: X 24.42911, Y 15.25673 end pt: X -18.1368, Y 15.25673
- --Arc--
- start pt: X -18.1368, Y 15.25673 center pt: X -18.1368, Y 9.086716 end pt: X -24.306814, Y 9.086716 Radius: 6.170014 Direction: Vector (0, 0, 1)
- --Line--
- start pt: X -24.306814, Y 9.086716 end pt: X -24.306814, Y -10.557453
- --Arc--
- start pt: X -24.306814, Y -10.557453 center pt: X -18.62915, Y -10.557453 end pt: X -18.62915, Y -16.235117 Radius: 5.677664 Direction: Vector (0, 0, 1)
- --Line--
- start pt: X -18.62915, Y -16.235117 end pt: X 23.017835, Y -16.235117
- --Arc--
- start pt: X 23.017835, Y -16.235117 center pt: X 23.017835, Y -10.054202 end pt: X 29.19875, Y -10.054202 Radius: 6.180915 Direction: Vector (0, 0, 1)
- --Line--
- start pt: X 29.19875, Y -10.054202 end pt: X 29.19875, Y 10.48709
- --Arc--
- start pt: X 29.19875, Y 10.48709 center pt: X 24.42911, Y 10.48709 end pt: X 24.42911, Y 15.25673 Radius: 4.76964 Direction: Vector (0, 0, 1)
- #############################################
- ### HeeksCNC related scripting
- #############################################
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S3 =Part
- S4 = S3.__sortEdges__(edges)
- w1 = Part.Wire(S4)
- #check to see if shape is closed
- #w1.isClosed()
- #make an offset
- #o1 = w1.makeOffset(10)
- #Part.show(o1)
- if (S4[0].Vertexes[0].X == S4[1].Vertexes[1].X) and (S4[0].Vertexes[0].Y == S4[1].Vertexes[1].Y):
- print 'curve = area.Curve()\n' \
- +'curve.append(area.Point(' +str(S4[0].Vertexes[1].X) + ',' + str(S4[0].Vertexes[1].Y)+'))\n'\
- +'curve.append(area.Point(' +str(S4[0].Vertexes[0].X) + ',' + str(S4[0].Vertexes[0].Y)+'))\n'
- else:
- print 'curve = area.Curve()\n' \
- +'curve.append(area.Point(' +str(S4[0].Vertexes[0].X) + ',' + str(S4[0].Vertexes[0].Y)+'))\n'\
- +'curve.append(area.Point(' +str(S4[0].Vertexes[1].X) + ',' + str(S4[0].Vertexes[1].Y)+'))\n'
- inx = 1
- while (inx <len(S4)):
- if (S4[inx].Curve.__class__.__name__ == 'GeomCircle'):
- if S4[inx].Closed:
- print '#--Warning->Circle--'
- #print "center pt: X "+str(S4[inx].Curve.Center.x)+', Y '+str(S4[inx].Curve.Center.y)\
- #+" Radius: "+str(S4[inx].Curve.Radius)
- else:
- if (S4[inx-1].Vertexes[0].X == S4[inx].Vertexes[1].X) and (S4[inx-1].Vertexes[0].Y == S4[inx].Vertexes[1].Y):
- print 'curve.append(area.Vertex('+str(int(1*(S4[inx].Curve.Axis[2])))+', area.Point('+str(S4[inx].Vertexes[0].X)+', '+str(S4[inx].Vertexes[0].Y)\
- +'), area.Point('+str(S4[inx].Curve.Center.x)+', '+str(S4[inx].Curve.Center.y)\
- +')))\n'
- #+" Radius: "+str(S4[inx].Curve.Radius)\
- #+" Direction: "+str(S4[inx].Curve.Axis)
- else:
- print 'curve.append(area.Vertex('+str(1*(int(S4[inx].Curve.Axis[2])))+', area.Point('+str(S4[inx].Vertexes[1].X)+', '+str(S4[inx].Vertexes[1].Y)\
- +'), area.Point('+str(S4[inx].Curve.Center.x)+', '+str(S4[inx].Curve.Center.y)\
- +')))\n'
- else:
- #print '--Line--'
- if (S4[inx-1].Vertexes[0].X == S4[inx].Vertexes[1].X) and (S4[inx-1].Vertexes[0].Y == S4[inx].Vertexes[1].Y):
- print 'curve.append(area.Point(' +str(S4[inx].Vertexes[0].X) + ',' + str(S4[inx].Vertexes[0].Y)+'))\n'
- else:
- print 'curve.append(area.Point(' +str(S4[inx].Vertexes[1].X) + ',' + str(S4[inx].Vertexes[1].Y)+'))\n'
- inx = inx+1
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S1 =Part
- S2 = S1.__sortEdges__(edges)
- w1 = Part.Wire(S2)
- o1 = w1.makeOffset(1)
- Part.show(o1)
- import Part,Drawing,FreeCADGui,FreeCAD
- from FreeCAD import Base
- edges=[]
- s=Gui.Selection.getSelectionEx()
- for i in s:
- for e in i.SubElementNames:
- edges.append(getattr(i.Object.Shape,e))
- S3 =Part
- S4 = S3.__sortEdges__(edges)
- w1 = Part.Wire(S4)
- o1 = w1.makeOffset(1.5)
- Part.show(o1)
- #One way to make a non parametric copy of any Part-based object (change MyObjectName by the name of your object)
- import Part
- myShape = FreeCAD.ActiveDocument.Sketch.Shape
- Part.show(myShape)
- #select an object in the gui and parse it in python:
- for o in Gui.Selection.getSelectionEx():
- print o.ObjectName
- for s in o.SubElementNames:
- print "name: ",s
- for s in o.SubObjects:
- print "object: ",s
- #Adding and removing an object to a group
- doc=App.activeDocument()
- grp=doc.addObject("App::DocumentObjectGroup", "Group1")
- grp.addObject(f) # adds the circle (f) object to the group grp
- grp.removeObject(f) # removes the circle object from the group grp
- #create a pyqt dialog and display it:
- from PyQt4 import QtGui
- import sys
- sys.path.insert(0,'/home/danfalck/cadcam/freecad/')
- import create_plane
- d = QtGui.QWidget()
- d.ui = create_plane.Ui_Dialog()
- d.ui.setupUi(d)
- d.show()
- import sys
- sys.path.insert(0,'/home/danfalck/cadcam/freecad/')
- import create_plane
- create_plane.plane()
- #rotate view 90 degrees
- import math
- from pivy import coin
- cam = Gui.ActiveDocument.ActiveView.getCameraNode()
- rot = coin.SbRotation()
- rot.setValue(coin.SbVec3f(0,0,1),math.pi/2)
- nrot = cam.orientation.getValue() * rot
- cam.orientation = nrot
- import Part, FreeCAD, math
- from FreeCAD import Base
- helix = Part.makeHelix(1,10,3)
- edge1 = Part.makeLine((2.5,0,-0.125), (2.5,0,0.125))
- edge2 = Part.makeLine((2.5,0,0.125), (3.1,0,0.419))
- edge3 = Part.makeLine((3.1,0,0.419), (3.1,0,-0.419))
- edge4 = Part.makeLine((3.1,0,-0.419), (2.5,0,-0.125))
- section = Part.Wire([edge1,edge2,edge3,edge4])
- makeSolid=0
- isFrenet=1
- pipe = Part.Wire(helix).makePipeShell([section],makeSolid,isFrenet)
- Part.show(pipe)
- import Part, FreeCAD, math
- from FreeCAD import Base
- V1 = Base.Vector(0,0,0)
- V2 = Base.Vector(0,0,10)
- line = Part.Line(V1,V2)
- edge = line.toShape()
- edge1 = Part.makeLine((-1.0,-1.0,0.0), (1.0,-1.0,0.0))
- edge2 = Part.makeLine((1.0,-1.0,0.0), (1.0,1.0,0))
- edge3 = Part.makeLine((1.0,1.0,0), (-1.0,1.0,-0))
- edge4 = Part.makeLine((-1.0,1.0,-0), (-1.0,-1.0,-0))
- section = Part.Wire([edge1,edge2,edge3,edge4])
- Part.show(c1)
- Part.show(wire1)
- makeSolid=0
- isFrenet=1
- pipe = Part.Wire(edge).makePipeShell([section],makeSolid,isFrenet)
- Part.show(pipe)
- #<<<<<<<<<<<<<<<<<<<<<<<<<<<arcs
- import Part, FreeCAD, math
- from FreeCAD import Base
- V1 = Base.Vector(0,0,0)
- V2 = Base.Vector(0,0,10)
- line = Part.Line(V1,V2)
- edge = line.toShape()
- vc1 = Base.Vector(0,-10,0)
- vc2 = Base.Vector(10,0,0)
- vc3 = Base.Vector(0, 10, 0)
- vc4 = Base.Vector(-10,0,0)
- arc1 = Part.Arc(vc1,vc2,vc3)
- arc2 = Part.Arc(vc1,vc4,vc3)
- circ1= Part.Shape([arc1,arc2])
- s1 = Part.Wire(circ1.Edges)
- makeSolid=1
- isFrenet=1
- pipe = Part.Wire(edge).makePipeShell([s1],makeSolid,isFrenet)
- Part.show(pipe)
- object=App.ActiveDocument.addObject("Part::Feature","G1")
- object.Shape=Part.makeLine((4.0 ,4.0 ,0.0 ),( 3.204 ,-19.641 ,0.0))
- object.ViewObject.LineColor = (1.0,0.0,0.0) #red
- object=App.ActiveDocument.addObject("Part::Feature","G2")
- object.Shape=Part.makeCircle(0.254, Base.Vector(2.95,-19.641,-0.793), Base.Vector(0,0,1),0.0,90.0)
- object.ViewObject.LineColor = (0.0,1.0,0.0)#green
- object.ViewObject.LineWidth = .50
- #make a compound:
- shapes = []
- l1 = (Part.makeLine((3.9089 ,0.1209 ,-0.5999 ),( 0.8871 ,0.1209 ,-0.5999)))
- shapes.append(l1)
- l2 = (Part.makeLine((0.8871 ,0.1209 ,-0.5999 ),( 0.8871 ,0.1209 ,0.2218)))
- shapes.append(l2)
- l3 = (Part.makeLine((0.8871 ,0.1209 ,0.2218 ),( -1.0 ,1.0 ,0.2218)))
- shapes.append(l3)
- comp = Part.makeCompound(shapes)
- #make a compound with change line color and line weight
- shapes = []
- l = (Part.makeLine((3.9089 ,0.1209 ,-0.5999 ),( 0.8871 ,0.1209 ,-0.5999)))
- shapes.append(l)
- l = (Part.makeLine((0.8871 ,0.1209 ,-0.5999 ),( 0.8871 ,0.1209 ,0.2218)))
- shapes.append(l)
- l = (Part.makeLine((0.8871 ,0.1209 ,0.2218 ),( -1.0 ,1.0 ,0.2218)))
- shapes.append(l)
- object=App.ActiveDocument.addObject("Part::Feature","path")
- object.Shape=Part.makeCompound(shapes)
- object.ViewObject.LineColor = (0.0,1.0,0.0)#green
- object.ViewObject.LineWidth = 4.0
- def arc_angle(start_pt,end_pt,cen_pt):
- """Return correct direction of arc- for arcs less than 180 degrees """
- #move the arc so that center is at origin for easy calcs
- new_start = start_pt.sub(cen_pt))
- new_end = end_pt.sub(cen_pt))
- angle1= fcvec.angle(new_start,(0,0,0))
- angle2= fcvec.angle(new_end,(0,0,0))
- #subtract angle1 from angle2
- angle_diff= (angle2-angle1)
- return angle_diff
- def arc_angle2(start_pt,mid_pt,cen_pt):
- """Return direction of arc- for CNC operations-works for arcs less than 180 degrees """
- #move the arc so that center is at origin for easy calcs
- new_start=sub_pt(start_pt,cen_pt)
- new_mid =sub_pt(mid_pt,cen_pt)
- angle1= p2p_angle((0,0),new_start)
- angle2= p2p_angle((0,0),new_mid)
- #subtract angle1 from angle2
- angle_diff= (angle2-angle1)
- return angle_diff
- #parse a profile
- import math
- from draftlibs import fcvec
- from FreeCAD import Vector
- for o in Gui.Selection.getSelectionEx():
- print o.ObjectName
- for s in o.SubElementNames:
- print "name: ",s
- for s in o.SubObjects:
- print "object: ",s
- ve1 =s.Vertexes[0].Point
- ve2 =s.Vertexes[-1].Point
- ce = s.Curve.Center
- ang1=-math.degrees(fcvec.angle(ve1.sub(ce)))
- ang2=-math.degrees(fcvec.angle(ve2.sub(ce)))
- cross1 = Vector.cross(ce,ve1)
- cross2 = Vector.cross(ce,ve2)
- cross3 = Vector.cross(ve1,ve2)
- cross4 = Vector.cross(ve2,ce)
- print cross1, cross2,cross3,cross4
- angle = abs(fcvec.angle(ve1.sub(ce),ve2.sub(ce)))
- bul = math.tan(angle/4) #bulge
- cross_product1 = Vector.cross(ce,ve1)
- cross_product2 = Vector.cross(ce,ve2)
- print ce, ve1, ve2
- print cross_product1,cross_product2
- print fcvec.angle(ve1)
- print fcvec.angle(ve2)
- print fcvec.angle(ve1,ve2)
- print s.centerOfCurvatureAt(.5)#midpoint of arc
- if (fcvec.angle(ve2.sub(ce)) < fcvec.angle(ve1.sub(ce))):
- print 'clockwise'
- import math
- from draftlibs import fcvec,fcgeo
- from FreeCAD import Vector
- for o in Gui.Selection.getSelectionEx():
- for s in o.SubObjects:
- if (isinstance(s.Curve,Part.Circle)):
- mp = fcgeo.findMidpoint(s)
- ce = s.Curve.Center
- print "circle-start_pt: ",s.Vertexes[0].Point," center_pt:", s.Curve.Center , "mid_pt: ",mp, " end_pt: ",s.Vertexes[-1].Point
- elif (isinstance(s.Curve,Part.Line)):
- print "line-start_pt: ",s.Vertexes[0].Point, " end_pt: ",s.Vertexes[-1].Point
- else:
- print "unknown"
- import math
- from draftlibs import fcvec,fcgeo
- from FreeCAD import Vector
- edges_e = Gui.Selection.getSelectionEx()
- sorted_edges = fcgeo.sortEdges(edges_e, edges_e[0].Vertexes[0] )
- #select first edge
- edge1 = []
- for edges in Gui.Selection.getSelectionEx():
- for s in o.SubObjects:
- edge1.append(s)
- first = edge1[0].Curve
- print edge1
- #select group of connected edges
- olEdges = [] # ol stands for ordered list
- for edges in Gui.Selection.getSelectionEx():
- for s in edges.SubObjects:
- olEdges.append(s)
- if (isinstance(s.Curve,Part.Circle)):
- mp = fcgeo.findMidpoint(s)
- ce = s.Curve.Center
- print "circle-start_pt: ",s.Vertexes[0].Point," center_pt:", s.Curve.Center , "mid_pt: ",mp, " end_pt: ",s.Vertexes[-1].Point
- elif (isinstance(s.Curve,Part.Line)):
- print "line-start_pt: ",s.Vertexes[0].Point, " end_pt: ",s.Vertexes[-1].Point
- else:
- print "unknown"
- sorted_edges = []
- sorted_edges = fcgeo.sortEdges(olEdges,olEdges[0].Vertexes[0])
- for s in sorted_edges:
- olEdges.append(s)
- if (isinstance(s.Curve,Part.Circle)):
- mp = fcgeo.findMidpoint(s)
- ce = s.Curve.Center
- print "circle-start_pt: ",s.Vertexes[0].Point," center_pt:", s.Curve.Center , "mid_pt: ",mp, " end_pt: ",s.Vertexes[-1].Point
- elif (isinstance(s.Curve,Part.Line)):
- print "line-start_pt: ",s.Vertexes[0].Point, " end_pt: ",s.Vertexes[-1].Point
- else:
- print "unknown"
- #from an open profile:
- #unsorted:
- circle-start_pt: Vector (-20.024, 59.6741, 0) center_pt:Vector (-20.024, 48.4448, 0)mid_pt: Vector (-27.9644, 56.3851, 0) end_pt: Vector (-31.2534, 48.4448, 0)
- line-start_pt: Vector (-67.02, -47.7771, 0) end_pt: Vector (2.73822, -47.7771, 0)
- line-start_pt: Vector (-38.7431, 33.4251, 0) end_pt: Vector (-67.1174, 33.4251, 0)
- circle-start_pt: Vector (-38.7431, 33.4251, 0) center_pt:Vector (-38.7431, 40.9147, 0)mid_pt: Vector (-33.4471, 35.6187, 0) end_pt: Vector (-31.2534, 40.9147, 0)
- line-start_pt: Vector (-31.2534, 48.4448, 0) end_pt: Vector (-31.2534, 40.9147, 0)
- line-start_pt: Vector (49.5321, 59.6741, 0) end_pt: Vector (-20.024, 59.6741, 0)
- circle-start_pt: Vector (55.0475, 54.1588, 0) center_pt:Vector (49.5321, 54.1588, 0)mid_pt: Vector (53.4321, 58.0587, 0) end_pt: Vector (49.5321, 59.6741, 0)
- line-start_pt: Vector (55.0475, -8.87558, 0) end_pt: Vector (55.0475, 54.1588, 0)
- circle-start_pt: Vector (49.3822, -14.5408, 0) center_pt:Vector (49.3822, -8.87558, 0)mid_pt: Vector (53.3882, -12.8815, 0) end_pt: Vector (55.0475, -8.87558, 0)
- line-start_pt: Vector (16.1482, -14.5408, 0) end_pt: Vector (49.3822, -14.5408, 0)
- circle-start_pt: Vector (16.1482, -14.5408, 0) center_pt:Vector (16.1482, -22.6633, 0)mid_pt: Vector (10.4048, -16.9198, 0) end_pt: Vector (8.0258, -22.6633, 0)
- line-start_pt: Vector (8.0258, -42.4895, 0) end_pt: Vector (8.0258, -22.6633, 0)
- circle-start_pt: Vector (2.73822, -47.7771, 0) center_pt:Vector (2.73822, -42.4895, 0)mid_pt: Vector (6.4771, -46.2284, 0) end_pt: Vector (8.0258, -42.4895, 0)
- #sorted:
- line-start_pt: Vector (-67.02, -47.7771, 0) end_pt: Vector (2.73822, -47.7771, 0)
- circle-start_pt: Vector (2.73822, -47.7771, 0) center_pt:Vector (2.73822, -42.4895, 0)mid_pt: Vector (6.4771, -46.2284, 0) end_pt: Vector (8.0258, -42.4895, 0)
- line-start_pt: Vector (8.0258, -42.4895, 0) end_pt: Vector (8.0258, -22.6633, 0)
- circle-start_pt: Vector (8.0258, -22.6633, 0) center_pt:Vector (16.1482, -22.6633, 0)mid_pt: Vector (10.4048, -16.9198, 0) end_pt: Vector (16.1482, -14.5408, 0)
- line-start_pt: Vector (16.1482, -14.5408, 0) end_pt: Vector (49.3822, -14.5408, 0)
- circle-start_pt: Vector (49.3822, -14.5408, 0) center_pt:Vector (49.3822, -8.87558, 0)mid_pt: Vector (53.3882, -12.8815, 0) end_pt: Vector (55.0475, -8.87558, 0)
- line-start_pt: Vector (55.0475, -8.87558, 0) end_pt: Vector (55.0475, 54.1588, 0)
- circle-start_pt: Vector (55.0475, 54.1588, 0) center_pt:Vector (49.5321, 54.1588, 0)mid_pt: Vector (53.4321, 58.0587, 0) end_pt: Vector (49.5321, 59.6741, 0)
- line-start_pt: Vector (49.5321, 59.6741, 0) end_pt: Vector (-20.024, 59.6741, 0)
- circle-start_pt: Vector (-20.024, 59.6741, 0) center_pt:Vector (-20.024, 48.4448, 0)mid_pt: Vector (-27.9644, 56.3851, 0) end_pt: Vector (-31.2534, 48.4448, 0)
- line-start_pt: Vector (-31.2534, 48.4448, 0) end_pt: Vector (-31.2534, 40.9147, 0)
- circle-start_pt: Vector (-31.2534, 40.9147, 0) center_pt:Vector (-38.7431, 40.9147, 0)mid_pt: Vector (-33.4471, 35.6187, 0) end_pt: Vector (-38.7431, 33.4251, 0)
- line-start_pt: Vector (-38.7431, 33.4251, 0) end_pt: Vector (-67.1174, 33.4251, 0)
- #select a sketch in the tree:
- lEdges = []
- for edges in Gui.Selection.getSelectionEx():
- for s in edges.Object.Geometry:
- lEdges.append(s)
- #print s
- print lEdges
- import math
- from draftlibs import fcvec,fcgeo
- from FreeCAD import Vector,Base
- #select sketch from the gui window- not the tree
- edges=[]
- for i in Gui.Selection.getSelectionEx():
- if i.ObjectName == 'Sketch':
- for e in i.Object.Geometry:
- if type(e) is Part.ArcOfCircle:
- tang1 = e.tangent(e.FirstParameter) ; tang2 = e.tangent(e.LastParameter)
- print "Arc -radius: " , e.Radius, " center: ", e.Center, " start angle: ", e.FirstParameter, " end angle: ", e.LastParameter, " tang1: " ,tang1, " tang2: " , tang2
- print "Cross Product: " , Vector.cross(Base.Vector(tang1[0][0],tang1[0][1],tang1[0][2]),Base.Vector(tang2[0][0],tang2[0][1],tang2[0][2]))
- elif type(e)is Part.Line:
- print "Line - start point: ", e.StartPoint , " end point: " , e.EndPoint
- i.Object.Shape.Edges
- i.Object.Shape.Edges[0].Vertexes[0].X
- i.Object.Shape.Edges[0].Curve
- for i in Gui.Selection.getSelectionEx():
- if i.ObjectName == 'Sketch':
- print "true"
- i.Object.Shape.Edges[0].Curve
- i.Object.GeometryCount
- import math
- from draftlibs import fcvec,fcgeo
- from FreeCAD import Vector,Base
- olEdges = []
- for s in Gui.Selection.getSelectionEx():
- i = 0
- if s.ObjectName == 'Sketch':
- for e in s.Object.Geometry:
- olEdges.append(s.Object.Shape.Edges[i])
- i = i+1
- sorted_edges = []
- sorted_edges = fcgeo.sortEdges(olEdges,olEdges[0].Vertexes[0])
- for s in sorted_edges:
- olEdges.append(s)
- if (isinstance(s.Curve,Part.Circle)):
- mp = fcgeo.findMidpoint(s)
- ce = s.Curve.Center
- tang1 = s.Curve.tangent(s.ParameterRange[0]) ; tang2 = s.Curve.tangent(s.ParameterRange[1])
- cross1 = Vector.cross(Base.Vector(tang1[0][0],tang1[0][1],tang1[0][2]),Base.Vector(tang2[0][0],tang2[0][1],tang2[0][2]))
- print "circle - start_pt: ",s.Vertexes[0].Point," center_pt:", s.Curve.Center , "mid_pt: ",mp, " end_pt: ",s.Vertexes[-1].Point
- print "tangent1: " , tang1, " tangent2: " , tang2, " cross product: ", cross1
- if cross1[2] > 0:
- print 'counter clockwise arc'
- else:
- print 'clockwise arc'
- elif (isinstance(s.Curve,Part.Line)):
- print "line - start_pt: ",s.Vertexes[0].Point, " end_pt: ",s.Vertexes[-1].Point
- else:
- print "unknown"
- #export curve elements to heekscnc
- import math
- from draftlibs import fcvec,fcgeo
- from FreeCAD import Vector,Base
- olEdges = []
- shape1 = Part.Shape
- for s in Gui.Selection.getSelectionEx():
- i = 0
- if s.ObjectName == 'Sketch':
- for e in s.Object.Geometry:
- olEdges.append(s.Object.Shape.Edges[i])
- i = i+1
- print "comment('Sketch from FreeCAD')"
- print "curve = area.Curve()"
- sorted_edges = []
- sorted_edges = fcgeo.sortEdges(olEdges,olEdges[0].Vertexes[0])
- print "curve.append(area.Point(" , olEdges[0].Vertexes[-1].X , "," , olEdges[0].Vertexes[-1].Y, "))"
- for s in sorted_edges:
- olEdges.append(s)
- if (isinstance(s.Curve,Part.Circle)):
- mp = fcgeo.findMidpoint(s)
- ce = s.Curve.Center
- tang1 = s.Curve.tangent(s.ParameterRange[0]) ; tang2 = s.Curve.tangent(s.ParameterRange[1])
- cross1 = Vector.cross(Base.Vector(tang1[0][0],tang1[0][1],tang1[0][2]),Base.Vector(tang2[0][0],tang2[0][1],tang2[0][2]))
- if cross1[2] > 0:
- direct = '1 ' #we seem to be working in a rh system in FreeCAD
- else:
- direct = '-1 '
- print "curve.append(area.Vertex(",direct, ", area.Point( ", s.Vertexes[-1].Point[0],", ",s.Vertexes[-1].Point[1], "), area.Point(", s.Curve.Center [0], ", " , s.Curve.Center[1], ")))"
- elif (isinstance(s.Curve,Part.Line)):
- print "curve.append(area.Point( ",s.Vertexes[-1].Point[0],", " ,s.Vertexes[-1].Point[1], "))"
- else:
- pass
- #export curve elements to heekscnc
- #to reverse the curve:
- print "curve.Reverse()"
- 24"
- #sketch stuff:
- o.Object.Label
- #gives the user assigned label of the sketch
- o.Object.Shape.Edges[0].Curve #gives geo info about element in sketch (ignores construction lines)
- #constraints stuff
- from Sketcher import *
- from Part import *
- from FreeCAD import *
- # set some constances for the constraints
- StartPoint = 1
- EndPoint = 2
- CenterPoint = 3
- # create a document and a Sketch object
- #if(App.activeDocument() == None):App.newDocument()
- f = App.activeDocument().addObject("Sketcher::SketchObject","newSketch")
- # add geometry to the sketch
- #f.Geometry = ()
- #f.Geometry = (Line(Vector(0,20,0),Vector(0,0,0)))
- f.addGeometry(Line(Vector(0,20,0),Vector(0,0,0)))
- f.addGeometry(Line(Vector(0,0,0),Vector(20,0,0)))
- #addGeometry(Part.ArcOfCircle(Part.Circle(App.Vector(2.738215,-33.047379,0),App.Vector(0,0,1),68.307899),0.674741,2.256331))
- #App.ActiveDocument.Sketch.addGeometry(Part.ArcOfCircle(Part.Circle(App.Vector(0.000000,-0.000000,0),App.Vector(0,0,1),20.000000),0.000000,3.141593))
- #f.Geometry = [Circle(Vector(2.738215,-33.047379,0),Vector(0,0,1),2.0)]
- #f.addGeometry(fillet(0,1,Vector(-0.000000,1.000000,0),Vector(1.000000,-0.000000,0),1.000000))
- #f.addGeometry(ArcOfCircle(Part.Circle(App.Vector(0.000000,-0.000000,0),App.Vector(0,0,1),20.000000),0.000000,1.5707963267948966))
- f.addGeometry(Part.ArcOfCircle(Part.Circle(App.Vector(0.000000,-0.000000,0),App.Vector(0,0,1),20.000000),0.000000,1.5707963267948966))
- f.Constraints = [Constraint('Vertical',0),Constraint('Horizontal',1)]
- l = f.Constraints
- #l.append(Constraint('DistanceX',0,0.0))
- l.append(Constraint('Coincident',0,EndPoint,1,StartPoint))
- l.append(Constraint('Coincident',0,StartPoint,2,EndPoint))
- l.append(Constraint('Coincident',1,EndPoint,2,StartPoint))
- l.append(Constraint('Coincident',2,CenterPoint,0,EndPoint))
- l.append(Constraint('Radius',2,3.333))
- l.append(Constraint('DistanceX',0,2,6.819825))
- l.append(Constraint('DistanceY',0,2,6.038286))
- f.Constraints = l
- p = App.activeDocument().addObject("PartDesign::Pad","Pad")
- p.Sketch =f
- p.Length=1.0
- p.Reversed = 0
- p.Midplane = 0
- p.Length2 = 100.00
- p.Type = 0
- p.UpToFace = None
- App.activeDocument().recompute()
- #import DXF to Sketcher
- import toSketch
- import FreeCAD
- dxf = "/home/danfalck/Documents/freecad/dxf_import/test_entities.dxf"
- doc = FreeCAD.ActiveDocument.Name
- reload(toSketch) #just for now
- toSketch.insert(dxf,doc)
- #lists
- olEdges = []
- i = 0
- for s in Gui.Selection.getSelectionEx():
- if s.Object.Type == 'Sketcher::SketchObject':
- for e in s.Object.Geometry:
- while i < 8:
- if not e.Construction:
- olEdges.append(s.Object.Shape.Edges[i])
- print 'non construction'
- print s.Object.Geometry[i]
- print i
- else:
- print 'construction'
- print s.Object.Geometry[i]
- print i
- i= i + 1
- olEdges = []
- for s in Gui.Selection.getSelectionEx():
- i = 0
- if s.Object.Type == 'Sketcher::SketchObject':
- for e in s.Object.Geometry:
- while i < len(s.Object.Geometry):
- if not s.Object.Geometry[i].Construction:
- olEdges.append(s.Object.Geometry[i])
- print s.Object.Geometry[i]
- print i
- i= i + 1
- <Line (-61.8648;2.25316,0) (-85.2121;7.39871,0) >
- 0
- <Line (-86.501;7.31343,0) (-100.627;2.1721,0) >
- 1
- <Line (-100.627;-2.17444,0) (-86.5026;-7.31894,0) >
- 2
- <Line (-85.2138;-7.40451,0) (-61.8653;-2.26422,0) >
- 3
- ArcOfCircle (Radius : 2.31284, Position : (-99.8356, -0.00125464, 0), Direction : (0, 0, 1), Parameter : (1.91986, 4.3631))
- 16
- ArcOfCircle (Radius : 2.31284, Position : (-62.3625, -0.00547331, 0), Direction : (0, 0, 1), Parameter : (4.92909, 7.63706))
- 17
- ArcOfCircle (Radius : 2.31284, Position : (-85.7099, 5.14007, 0), Direction : (0, 0, 1), Parameter : (1.35387, 1.91986))
- 18
- ArcOfCircle (Radius : 2.31284, Position : (-85.7111, -5.14576, 0), Direction : (0, 0, 1), Parameter : (4.3631, 4.92909))
- 19
- shape1 = Part.Shape
- for s in Gui.Selection.getSelectionEx():
- i = 0
- j = 0
- if s.Object.Type == 'Sketcher::SketchObject':
- for e in s.Object.Geometry:
- while i < (len(s.Object.Geometry)):
- if not s.Object.Geometry[i].Construction:
- olEdges.append(s.Object.Shape.Edges[j])
- j = j+1
- i = i+1
- elif s.Object.Type == 'Part::TopoShape'
- else:
- for e in s.Object.Shape.Edges:
- olEdges.append(s.Object.Shape.Edges[i])
- i = i+1
- for s in Gui.Selection.getSelectionEx():
- for e in s.Object.Shape.Edges:
- print e
- #get a point from the screen
- #Basically you need to do this:
- #- create a callback function, that will be called whenever a coin "event" occurs (a mouse button is pressed, a key is pressed, etc)
- #- register that function so coin knows it needs to execute it
- #- inside that function, check if the event is what you want (a left mouse click)
- #- if yes, check the position of the mouse, and take the corresponding 3D point
- #- unregister the callback function
- import FreeCAD
- import FreeCADGui, Part
- from pivy.coin import *
- class point:
- "this class will print out the coords of a point after the user clicked a point on the screen"
- def __init__(self):
- self.view = FreeCADGui.ActiveDocument.ActiveView
- self.stack = []
- self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)
- def getpoint(self,event_cb):
- event = event_cb.getEvent()
- if event.getState() == SoMouseButtonEvent.DOWN:
- pos = event.getPosition()
- point = self.view.getPoint(pos[0],pos[1])
- self.stack.append(point)
- if len(self.stack) == 2:
- FreeCAD.Console.PrintMessage("a point at" +str(self.stack[0])+","+str(self.stack[1])+ "\n")
- l = Part.Line(self.stack[0],self.stack[1])
- shape = l.toShape()
- Part.show(shape)
- self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
- point()
- from pivy import coin
- class PointTracker:
- def __init__(self,view):
- self.view=view
- self.__cb__ = self.view.addEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(),self.mouseButton)
- def mouseButton(self, event_cb):
- FreeCAD.Console.PrintMessage("Point clicked")
- self.result=event_cb.getEvent().getPosition()
- self.view.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(),self.__cb__)
- tracker=PointTracker(Gui.ActiveDocument.ActiveView)
- import Draft
- from FreeCAD import Vector
- #trying out Shape2DView
- for ob in Draft.getSelection():
- Draft.move(Draft.makeShape2DView(ob,Vector(0,0,1)),Vector(0,35,0))
- Draft.move(Draft.rotate(Draft.makeShape2DView(ob,Vector(0,-1,0)),-90.0,Vector(0,0,0),Vector(0,0,1),False),Vector(0,20,0))
- Draft.move(Draft.rotate(Draft.makeShape2DView(ob,Vector(1,0,0)),90.0,Vector(0,0,0),Vector(0,0,1),False),Vector(15,20,0))
- #working on exporting blocks
- for ob in Draft.getSelection():
- print ob
- isinstance (edge.Curve,Part.Circle)
- #clicking on points again
- from pivy import coin
- v=Gui.activeDocument().activeView()
- #This class logs any mouse button events. As the registered callback function fires twice for 'down' and
- #'up' events we need a boolean flag to handle this.
- class ViewObserver:
- def logPosition(self, info):
- down = (info["State"] == "DOWN")
- pos = info["Position"]
- if (down):
- FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[0])+")\n")
- o = ViewObserver()
- c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
- #kill the function with this:
- v.removeEventCallback("SoMouseButtonEvent",c)
- #coin stuff
- from pivy import coin
- sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
- co = coin.SoCoordinate3()
- pts = [[0,0,0],[10,0,0]]
- co.point.setValues(0,len(pts),pts)
- ma = coin.SoBaseColor()
- ma.rgb = (1,0,0)
- li = coin.SoLineSet()
- li.numVertices.setValue(2)
- no = coin.SoSeparator()
- no.addChild(co)
- no.addChild(ma)
- no.addChild(li)
- sg.addChild(no)
- #remove it:
- sg.removeChild(no)
- from pivy import coin
- sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
- color = coin.SoBaseColor()
- color.rgb = (0,0,1)
- marker = coin.SoMarkerSet() # this is the marker symbol
- marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_9_9
- coords = coin.SoCoordinate3() # this is the coordinate
- #coords.point.setValue((0,0,0)) just one point
- pts = [[0,0,0],[10,0,0]]#skip this for just one point
- coords.point.setValues(0,len(pts),pts)
- node = coin.SoAnnotation()
- node.addChild(coords)
- node.addChild(color)
- node.addChild(marker)
- sg.addChild(node)
- #remove them:
- sg.removeChild(node)
- from pivy import coin
- def makeDot(point,sg):
- color = coin.SoBaseColor()
- color.rgb = (0,0,1)
- marker = coin.SoMarkerSet() # this is the marker symbol
- marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_9_9
- coords = coin.SoCoordinate3() # this is the coordinate
- x,y,z = point
- coords.point.setValue(x,y,z)
- node = coin.SoAnnotation()
- node.addChild(coords)
- node.addChild(color)
- node.addChild(marker)
- sg.addChild(node)
- sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
- makeDot((0,0,0),sg)
- makeDot((10,0,0),sg)
- makeDot((10,10,0),sg)
- makeDot((0,10,0),sg)
- sg.removeAllChildren()
- #now let's try that with the mouse:
- from pivy import coin
- v=Gui.ActiveDocument.ActiveView
- #sg = v.getSceneGraph()
- #This class logs any mouse button events. As the registered callback function fires twice for 'down' and
- #'up' events we need a boolean flag to handle this.
- class ViewObserver:
- def logPosition(self, info):
- down = (info["State"] == "DOWN")
- pos = info["Position"]
- if (down):
- FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
- x,y = pos[0],pos[1]
- #print pos[0], pos[1]
- makeDot((x,y,0),Gui.ActiveDocument.ActiveView.getSceneGraph())
- def makeDot(point,sg):
- color = coin.SoBaseColor()
- color.rgb = (0,0,1)
- marker = coin.SoMarkerSet() # this is the marker symbol
- marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_9_9
- coords = coin.SoCoordinate3() # this is the coordinate
- x,y,z = point
- coords.point.setValue(x,y,z)
- node = coin.SoAnnotation()
- node.addChild(coords)
- node.addChild(color)
- node.addChild(marker)
- sg.addChild(node)
- o = ViewObserver()
- c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
- #kill the function with this:
- v.removeEventCallback("SoMouseButtonEvent",c)
- #kill the dots:
- Gui.ActiveDocument.ActiveView.getSceneGraph().removeAllChildren()
- #create dots on the screen with the mouse:
- import FreeCAD
- import FreeCADGui, Part
- from pivy.coin import *
- class point:
- "this class will print out the coords of a point after the user clicked a point on the screen"
- def __init__(self):
- self.color = coin.SoBaseColor()
- self.color.rgb = (0,0,1)
- self.marker = coin.SoMarkerSet()
- self.marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_9_9
- self.view = FreeCADGui.ActiveDocument.ActiveView
- self.sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
- self.node = coin.SoAnnotation()
- self.stack = []
- self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.getpoint)
- def getpoint(self,event_cb):
- event = event_cb.getEvent()
- if event.getState() == SoMouseButtonEvent.DOWN:
- pos = event.getPosition()
- point = self.view.getPoint(pos[0],pos[1])
- self.stack.append(point)
- if len(self.stack) == 1:
- FreeCAD.Console.PrintMessage("a point at" +str(self.stack[0])+ "\n")
- self.coords = coin.SoCoordinate3()
- #self.coords.point.setValue(0,0,0)
- self.coords.point.setValue(self.stack[0][0],self.stack[0][1],0)
- self.node.addChild(self.coords)
- self.node.addChild(self.color)
- self.node.addChild(self.marker)
- self.sg.addChild(self.node)#<<<
- self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
- point()
- #create dots on the screen with the mouse and remove them or restore them:
- import FreeCAD
- import FreeCADGui, Part
- from pivy.coin import *
- class point:
- "this class will print out the coords of a point after the user clicked a point on the screen and do some point manipulation"
- def __init__(self,path_pt):
- self.start_end = path_pt
- self.color = coin.SoBaseColor()
- if self.start_end =='start':
- self.color.rgb = (0,0,1)
- else:
- self.color.rgb = (0,1,0)
- self.marker = coin.SoMarkerSet()
- self.marker.markerIndex = coin.SoMarkerSet.CROSS_9_9
- self.view = FreeCADGui.ActiveDocument.ActiveView
- self.sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
- self.node = coin.SoAnnotation()
- self.stack = []
- self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.clickPoint)
- #FreeCAD.Console.PrintMessage("this is a "+ str(self.start_end)+ " point\n")
- def clickPoint(self,event_cb):
- "this is how the mouse event gets recorded"
- event = event_cb.getEvent()
- if event.getState() == SoMouseButtonEvent.DOWN:
- pos = event.getPosition()
- point = self.view.getPoint(pos[0],pos[1])
- self.stack.append(point)
- if len(self.stack) == 1:
- FreeCAD.Console.PrintMessage("a point at" +str(self.stack[0])+ "\n")
- self.coords = coin.SoCoordinate3()
- #self.coords.point.setValue(0,0,0)
- self.coords.point.setValue(self.stack[0][0],self.stack[0][1],0)
- self.node.addChild(self.coords)
- self.node.addChild(self.color)
- self.node.addChild(self.marker)
- self.sg.addChild(self.node)#<<<
- self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(),self.callback)
- FreeCAD.Console.PrintMessage("this is a "+ str(self.start_end)+ " point\n")
- def hidePoint(self):
- "hides the point on the screen"
- self.sg.removeChild(self.node)#clears node
- def showPoint(self):#show it again, after being erased
- "shows the point on the screen"
- self.coords.point.setValue(self.stack[0][0],self.stack[0][1],0)
- self.node.addChild(self.coords)
- self.node.addChild(self.color)
- self.node.addChild(self.marker)
- self.sg.addChild(self.node)#<<<
- def movePoint(self,newCoords):
- "moves the point to a new location - movePoint((new coordinate))"
- self.sg.removeChild(self.node)#clears node
- self.coords.point.setValue(newCoords[0],newCoords[1],0)
- self.node.addChild(self.coords)
- self.node.addChild(self.color)
- self.node.addChild(self.marker)
- self.sg.addChild(self.node)#<<<
- self.stack[0][0] = float(newCoords[0])
- self.stack[0][1] = float(newCoords[1])
- def coordLocation(self):
- "returns the coordinate location of the point"
- return self.stack[0][0],self.stack[0][1]
- p1 = point('start') #click on the screen
- p1.hidePoint() #erases the point you just created
- p1.showPoint() #shows the point again
- p1.movePoint((1,0,0))#move it somewhere else
- p1.Coords() #gives it's coordinates
- #compound objects
- import Part
- cmpnd=Part.Compound()
- selection = FreeCADGui.Selection.getSelection()
- for obj in selection:
- cmpnd.add(obj.Shape) # add all the shape data from the objects you need
- Part.show(cmpnd)
- #grouping again:
- #Adding and removing an object to a group
- doc=App.activeDocument()
- grp=doc.addObject("App::DocumentObjectGroup", "Group1")
- for o in Gui.Selection.getSelectionEx():
- for s in o.SubObjects:
- grp.addObject(s)
- grp.removeObject(f) # removes the circle object from the group grp
- import FreeCAD
- from FreeCAD import Part
- class Line:
- def __init__(self, obj):
- "App two point properties"
- obj.addProperty("App::PropertyVector","p1","Line","Start point")
- obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(1,0,0)
- obj.Proxy = self
- def execute(self, fp):
- "Print a short message when doing a recomputation, this method is mandatory"
- fp.Shape = Part.makeLine(fp.p1,fp.p2)
- a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
- Line(a)
- a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification)
- #find the area of a solid part:
- import Part
- s = Gui.Selection.getSelectionEx()
- p = s[0].Object.Shape
- p.Area
- #here's an even easier way that Yorik showed me:
- FreeCAD.ActiveDocument.ActiveObject.Shape.Area
- #animation example from werner:
- from PyQt4 import QtCore
- from FreeCAD import Base
- loop=QtCore.QEventLoop()
- timer=QtCore.QTimer()
- timer.setSingleShot(True)
- QtCore.QObject.connect(timer,QtCore.SIGNAL("timeout()"),loop,QtCore.SLOT("quit()"))
- duration = 3000 # in ms
- steps=300
- ms=duration/steps
- obj=App.ActiveDocument.ActiveObject
- start=obj.Placement.Base
- end=Base.Vector(12,23,34)
- for i in range(steps):
- s=float(i)/steps
- px=start.x * (1-s) + end.x * s
- py=start.y * (1-s) + end.y * s
- pz=start.z * (1-s) + end.z * s
- obj.Placement.Base=Base.Vector(px,py,pz)
- timer.start(ms)
- loop.exec_(QtCore.QEventLoop.ExcludeUserInputEvents)
- obj.Placement.Base=end
- # use freetype extension to make text string
- String = 'FreeCAD'
- FontPath = '/usr/share/fonts/truetype/freefont/'
- FontName = 'FreeMonoBoldOblique.ttf'
- Height = 2000
- Track = 0
- s = Part.makeWireString(String,FontPath,FontName,Height,Track)
- for char in s:
- for contour in char:
- Part.show(contour)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement