Python FreeCAD.Placement() Examples

The following are 30 code examples of FreeCAD.Placement(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module FreeCAD , or try the search function .
Example #1
Source File: utils.py    From FreeCAD_assembly3 with GNU General Public License v3.0 7 votes vote down vote up
def getElementPlacement(obj,mat=None):
    '''Get the placement of an element

       obj: either a document object or a tuple(obj,subname)
       mat: if not None, then this should be a matrix, and the returned
            placement will be relative to this transformation matrix.
    '''
    if not isElement(obj):
        if not isinstance(obj,(tuple,list)):
            pla = obj.Placement
        else:
            _,mat = obj[0].getSubObject(obj[1],1,FreeCAD.Matrix())
            pla = FreeCAD.Placement(mat)
    else:
        pla = FreeCAD.Placement(getElementPos(obj),getElementRotation(obj))
    if not mat:
        return pla
    return FreeCAD.Placement(mat.inverse()).multiply(pla) 
Example #2
Source File: HelicalSweepFP.py    From CurvesWB with GNU Lesser General Public License v2.1 7 votes vote down vote up
def make_profile_sketch(self):
        import Sketcher
        sk = FreeCAD.ActiveDocument.addObject('Sketcher::SketchObject','Profile')
        sk.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0),FreeCAD.Rotation(0,0,0,1))
        sk.MapMode = "Deactivated"
        sk.addGeometry(Part.LineSegment(FreeCAD.Vector(100.0,0.0,0),FreeCAD.Vector(127.0,12.0,0)),False)
        sk.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-1)) 
        sk.addGeometry(Part.ArcOfCircle(Part.Circle(FreeCAD.Vector(125.0,17.0,0),FreeCAD.Vector(0,0,1),5.8),-1.156090,1.050925),False)
        sk.addConstraint(Sketcher.Constraint('Tangent',0,2,1,1)) 
        sk.addGeometry(Part.LineSegment(FreeCAD.Vector(128.0,22.0,0),FreeCAD.Vector(100.0,37.0,0)),False)
        sk.addConstraint(Sketcher.Constraint('Tangent',1,2,2,1)) 
        sk.addConstraint(Sketcher.Constraint('Vertical',0,1,2,2)) 
        sk.addConstraint(Sketcher.Constraint('DistanceY',0,1,2,2,37.5)) 
        sk.setDatum(4,FreeCAD.Units.Quantity('35.000000 mm'))
        sk.renameConstraint(4, u'Lead')
        sk.setDriving(4,False)
        sk.addConstraint(Sketcher.Constraint('Equal',2,0)) 
        FreeCAD.ActiveDocument.recompute()
        return sk 
Example #3
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def shapeReferenceAxis(obj=None, axObj=None):
  # function to get the reference axis of the shape for rotateTheTubeAx()
  # used in rotateTheTubeEdge() and pipeForms.rotateForm().getAxis()
  '''
  shapeReferenceAxis(obj, axObj)
  Returns the direction of an axis axObj
  according the original Shape orientation of the object obj
  If arguments are None axObj is the normal to one circular edge selected
  and obj is the object selected.
  '''
  if obj==None and axObj==None:
    selex=FreeCADGui.Selection.getSelectionEx()
    if len(selex)==1 and len(selex[0].SubObjects)>0:
      sub=selex[0].SubObjects[0]
      if sub.ShapeType=='Edge' and sub.curvatureAt(0)>0:  
        axObj=sub.tangentAt(0).cross(sub.normalAt(0))
        obj=selex[0].Object
  X=obj.Placement.Rotation.multVec(FreeCAD.Vector(1,0,0)).dot(axObj)
  Y=obj.Placement.Rotation.multVec(FreeCAD.Vector(0,1,0)).dot(axObj)
  Z=obj.Placement.Rotation.multVec(FreeCAD.Vector(0,0,1)).dot(axObj)
  axShapeRef=FreeCAD.Vector(X,Y,Z)
  return axShapeRef 
Example #4
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def join(obj1,port1,obj2,port2):
  '''
  join(obj1,port1,obj2,port2)
  \t obj1, obj2 = two "Pype" parts
  \t port1, port2 = their respective ports to join
  '''  
  if hasattr(obj1,'PType') and hasattr(obj2,'PType'):
    if port1>len(obj1.Ports)-1 or port2>len(obj2.Ports)-1:
      FreeCAD.Console.PrintError('Wrong port(s) number\n')
    else:
      v1=portsDir(obj1)[port1]
      v2=portsDir(obj2)[port2]
      rot=FreeCAD.Rotation(v2,v1.negative())
      obj2.Placement.Rotation=rot.multiply(obj2.Placement.Rotation)
      p1=portsPos(obj1)[port1]
      p2=portsPos(obj2)[port2]
      obj2.Placement.move(p1-p2)
  else:
    FreeCAD.Console.PrintError('Object(s) are not pypes\n') 
Example #5
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def breakTheTubes(point,pipes=[],gap=0):
  '''
  breakTheTube(point,pipes=[],gap=0)
  Breaks the "pipes" at "point" leaving a "gap".
  '''
  pipes2nd=list()
  if not pipes:
    pipes=[p for p in frameCmd.beams() if isPipe(p)]
  if pipes:
    for pipe in pipes:
      if point<float(pipe.Height) and gap<(float(pipe.Height)-point):
        propList=[pipe.PSize,float(pipe.OD),float(pipe.thk),float(pipe.Height)-point-gap]
        pipe.Height=point
        Z=frameCmd.beamAx(pipe)
        pos=pipe.Placement.Base+Z*(float(pipe.Height)+gap)
        pipe2nd=makePipe(propList,pos,Z)
        pipes2nd.append(pipe2nd)
    #FreeCAD.activeDocument().recompute()
  return pipes2nd 
Example #6
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def laydownTheTube(pipe=None, refFace=None, support=None):
  '''
  laydownTheTube(pipe=None, refFace=None, support=None)
  Makes one pipe touch one face if the center-line is parallel to it.
  If support is not None, support is moved towards pipe.
  '''
  if not(pipe and refFace):  # without argument take from selection set
    refFace=[f for f in frameCmd.faces() if type(f.Surface)==Part.Plane][0]
    pipe=[p for p in frameCmd.beams() if hasattr(p,'OD')] [0]
  try:
    if type(refFace.Surface)==Part.Plane and frameCmd.isOrtho(refFace,frameCmd.beamAx(pipe)) and hasattr(pipe,'OD'):
      dist=rounded(refFace.normalAt(0,0).multiply(refFace.normalAt(0,0).dot(pipe.Placement.Base-refFace.CenterOfMass)-float(pipe.OD)/2))
      if support:
        support.Placement.move(dist)
      else:
        pipe.Placement.move(dist.multiply(-1))
    else:
      FreeCAD.Console.PrintError('Face is not flat or not parallel to axis of pipe\n')
  except:
    FreeCAD.Console.PrintError('Wrong selection\n') 
Example #7
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def placeoTherElbow(c,v1=None,v2=None,P=None):
  '''
  Like placeTheElbow() but with more math.
  '''
  if not (v1 and v2):
    v1,v2=[e.tangentAt(0) for e in frameCmd.edges()]
    try:
      P=frameCmd.intersectionCLines(*frameCmd.edges())
    except: pass
  if hasattr(c,'PType') and hasattr(c,'BendAngle') and v1 and v2:
    v1.normalize()
    v2.normalize()
    ortho=rounded(frameCmd.ortho(v1,v2))
    bisect=rounded(v2-v1)
    cBisect=rounded(c.Ports[1].normalize()+c.Ports[0].normalize()) # math
    cZ=c.Ports[0].cross(c.Ports[1]) # more math
    ang=degrees(v1.getAngle(v2))
    c.BendAngle=ang
    rot1=FreeCAD.Rotation(rounded(frameCmd.beamAx(c,cZ)),ortho)
    c.Placement.Rotation=rot1.multiply(c.Placement.Rotation)
    rot2=FreeCAD.Rotation(rounded(frameCmd.beamAx(c,cBisect)),bisect)
    c.Placement.Rotation=rot2.multiply(c.Placement.Rotation)
    if not P:
      P=c.Placement.Base
    c.Placement.Base=P 
Example #8
Source File: frameFeatures.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def makeSingle(self):
    FreeCAD.activeDocument().openTransaction('Insert Single Struct')
    if self.SType=='<by sketch>':
      profile=FreeCAD.ActiveDocument.getObjectsByLabel(self.form.listSizes.currentItem().text())[0]
    else:
      prop=self.sectDictList[self.form.listSizes.currentRow()]
      profile=newProfile(prop)
    if frameCmd.faces():
      Z=FreeCAD.Vector(0,0,1)
      for f in frameCmd.faces():
        beam=makeStructure(profile)
        beam.Placement=FreeCAD.Placement(f.CenterOfMass,FreeCAD.Rotation(Z,f.normalAt(0,0)))
        if self.form.editLength.text(): beam.Height=float(self.form.editLength.text())
    else:
      for e in frameCmd.edges():
        beam=makeStructure(profile)
        frameCmd.placeTheBeam(beam,e)
        if self.form.editLength.text(): beam.Height=float(self.form.editLength.text())
    FreeCAD.ActiveDocument.recompute() 
Example #9
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def reverseTheTube(objEx):
  '''
  reverseTheTube(objEx)
  Reverse the orientation of objEx spinning it 180 degrees around the x-axis
  of its shape.
  If an edge is selected, it's used as pivot.
  '''
  disp=None
  selectedEdges=[e for e in objEx.SubObjects if e.ShapeType=='Edge']
  if selectedEdges:
    for edge in frameCmd.edges([objEx]):
      if edge.curvatureAt(0):
        disp=edge.centerOfCurvatureAt(0)-objEx.Object.Placement.Base
        break
      elif frameCmd.beams([objEx.Object]):
        ax=frameCmd.beamAx(objEx.Object)
        disp=ax*((edge.CenterOfMass-objEx.Object.Placement.Base).dot(ax))
  rotateTheTubeAx(objEx.Object,FreeCAD.Vector(1,0,0),180)
  if disp:
    objEx.Object.Placement.move(disp*2) 
Example #10
Source File: Numpy.py    From NodeEditor with MIT License 6 votes vote down vote up
def zipRotation(
				x=('FloatPin', [0],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported}),
				y=('FloatPin', [1],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported}),
				z=('FloatPin', [2],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported}),
				angle=('FloatPin', [2],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported})
			) :
        """combine axis(x,y,z) and angle lists to a list of rotations"""
        
        res=np.array([x,y,z]).swapaxes(0,1)
        rots=[FreeCAD.Rotation(FreeCAD.Vector(list(a)),b) for a,b in zip(res,angle)]    
        return rots

#    @staticmethod
#    @IMPLEMENT_NODE(returns=('RotationPin', [],{'constraint': '1', "enabledOptions": PinOptions.ArraySupported | PinOptions.AllowAny}), meta={'Category': 'numpy|array', 'Keywords': ['list','random']})
#    def zipPlacement(
#			Base=('FloatPin', []),Rotation=('FloatPin', [])) :
#        """combine """
#        
#        pms=[FreeCAD.Placement(base,rot) for base,rot in zip(Base,Rotation)]    
#        return pms 
Example #11
Source File: assembly.py    From FreeCAD_assembly3 with GNU General Public License v3.0 6 votes vote down vote up
def linkSetup(self,obj):
        super(AsmElement,self).linkSetup(obj)
        if not hasProperty(obj,'Offset'):
            obj.addProperty("App::PropertyPlacement","Offset"," Link",'')
        if not hasProperty(obj,'Placement'):
            obj.addProperty("App::PropertyPlacement","Placement"," Link",'')
        obj.setPropertyStatus('Placement','Hidden')
        if not hasProperty(obj,'LinkTransform'):
            obj.addProperty("App::PropertyBool","LinkTransform"," Link",'')
            obj.LinkTransform = True
        if not hasProperty(obj,'Detach'):
            obj.addProperty('App::PropertyBool','Detach', ' Link','')
        obj.setPropertyStatus('LinkTransform',['Immutable','Hidden'])
        obj.setPropertyStatus('LinkedObject','ReadOnly')
        obj.configLinkProperty('LinkedObject','Placement','LinkTransform')

        parent = getattr(obj,'_Parent',None)
        if parent:
            self.parent = parent.Proxy

        AsmElement.migrate(obj)

        self.version = AsmVersion() 
Example #12
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def makeShell(L=1000,W=1500,H=1500,thk1=6,thk2=8):
  '''
  makeShell(L,W,H,thk1,thk2)
  Adds the shell of a tank, given
    L(ength):        default=800
    W(idth):         default=400
    H(eight):        default=500
    thk (thickness): default=6
  '''
  a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Serbatoio")
  pipeFeatures.Shell(a,L,W,H,thk1,thk2)
  a.ViewObject.Proxy=0
  a.Placement.Base=FreeCAD.Vector(0,0,0)
  a.ViewObject.ShapeColor=0.0,0.0,1.0
  a.ViewObject.Transparency=85
  FreeCAD.ActiveDocument.recompute()
  return a 
Example #13
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeReduct(propList=[], pos=None, Z=None, conc=True):
  '''Adds a Reduct object
  makeReduct(propList=[], pos=None, Z=None, conc=True)
    propList is one optional list with 6 elements:
      PSize (string): nominal diameter
      OD (float): major diameter
      OD2 (float): minor diameter
      thk (float): major thickness
      thk2 (float): minor thickness
      H (float): length of reduction      
    pos (vector): position of insertion; default = 0,0,0
    Z (vector): orientation: default = 0,0,1
    conc (bool): True for concentric or Flase for eccentric reduction
  Remember: property PRating must be defined afterwards
  '''
  if pos==None:
    pos=FreeCAD.Vector(0,0,0)
  if Z==None:
    Z=FreeCAD.Vector(0,0,1)
  a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Riduz")
  propList.append(conc)
  pipeFeatures.Reduct(a,*propList)
  a.ViewObject.Proxy=0
  a.Placement.Base=pos
  rot=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),Z)
  a.Placement.Rotation=rot.multiply(a.Placement.Rotation)
  return a 
Example #14
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def spinTheBeam(beam, angle):  # OBSOLETE: replaced by rotateTheTubeAx
  '''arg1=beam, arg2=angle: rotate the section of the beam
  OBSOLETE: replaced by rotateTheTubeAx'''
  if beam.TypeId=="Part::FeaturePython" and "Base" in beam.PropertiesList:
    beam.Base.Placement=FreeCAD.Placement(FreeCAD.Vector(0.0,0.0,0.0),FreeCAD.Rotation(FreeCAD.Vector(0.0,0.0,1.0),angle)) 
Example #15
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def placeTheBeam(beam, edge):
  '''arg1= beam, arg2= edge: lay down the selected beam on the selected edge'''
  vect=edge.tangentAt(0)
  beam.Placement.Rotation=FreeCAD.Rotation(0,0,0,1)
  rot=FreeCAD.Rotation(beam.Placement.Rotation.Axis,vect)
  beam.Placement.Rotation=rot.multiply(beam.Placement.Rotation)
  beam.Placement.Base=edge.valueAt(0)
  beam.Height=edge.Length 
Example #16
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def rotTheBeam(beam,faceBase,faceAlign):
  '''arg1=beam, arg2=faceBase, arg3=faceToMakeParallel: rotate the beams to make the flanges parallel to that of first selection.'''
  from Part import Face
  if type(faceBase)==Face:
    n1=faceBase.normalAt(0,0)
  elif type(faceBase)==FreeCAD.Base.Vector:
    n1=faceBase
  n2=faceAlign.normalAt(0,0)
  rot=FreeCAD.Rotation(n2,n1)
  beam.Placement.Rotation=rot.multiply(beam.Placement.Rotation) 
Example #17
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def placeTheElbow(c,v1=None,v2=None,P=None):
  '''
  placeTheElbow(c,v1,v2,P=None)
  Puts the curve C between vectors v1 and v2.
  If point P is given, translates it in there.
  NOTE: v1 and v2 oriented in the same direction along the path!
  '''
  if not (v1 and v2):
    v1,v2=[e.tangentAt(0) for e in frameCmd.edges()]
    try:
      P=frameCmd.intersectionCLines(*frameCmd.edges())
    except: pass
  if hasattr(c,'PType') and hasattr(c,'BendAngle') and v1 and v2:
    v1.normalize()
    v2.normalize()
    ortho=rounded(frameCmd.ortho(v1,v2))
    bisect=rounded(v2-v1)
    ang=degrees(v1.getAngle(v2))
    c.BendAngle=ang
    rot1=FreeCAD.Rotation(rounded(frameCmd.beamAx(c,FreeCAD.Vector(0,0,1))),ortho)
    c.Placement.Rotation=rot1.multiply(c.Placement.Rotation)
    rot2=FreeCAD.Rotation(rounded(frameCmd.beamAx(c,FreeCAD.Vector(1,1,0))),bisect)
    c.Placement.Rotation=rot2.multiply(c.Placement.Rotation)
    if not P:
      P=c.Placement.Base
    c.Placement.Base=P 
Example #18
Source File: frameFeatures.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def trim(self):
    FreeCAD.ActiveDocument.openTransaction('Trim FB')
    for target in self.targets:
      for b in frameCmd.beams():
        if hasattr(b,'tailOffset') and hasattr(b,'headOffset'):
          edge=b.Support[0][0].Shape.getElement(b.Support[0][1][0])
          ax=edge.tangentAt(0).normalize() #frameCmd.beamAx(b).normalize()
          tail=edge.valueAt(0) #b.Placement.Base
          head=edge.valueAt(edge.LastParameter) #tail+ax*float(b.Height)
          if target.ShapeType=="Vertex":
            P=target.Point
          elif target.ShapeType=="Face" and not frameCmd.isOrtho(target,ax):
            P=frameCmd.intersectionPlane(tail,ax,target)
          elif hasattr(target,"CenterOfMass"):
            P=target.CenterOfMass
          else: 
            P=None
          if P:
            #print P
            #print ax.Length
            deltaTail=(P-tail).dot(ax)
            deltaHead=(P-head).dot(ax)
            #print "D-tail = %.1f; D-head = %.1f" %(deltaTail,deltaHead)
            if abs(deltaTail)<abs(deltaHead):
              b.tailOffset=-deltaTail
            else:
              b.headOffset=deltaHead
    refresh()
    FreeCAD.ActiveDocument.commitTransaction() 
Example #19
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeCap(propList=[], pos=None, Z=None):
  '''add a Cap object
  makeCap(propList,pos,Z);
  propList is one optional list with 4 elements:
    DN (string): nominal diameter
    OD (float): outside diameter
    thk (float): shell thickness
  Default is "DN50 (SCH-STD)"
  pos (vector): position of insertion; default = 0,0,0
  Z (vector): orientation: default = 0,0,1
  Remember: property PRating must be defined afterwards
  '''
  if pos==None:
    pos=FreeCAD.Vector(0,0,0)
  if Z==None:
    Z=FreeCAD.Vector(0,0,1)
  a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Fondo")
  if len(propList)==3:
    pipeFeatures.Cap(a,*propList)
  else:
    pipeFeatures.Cap(a)
  a.ViewObject.Proxy=0
  a.Placement.Base=pos
  rot=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),Z)
  a.Placement.Rotation=rot.multiply(a.Placement.Rotation)
  return a 
Example #20
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def rotateTheTubeAx(obj=None,vShapeRef=None, angle=45):
  '''
  rotateTheTubeAx(obj=None,vShapeRef=None,angle=45)
  Rotates obj around the vShapeRef axis of its Shape by an angle.
    obj: if not defined, the first in the selection set
    vShapeRef: if not defined, the Z axis of the Shape
    angle: default=45 deg
  '''
  if obj==None:
    obj=FreeCADGui.Selection.getSelection()[0]
  if vShapeRef==None:
    vShapeRef=FreeCAD.Vector(0,0,1)
  rot=FreeCAD.Rotation(frameCmd.beamAx(obj,vShapeRef),angle)
  obj.Placement.Rotation=rot.multiply(obj.Placement.Rotation) 
Example #21
Source File: pipeCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeValve(propList=[], pos=None, Z=None):
  '''add a Valve object
  makeValve(propList,pos,Z);
  propList is one optional list with at least 4 elements:
    DN (string): nominal diameter
    VType (string): type of valve
    OD (float): outside diameter
    ID (float): inside diameter
    H (float): length of pipe
    Kv (float): valve's flow factor (optional)
  Default is "DN50 ball valve ('ball')"
  pos (vector): position of insertion; default = 0,0,0
  Z (vector): orientation: default = 0,0,1
  '''
  if pos==None:
    pos=FreeCAD.Vector(0,0,0)
  if Z==None:
    Z=FreeCAD.Vector(0,0,1)
  a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Valvola")
  if len(propList):
    pipeFeatures.Valve(a,*propList)
  else:
    pipeFeatures.Valve(a)
  a.ViewObject.Proxy=0
  a.Placement.Base=pos
  rot=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),Z)
  a.Placement.Rotation=rot.multiply(a.Placement.Rotation)
  return a 
Example #22
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def intersectionPlane(base=None,v=None,face=None):
  '''
  intersectionPlane(base,v,face)
  Returns the point (vector) at the intersection of a line and a plane.
    base (vector): the base point to be projected
    v (vector): the direction of the line that intersect the plane
    face (Face): the face that defines the plane to be intersect
  '''   
  # only for quick testing:
  if base==v==face==None:
    face = faces()[0]
    beam=beams()[0]
    base=beam.Placement.Base
    v=beamAx(beam)
  if isOrtho(v,face):
    FreeCAD.Console.PrintError('Direction of projection and Face are parallel.\n')
    return None
  else:
    # equation of plane: ax+by+cz+d=0
    a,b,c=list(face.normalAt(0,0))
    d=-face.CenterOfMass.dot(face.normalAt(0,0))
    #FreeCAD.Console.PrintMessage('a=%.2f b=%.2f c=%.2f d=%.2f\n' %(a,b,c,d))
    ## definition of line
    #FreeCAD.Console.PrintMessage('base=(%.2f,%.2f,%.2f)\n' %(base.x,base.y,base.z))
    #FreeCAD.Console.PrintMessage('v=(%.2f,%.2f,%.2f)\n' %(v.x,v.y,v.z))
    ##intersection
    k=-1*(a*base.x+b*base.y+c*base.z+d)/(a*v.x+b*v.y+c*v.z)
    #FreeCAD.Console.PrintMessage('k=%f\n' %float(k))
    P=base+v*k
    return rounded(P) 
Example #23
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def intersectionCLines(thing1=None, thing2=None):
  '''
  intersectionCLines(thing1=None, thing2=None)
  Returns the intersection (vector) of the center lines of thing1 and thing2.
  Things can be any combination of intersecting beams, pipes or edges.
  If less than 2 arguments are given, thing1 and thing2 are the first 2 beams
  or pipes found in the selection set.
  '''
  if not (thing1 and thing2):
    try:
      thing1,thing2=beams()[:2]
    except:
      FreeCAD.Console.PrintError('Insufficient arguments for intersectionCLines\n')
      return None
  edges=[]
  for thing in [thing1,thing2]:
    if beams([thing]):
      edges.append(vec2edge(thing.Placement.Base,beamAx(thing)))
    elif hasattr(thing,'ShapeType') and thing.ShapeType=='Edge':
      edges.append(thing)
  intersections=dgu.findIntersection(*edges, infinite1=True, infinite2=True)
  if len(intersections):
    return rounded(intersections[0])
  else:
    FreeCAD.Console.PrintError('No intersection found\n')
    return None 
Example #24
Source File: pipeFeatures.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def update(self,fp,edges=None):
    import pipeCmd, frameCmd
    from DraftVecUtils import rounded
    from math import degrees
    if not edges and hasattr(fp.Base,'Shape'):
      edges=fp.Base.Shape.Edges
      if not edges:
        FreeCAD.Console.PrintError('Base has not valid edges\n')
        return
    pipes=list()
    for e in edges:
      #---Create the tube---
      p=pipeCmd.makePipe([fp.PSize,fp.OD,fp.thk,e.Length],pos=e.valueAt(0),Z=e.tangentAt(0))
      p.PRating=fp.PRating
      p.PSize=fp.PSize
      pipeCmd.moveToPyLi(p,fp.Label)
      pipes.append(p)
      n=len(pipes)-1
      if n and not frameCmd.isParallel(frameCmd.beamAx(pipes[n]),frameCmd.beamAx(pipes[n-1])):
        #---Create the curve---
        propList=[fp.PSize,fp.OD,fp.thk,90,fp.BendRadius]
        c=pipeCmd.makeElbowBetweenThings(edges[n],edges[n-1],propList)
        if c:
          portA,portB=[c.Placement.multVec(port) for port in c.Ports]
          #---Trim the tube---
          p1,p2=pipes[-2:]
          frameCmd.extendTheBeam(p1,portA)
          frameCmd.extendTheBeam(p2,portB)
          pipeCmd.moveToPyLi(c,fp.Label) 
Example #25
Source File: pipeFeatures.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def execute(self, fp):
    if fp.BendAngle<180:
      if fp.thk>fp.OD/2:
        fp.thk=fp.OD/2
      fp.ID=fp.OD-2*fp.thk
      fp.Profile=str(fp.OD)+"x"+str(fp.thk)
      CenterOfBend=FreeCAD.Vector(fp.BendRadius,fp.BendRadius,0)
      ## make center-line ##
      R=Part.makeCircle(fp.BendRadius,CenterOfBend,FreeCAD.Vector(0,0,1),225-float(fp.BendAngle)/2,225+float(fp.BendAngle)/2)
      ## move the cl so that Placement.Base is the center of elbow ##
      from math import pi, cos, sqrt
      d=(fp.BendRadius*sqrt(2)-fp.BendRadius/cos(fp.BendAngle/180*pi/2))
      P=FreeCAD.Vector(-d*cos(pi/4),-d*cos(pi/4),0)
      R.translate(P)
      ## calculate Ports position ##
      fp.Ports=[R.valueAt(R.FirstParameter),R.valueAt(R.LastParameter)]
      ## make the shape of the elbow ##
      c=Part.makeCircle(fp.OD/2,fp.Ports[0],R.tangentAt(R.FirstParameter)*-1)
      b=Part.makeSweepSurface(R,c)
      p1=Part.Face(Part.Wire(c))
      p2=Part.Face(Part.Wire(Part.makeCircle(fp.OD/2,fp.Ports[1],R.tangentAt(R.LastParameter))))
      sol=Part.Solid(Part.Shell([b,p1,p2]))
      planeFaces=[f for f in sol.Faces if type(f.Surface)==Part.Plane]
      #elbow=sol.makeThickness(planeFaces,-fp.thk,1.e-3)
      #fp.Shape = elbow
      if fp.thk<fp.OD/2:
        fp.Shape=sol.makeThickness(planeFaces,-fp.thk,1.e-3)
      else:
        fp.Shape=sol
      super(Elbow,self).execute(fp) # perform common operations 
Example #26
Source File: frameCmd.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def rotjoinTheBeam(beam=None,e1=None,e2=None):
  if not (beam and e1 and e2):
    beam=beams()[1]
    e1,e2=edges()
  rot=FreeCAD.Rotation(e2.tangentAt(0),e1.tangentAt(0))
  dist=dgu.findDistance(beam.Placement.Base,e1)
  delta=beam.Placement.Base-e2.CenterOfMass
  beam.Placement.Rotation=rot.multiply(beam.Placement.Rotation)
  beam.Placement.move(rounded(dist+rot.multVec(delta))) 
Example #27
Source File: frameFeatures.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def mouseActionB1(self, CtrlAltShift):
    v = FreeCADGui.ActiveDocument.ActiveView
    i = v.getObjectInfo(v.getCursorPos())
    if i: 
      labText=i['Object']
      obj=FreeCAD.ActiveDocument.getObject(i['Object'])
      if hasattr(obj,'tailOffset') and hasattr(obj,'headOffset') and hasattr(obj,'spin'):
        self.form.editTail.setText(str(obj.tailOffset))
        self.form.editHead.setText(str(obj.headOffset))
        self.form.editAngle.setText(str(obj.spin))
        #self.form.sliTail.setValue(int(obj.tailOffset/float(obj.Height)*100))
        #self.form.sliHead.setValue(int(obj.headOffset/float(obj.Height)*100))
        #self.form.dialAngle.setValue(int(obj.spin))
        fb=findFB(i['Object'])
        if fb: 
          labText+=': part of '+fb.Label
        if self.labTail:
          self.labTail.removeLabel()
        self.labTail=label3D(pl=obj.Placement, text='____TAIL')
      else:
        if self.labTail:
          self.labTail.removeLabel()
        self.form.editTail.clear()
        self.form.editHead.clear()
        self.form.editAngle.clear()
        self.form.sliHead.setValue(0)
        self.form.sliTail.setValue(0)
        self.form.dialAngle.setValue(0)
      self.form.lab1.setText(labText)
    else:
      if self.labTail:
        self.labTail.removeLabel()
      self.form.sliHead.setValue(0)
      self.form.sliTail.setValue(0)
      self.form.dialAngle.setValue(0)
      self.form.lab1.setText('<no item selected>') 
Example #28
Source File: frameFeatures.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getProfile(self):
    if self.current:
      if frameCmd.beams():
        self.current.Profile=frameCmd.beams()[0].Base
      elif self.sectList.selectedItems():
        prof= FreeCAD.ActiveDocument.getObjectsByLabel(self.sectList.selectedItems()[0].text())[0]
        if prof.Shape.ShapeType=='Wire' and self.cb2.isChecked():
          prof.Placement.move(FreeCAD.Vector(0,0,0)-prof.Shape.CenterOfMass)
        prof.Placement.Rotation=FreeCAD.Base.Rotation()
        self.current.Profile=prof 
Example #29
Source File: pipeObservers.py    From flamingo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, name, pype, portNr, scale=100):
    self.stop=False
    self.pype=pype
    self.portDir=pipeCmd.portsDir(pype)[portNr]
    self.portPos=pipeCmd.portsPos(pype)[portNr]
    rot=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),self.portDir.negative())
    placement=FreeCAD.Placement(self.portPos,rot)
    super(arrow_insert,self).__init__(pl=placement, scale=[-scale,scale,scale/5], offset=-scale, name=name) 
Example #30
Source File: dev.py    From NodeEditor with MIT License 5 votes vote down vote up
def run_FreeCAD_Toy(self):
    self.setNodename("HU"+str(time.time()))
    self.setImage("freecad_cone")

    pml=[1,2,3,4,5,6,7,8,10,11,12,12,14,15,16,]
    tt=FreeCAD.Placement(FreeCAD.Matrix(*pml))
    pm2=self.getPinPlacement("PlacementPin_in")
    say("got",pm2)

    self.setPinPlacement("PlacementPin_out",tt.multiply(pm2))