Exemplo n.º 1
0
def makePypeLine2(DN="DN50",PRating="SCH-STD",OD=60.3,thk=3,BR=None, lab="Tubatura", pl=None, color=(0.8,0.8,0.8)):
  '''
  makePypeLine2(DN="DN50",PRating="SCH-STD",OD=60.3,thk=3,BR=None, lab="Tubatura",pl=None, color=(0.8,0.8,0.8))
  Adds a PypeLine2 object creating pipes over the selected edges.
  Default tube is "DN50", "SCH-STD"
  Bending Radius is set to 0.75*OD.
  '''
  if not BR:
    BR=0.75*OD
  # create the pypeLine group
  if not pl:
    a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython",lab)
    pFeatures.PypeLine2(a,DN,PRating,OD,thk,BR, lab)
    pFeatures.ViewProviderPypeLine(a.ViewObject) # a.ViewObject.Proxy=0
    a.ViewObject.ShapeColor=color
    if len(FreeCADGui.Selection.getSelection())==1:
      obj=FreeCADGui.Selection.getSelection()[0]
      isWire=hasattr(obj,'Shape') and obj.Shape.Edges #type(obj.Shape)==Part.Wire
      isSketch=hasattr(obj,'TypeId') and obj.TypeId=='Sketcher::SketchObject'
      if isWire or isSketch:
        a.Base=obj
        a.Proxy.update(a)
      if isWire:
        drawAsCenterLine(obj)
    elif fCmd.edges():
      path=makeW()
      a.Base=path
      a.Proxy.update(a)
  else:
    a=FreeCAD.ActiveDocument.getObjectsByLabel(pl)[0]
    group=FreeCAD.ActiveDocument.getObjectsByLabel(a.Group)[0]
    a.Proxy.update(a,fCmd.edges())
    FreeCAD.Console.PrintWarning("Objects added to pypeline's group "+a.Group+"\n")
  return a
Exemplo n.º 2
0
 def selectAction(self):
   self.objs=FreeCADGui.Selection.getSelection()
   L=direct=None
   pl=FreeCAD.Placement()
   # define general size of arrow
   if self.arrow: self.arrow.closeArrow()
   M=100.0
   moveSet=[o for o in FreeCADGui.Selection.getSelection() if hasattr(o,'Shape')]
   if moveSet:
     bb=moveSet[0].Shape.BoundBox
     for o in moveSet: bb=bb.united(o.Shape.BoundBox)
     edgesLens=[e.Length for o in moveSet for e in o.Shape.Edges]
     M=(bb.XLength+bb.YLength+bb.ZLength)/6.0
     # define placement of arrow
     orig=bb.Center
     orig[2]=bb.ZMax+bb.ZLength*0.1
     pl.move(orig)
   # define direction and displacement
   if fCmd.faces():
     direct=fCmd.faces()[0].normalAt(0,0)
   elif fCmd.edges():
     direct=fCmd.edges()[0].tangentAt(0)
   # create the arrow_move object
   if direct: 
     pl.Rotation=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),direct).multiply(pl.Rotation)
     self.arrow=arrow_move(self.form.edit1,self.form.edit2,pl=pl,direct=direct,M=M,objs=self.objs)
Exemplo n.º 3
0
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 fCmd.edges()]
    try:
      P=fCmd.intersectionCLines(*fCmd.edges())
    except: pass
  if hasattr(c,'PType') and hasattr(c,'BendAngle') and v1 and v2:
    v1.normalize()
    v2.normalize()
    ortho=rounded(fCmd.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(fCmd.beamAx(c,cZ)),ortho)
    c.Placement.Rotation=rot1.multiply(c.Placement.Rotation)
    rot2=FreeCAD.Rotation(rounded(fCmd.beamAx(c,cBisect)),bisect)
    c.Placement.Rotation=rot2.multiply(c.Placement.Rotation)
    if not P:
      P=c.Placement.Base
    c.Placement.Base=P
Exemplo n.º 4
0
def rotateTheTubeEdge(ang=45):
  if len(fCmd.edges())>0 and fCmd.edges()[0].curvatureAt(0)!=0:
    originalPos=fCmd.edges()[0].centerOfCurvatureAt(0)
    obj=FreeCADGui.Selection.getSelection()[0]
    rotateTheTubeAx(vShapeRef=shapeReferenceAxis(),angle=ang)
    newPos=fCmd.edges()[0].centerOfCurvatureAt(0)
    obj.Placement.move(originalPos-newPos)
Exemplo n.º 5
0
def doCaps(propList=['DN50',60.3,3], pypeline=None):
  '''
    propList = [
      DN (string): nominal diameter
      OD (float): outside diameter
      thk (float): shell thickness ]
    pypeline = string
  '''
  clist=[]
  FreeCAD.activeDocument().openTransaction('Insert cap')
  if len(fCmd.edges())==0:
    vs=[v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]
    if len(vs)==0:   # nothing is selected
      clist.append(makeCap(propList))
    else:
      for v in vs:   # vertexes are selected
        clist.append(makeCap(propList,v.Point))
  else:
    for edge in fCmd.edges():
      if edge.curvatureAt(0)!=0:   # curved edges are selected...
        objs=[o for o in FreeCADGui.Selection.getSelection() if hasattr(o,'PSize') and hasattr(o,'OD') and hasattr(o,'thk')]
        Z=None
        if len(objs)>0:  # ...pype objects are selected
          Z=edge.centerOfCurvatureAt(0)-objs[0].Shape.Solids[0].CenterOfMass
        else:            # ...no pype objects are selected
          Z=edge.tangentAt(0).cross(edge.normalAt(0))
        clist.append(makeCap(propList,edge.centerOfCurvatureAt(0),Z))
  if pypeline:
    for c in clist:
      moveToPyLi(c,pypeline)
  FreeCAD.activeDocument().commitTransaction()
  FreeCAD.activeDocument().recompute()
Exemplo n.º 6
0
def placeThePype(pypeObject, port=0, target=None, targetPort=0):
  '''
  placeThePype(pypeObject, port=None, target=None, targetPort=0)
    pypeObject: a FeaturePython with PType property
    port: an optional port of pypeObject
  Aligns pypeObject's Placement to the Port of another pype which is selected in the viewport.
  The pype shall be selected to the circular edge nearest to the port concerned.
  '''
  pos=Z=FreeCAD.Vector()
  if target and hasattr(target,'PType') and hasattr(target,'Ports'): # target is given
    pos=portsPos(target)[targetPort]
    Z=portsDir(target)[targetPort]
  else: # find target
    try:
      selex=FreeCADGui.Selection.getSelectionEx()
      target=selex[0].Object
      so=selex[0].SubObjects[0]
    except:
      FreeCAD.Console.PrintError('No geometry selected\n')
      return
    if type(so)==Part.Vertex: pick=so.Point
    else: pick=so.CenterOfMass
    if hasattr(target,'PType') and hasattr(target,'Ports'): # ...selection is another pype-object
      pos, Z = nearestPort(target, pick)[1:]
    elif fCmd.edges([selex[0]]): # one or more edges selected...
      edge=fCmd.edges([selex[0]])[0]
      if edge.curvatureAt(0)!=0: # ...and the first is curve
        pos=edge.centerOfCurvatureAt(0)
        Z=edge.tangentAt(0).cross(edge.normalAt(0))
  # now place pypeObject on target
  pOport=pypeObject.Ports[port]
  if pOport==FreeCAD.Vector():
    pOport=pypeObject.Ports[port]
    if pOport==FreeCAD.Vector(): pOport=FreeCAD.Vector(0,0,-1)
  pypeObject.Placement=FreeCAD.Placement(pos+Z*pOport.Length,FreeCAD.Rotation(pOport*-1,Z))
Exemplo n.º 7
0
 def selectAction(self):
     edged = [
         objex for objex in FreeCADGui.Selection.getSelectionEx()
         if fCmd.edges([objex])
     ]
     if edged:
         self.Axis = fCmd.edges([edged[0]])[0]
         self.deleteArrow()
         from uCmd import arrow
         where = FreeCAD.Placement()
         where.Base = self.Axis.valueAt(self.Axis.LastParameter)
         where.Rotation = FreeCAD.Rotation(
             FreeCAD.Vector(0, 0, 1),
             self.Axis.tangentAt(self.Axis.LastParameter))
         obj = edged[
             0].Object  #TARGET [solved]: make "where" deal with App::Parts
         if fCmd.isPartOfPart(obj):
             part = fCmd.isPartOfPart(obj)
             where = part.Placement.multiply(where)
         size = [
             self.Axis.Length / 20.0, self.Axis.Length / 10.0,
             self.Axis.Length / 20.0
         ]
         self.arrow = arrow(pl=where,
                            scale=size,
                            offset=self.Axis.Length / 10.0)
         if self.Axis.curvatureAt(0):
             O = self.Axis.centerOfCurvatureAt(0)
             n = self.Axis.tangentAt(0).cross(self.Axis.normalAt(0))
             from Part import Edge, Line
             self.Axis = (Edge(
                 Line(FreeCAD.Vector(O), FreeCAD.Vector(O + n))))
         self.form.lab1.setText(edged[0].Object.Label + ": edge")
Exemplo n.º 8
0
 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 fCmd.faces():
     Z=FreeCAD.Vector(0,0,1)
     for f in fCmd.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())
   elif fCmd.edges():
     for e in fCmd.edges():
       beam=makeStructure(profile)
       fCmd.placeTheBeam(beam,e)
       if self.form.editLength.text(): beam.Height=float(self.form.editLength.text())
   elif [v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]:
     vs=[v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]
     for v in vs:
       beam=makeStructure(profile)
       beam.Placement.Base=v.Point
   else:
     beam=makeStructure(profile)
     if self.form.editLength.text(): beam.Height=float(self.form.editLength.text())
   FreeCAD.ActiveDocument.recompute()
Exemplo n.º 9
0
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 fCmd.edges()]
    try:
      P=fCmd.intersectionCLines(*fCmd.edges())
    except: pass
  if hasattr(c,'PType') and hasattr(c,'BendAngle') and v1 and v2:
    v1.normalize()
    v2.normalize()
    ortho=rounded(fCmd.ortho(v1,v2))
    bisect=rounded(v2-v1)
    ang=degrees(v1.getAngle(v2))
    c.BendAngle=ang
    rot1=FreeCAD.Rotation(rounded(fCmd.beamAx(c,FreeCAD.Vector(0,0,1))),ortho)
    c.Placement.Rotation=rot1.multiply(c.Placement.Rotation)
    rot2=FreeCAD.Rotation(rounded(fCmd.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
Exemplo n.º 10
0
 def accept(self):
   if self.beam!=None and len(fCmd.edges())>0:
     FreeCAD.activeDocument().openTransaction('Fill frame')
     if self.form.radio1.isChecked():
       fCmd.placeTheBeam(self.beam,fCmd.edges()[0])
     else:
       for edge in fCmd.edges():
         struct=FreeCAD.activeDocument().copyObject(self.beam,True)
         fCmd.placeTheBeam(struct,edge)
       FreeCAD.activeDocument().recompute()
     FreeCAD.ActiveDocument.recompute()
     FreeCAD.activeDocument().commitTransaction()
Exemplo n.º 11
0
def doPipes(propList=['DN50',60.3,3,1000], pypeline=None):
  '''
    propList = [
      DN (string): nominal diameter
      OD (float): outside diameter
      thk (float): shell thickness
      H (float): length of pipe ]
    pypeline = string
  '''
  FreeCAD.activeDocument().openTransaction('Insert pipe')
  plist=list()
  if len(fCmd.edges())==0: #..no edges selected
    vs=[v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]
    if len(vs)==0: # ...no vertexes selected
      plist.append(makePipe(propList))
    else: # ... one or more vertexes
      for v in vs: plist.append(makePipe(propList,v.Point))
  else:
    selex=FreeCADGui.Selection.getSelectionEx()
    for objex in selex:
      o=objex.Object
      if fCmd.faces(): # Face selected...
        for face in fCmd.faces():
          x=(face.ParameterRange[0]+face.ParameterRange[1])/2
          y=(face.ParameterRange[2]+face.ParameterRange[3])/2
          plist.append(makePipe(propList,face.valueAt(x,y),face.normalAt(x,y)))
        FreeCAD.activeDocument().commitTransaction()
        FreeCAD.activeDocument().recompute()
      else:
        for edge in fCmd.edges([objex]): # ...one or more edges...
          if edge.curvatureAt(0)==0: # ...straight edges
            pL=propList
            pL[3]=edge.Length
            plist.append(makePipe(pL,edge.valueAt(0),edge.tangentAt(0)))
          else: # ...curved edges
            pos=edge.centerOfCurvatureAt(0)
            Z=edge.tangentAt(0).cross(edge.normalAt(0))
            if isElbow(o):
              p0,p1=[o.Placement.Rotation.multVec(p) for p in o.Ports]
              if not fCmd.isParallel(Z,p0):
                Z=p1
            plist.append(makePipe(propList,pos,Z))
  if pypeline:
    for p in plist:
      moveToPyLi(p,pypeline)
  FreeCAD.activeDocument().commitTransaction()
  FreeCAD.activeDocument().recompute()
  return plist
Exemplo n.º 12
0
def makeW():
  edges=fCmd.edges()
  if len(edges)>1:
    first=edges[0]
    last=edges[-1]
    points=list()
    while len(edges)>1: points.append(fCmd.intersectionCLines(edges.pop(0),edges[0]))
    delta1=(first.valueAt(0)-points[0]).Length
    delta2=(first.valueAt(first.LastParameter)-points[0]).Length
    if delta1>delta2:
      points.insert(0,first.valueAt(0))
    else:
      points.insert(0,first.valueAt(first.LastParameter))
    delta1=(last.valueAt(0)-points[0]).Length
    delta2=(last.valueAt(last.LastParameter)-points[0]).Length
    if delta1>delta2:
      points.append(last.valueAt(0))
    else:
      points.append(last.valueAt(last.LastParameter))
    from Draft import makeWire
    try:
      p=makeWire(points)
    except:
      FreeCAD.Console.PrintError('Missing intersection\n')
      return None
    p.Label='Path'
    drawAsCenterLine(p)
    return p
  elif FreeCADGui.Selection.getSelection():
    obj=FreeCADGui.Selection.getSelection()[0]
    if hasattr(obj,'Shape') and type(obj.Shape)==Part.Wire:
      drawAsCenterLine(obj)
    return obj
  else:
    return None
Exemplo n.º 13
0
def makeBranch(base=None, DN="DN50",PRating="SCH-STD",OD=60.3,thk=3,BR=None, lab="Traccia", color=(0.8,0.8,0.8)):
  '''
  makeBranch(base=None, DN="DN50",PRating="SCH-STD",OD=60.3,thk=3,BR=None, lab="Traccia" color=(0.8,0.8,0.8))
  Draft function for PypeBranch.
  '''
  if not BR:
    BR=0.75*OD
  if not base:
    if FreeCADGui.Selection.getSelection():
      obj=FreeCADGui.Selection.getSelection()[0]
      isWire=hasattr(obj,'Shape') and type(obj.Shape)==Part.Wire
      isSketch=hasattr(obj,'TypeId') and obj.TypeId=='Sketcher::SketchObject'
      if isWire or isSketch:
        base=obj
      if isWire:
        drawAsCenterLine(obj)
    elif fCmd.edges():
      base=makeW()
  if base:
    a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython",lab)
    pFeatures.PypeBranch2(a,base,DN,PRating,OD,thk,BR)
    pFeatures.ViewProviderPypeBranch(a.ViewObject)
    return a
  else:
    FreeCAD.Console.PrintError('Select a valid path.\n')
Exemplo n.º 14
0
def makeNozzle(DN='DN50', H=200, OD=60.3, thk=3,D=160, d=62, df=132,f=14,t=15,n=4):
  '''
  makeNozzle(DN,OD,thk,D,df,f,t,n)
    DN (string): nominal diameter
    OD (float): pipe outside diameter
    thk (float): pipe wall thickness
    D (float): flange diameter
    d (float): flange hole
    df (float): bolts holes distance
    f (float): bolts holes diameter
    t (float): flange thickness
    n (int): nr. of bolts
  '''
  selex=FreeCADGui.Selection.getSelectionEx()
  for sx in selex:
    #e=sx.SubObjects[0]
    s=sx.Object
    curved=[e for e in fCmd.edges([sx]) if e.curvatureAt(0)]
    for e in curved:
      pipe=makePipe([DN,OD,thk,H], pos=e.centerOfCurvatureAt(0),Z=e.tangentAt(0).cross(e.normalAt(0)))
      FreeCAD.ActiveDocument.recompute()
      flange=makeFlange([DN,'S.O.',D,d,df,f,t,n],pos=portsPos(pipe)[1],Z=portsDir(pipe)[1])
      pipe.MapReversed = False
      pipe.Support = [(s,fCmd.edgeName(s,e)[1])]
      pipe.MapMode = 'Concentric'
      FreeCADGui.Selection.clearSelection()
      FreeCADGui.Selection.addSelection(pipe)
      FreeCADGui.Selection.addSelection(flange)
      flange.Support = [(pipe,'Edge1')]
      flange.MapReversed = True
      flange.MapMode = 'Concentric'
      FreeCAD.ActiveDocument.recompute()
Exemplo n.º 15
0
def simpleSurfBend(path=None,profile=None):
  'select the centerline and the O.D. and let it sweep'
  curva=FreeCAD.activeDocument().addObject("Part::Feature",translate("Part::Feature","Simple curve"))
  if path==None or profile==None:
    curva.Shape=Part.makeSweepSurface(*fCmd.edges()[:2])
  elif path.ShapeType==profile.ShapeType=='Edge':
    curva.Shape=Part.makeSweepSurface(path,profile)
Exemplo n.º 16
0
def doFlanges(propList=["DN50", "SO", 160, 60.3, 132, 14, 15, 4, 0, 0, 0, 0, 0], pypeline=None):
  '''
    propList = [
      DN (string): nominal diameter
      FlangeType (string): type of Flange
      D (float): flange diameter
      d (float): bore diameter
      df (float): bolts holes distance
      f (float): bolts holes diameter
      t (float): flange thickness
      n (int): nr. of bolts
      trf (float): raised-face thikness - OPTIONAL -
      drf (float): raised-face diameter - OPTIONAL -
      twn (float): welding-neck thikness - OPTIONAL -
      dwn (float): welding-neck diameter - OPTIONAL -
      ODp (float): outside diameter of pipe for wn flanges - OPTIONAL -
    pypeline = string
  '''
  flist=[]
  tubes=[t for t in fCmd.beams() if hasattr(t,'PSize')]
  FreeCAD.activeDocument().openTransaction('Insert flange')
  if len(fCmd.edges())==0:
    vs=[v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]
    if len(vs)==0:
      flist.append(makeFlange(propList))
    else:
      for v in vs:
        flist.append(makeFlange(propList,v.Point))
  elif tubes:
    selex=FreeCADGui.Selection.getSelectionEx()
    for sx in selex:
      if isPipe(sx.Object) and fCmd.edges([sx]):
        for edge in fCmd.edges([sx]):
          if edge.curvatureAt(0)!=0:
            flist.append(makeFlange(propList,edge.centerOfCurvatureAt(0),sx.Object.Shape.Solids[0].CenterOfMass-edge.centerOfCurvatureAt(0)))
  else:
    for edge in fCmd.edges():
      if edge.curvatureAt(0)!=0:
        flist.append(makeFlange(propList,edge.centerOfCurvatureAt(0),edge.tangentAt(0).cross(edge.normalAt(0))))
  if pypeline:
    for f in flist:
      moveToPyLi(f,pypeline)
  FreeCAD.activeDocument().commitTransaction()
  FreeCAD.activeDocument().recompute()
  return flist
Exemplo n.º 17
0
 def selectAction(self):
     shapes = [
         y for x in FreeCADGui.Selection.getSelectionEx()
         for y in x.SubObjects if hasattr(y, 'ShapeType')
     ][:2]
     if len(shapes) > 1:
         self.getDistance()
     elif len(fCmd.edges()) > 0:
         self.getLength()
Exemplo n.º 18
0
 def pickAction(self,path=None,event=None,arg=None):
   FreeCAD.activeDocument().openTransaction('Quick move')
   if event.wasCtrlDown(): k=-1*float(self.edit.text())
   else: k=1*float(self.edit.text())
   sel=FreeCADGui.Selection.getSelection()
   if sel: self.objs=[o for o in sel if hasattr(o,'Shape')]
   if event.wasCtrlDown() and event.wasAltDown():
     alfa=float(self.edit2.text())
     if fCmd.edges(): 
       self.edge=fCmd.edges()[0]
       for o in self.objs: fCmd.rotateTheBeamAround(o, self.edge, alfa)
     elif self.edge:
       for o in self.objs: fCmd.rotateTheBeamAround(o, self.edge, alfa)
   else:
     for o in self.objs: o.Placement.move(self.direct*k)
     self.Placement.move(self.direct*k)
     pl,direct,M=[self.Placement,self.direct,self.scale]
     self.closeArrow()
     self.__init__(self.edit, self.edit2, pl,direct,M,self.objs)
   FreeCAD.activeDocument().commitTransaction()
Exemplo n.º 19
0
def alignTheTube():
  '''
  Mates the selected 2 circular edges
  of 2 separate objects.
  '''
  try:
    t1=FreeCADGui.Selection.getSelection()[0]
    t2=FreeCADGui.Selection.getSelection()[-1]
  except:
    FreeCAD.Console.PrintError("Select at least one object.\n")
    return None
  d1,d2=fCmd.edges()[:2]
  if d1.curvatureAt(0)!=0 and d2.curvatureAt(0)!=0:
    n1=d1.tangentAt(0).cross(d1.normalAt(0))
    n2=d2.tangentAt(0).cross(d2.normalAt(0))
  else:
    FreeCAD.Console.PrintError("Select 2 curved edges.\n")
    return None
  rot=FreeCAD.Rotation(n2,n1)
  t2.Placement.Rotation=rot.multiply(t2.Placement.Rotation)
  #traslazione centri di curvatura
  d1,d2=fCmd.edges() #redo selection to get new positions
  dist=d1.centerOfCurvatureAt(0)-d2.centerOfCurvatureAt(0)
  t2.Placement.move(dist)
  #verifica posizione relativa
  try:
    com1,com2=[t.Shape.Solids[0].CenterOfMass for t in [t1,t2]]
    if isElbow(t2):
      pass
    elif (com1-d1.centerOfCurvatureAt(0)).dot(com2-d1.centerOfCurvatureAt(0))>0:
      reverseTheTube(FreeCADGui.Selection.getSelectionEx()[:2][1])
  except:
    pass
  #TARGET [solved]: verify if t1 or t2 belong to App::Part and changes the Placement consequently
  if fCmd.isPartOfPart(t1):
    part=fCmd.isPartOfPart(t1)
    t2.Placement=part.Placement.multiply(t2.Placement)
  if fCmd.isPartOfPart(t2):
    part=fCmd.isPartOfPart(t2)
    t2.Placement=part.Placement.inverse().multiply(t2.Placement)
Exemplo n.º 20
0
def makeElbowBetweenThings(thing1=None, thing2=None, propList=None):
  '''
  makeElbowBetweenThings(thing1, thing2, propList=None):
  Place one elbow at the intersection of thing1 and thing2.
  Things can be any combination of intersecting beams, pipes or edges.
  If nothing is passed as argument, the function attempts to take the
  first two edges selected in the view.
  propList is one optional list with 5 elements:
    DN (string): nominal diameter
    OD (float): outside diameter
    thk (float): shell thickness
    BA (float): bend angle - that will be recalculated! -
    BR (float): bend radius
  Default is "DN50 (SCH-STD)"
  Remember: property PRating must be defined afterwards
  '''
  if not (thing1 and thing2):
    thing1,thing2=fCmd.edges()[:2]
  P=fCmd.intersectionCLines(thing1,thing2)
  directions=list()
  try:
    for thing in [thing1,thing2]:
      if fCmd.beams([thing]):
        directions.append(rounded((fCmd.beamAx(thing).multiply(thing.Height/2)+thing.Placement.Base)-P))
      elif hasattr(thing,'ShapeType') and thing.ShapeType=='Edge':
        directions.append(rounded(thing.CenterOfMass-P))
  except:
    return None
  ang=180-degrees(directions[0].getAngle(directions[1]))
  if ang==0 or ang==180: return None
  if not propList:
    propList=["DN50",60.3,3.91,ang,45.24]
  else:
    propList[3]=ang
  elb=makeElbow(propList,P,directions[0].negative().cross(directions[1].negative()))
  # mate the elbow ends with the pipes or edges
  b=fCmd.bisect(directions[0],directions[1])
  elbBisect=rounded(fCmd.beamAx(elb,FreeCAD.Vector(1,1,0))) #if not rounded, fail in plane xz
  rot=FreeCAD.Rotation(elbBisect,b)
  elb.Placement.Rotation=rot.multiply(elb.Placement.Rotation)
  # trim the adjacent tubes
  #FreeCAD.activeDocument().recompute() # may delete this row?
  portA=elb.Placement.multVec(elb.Ports[0])
  portB=elb.Placement.multVec(elb.Ports[1])
  for tube in [t for t in [thing1,thing2] if fCmd.beams([t])]:
    vectA=tube.Shape.Solids[0].CenterOfMass-portA
    vectB=tube.Shape.Solids[0].CenterOfMass-portB
    if fCmd.isParallel(vectA,fCmd.beamAx(tube)):
      fCmd.extendTheBeam(tube,portA)
    else:
      fCmd.extendTheBeam(tube,portB)
  return elb
Exemplo n.º 21
0
 def getLength(self):
   roundDigits=3
   if len(fCmd.edges())>0:
     edge=fCmd.edges()[0]
     self.form.edit4.setText(str(edge.Length))
     self.form.edit5.setText('1')
     dx,dy,dz=list(edge.tangentAt(0))
     self.form.edit1.setText(str(round(dx,roundDigits)))
     self.form.edit2.setText(str(round(dy,roundDigits)))
     self.form.edit3.setText(str(round(dz,roundDigits)))
     self.deleteArrow()
     from uCmd import arrow
     where=FreeCAD.Placement()
     where.Base=edge.valueAt(0)
     where.Rotation=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),edge.tangentAt(0))
     # obj=fCmd.edgeName[0] #TARGET [working]: make "where" deal with App::Parts
     # if fCmd.isPartOfPart(obj):
       # part=fCmd.isPartOfPart(obj)
       # where=part.Placement.multiply(where)
     size=[edge.Length/20.0,edge.Length/10.0,edge.Length/20.0]
     self.arrow=arrow(pl=where,scale=size,offset=edge.Length/2.0)
     FreeCADGui.Selection.clearSelection()
Exemplo n.º 22
0
 def Activated(self):
   import FreeCAD, FreeCADGui, fCmd, fObservers
   edges=fCmd.edges()
   if len(edges)>=2 and len(FreeCADGui.Selection.getSelection())>=2:
     e1=edges.pop(0)
     beams=FreeCADGui.Selection.getSelection()[1:]
     if len(edges)==len(beams):
       pairs=[(beams[i],edges[i]) for i in range(len(beams))]
       FreeCAD.activeDocument().openTransaction('AlignEdge')
       for p in pairs:
         fCmd.joinTheBeamsEdges(p[0],e1,p[1])
       FreeCAD.activeDocument().commitTransaction()
   else:
     FreeCADGui.Selection.clearSelection()
     s=fObservers.alignEdgeObserver()
     FreeCADGui.Selection.addObserver(s)
Exemplo n.º 23
0
def setWP():  #TARGET [working]: deal with App::Parts
    'function to change working plane'
    import FreeCAD, FreeCADGui, fCmd
    normal = point = None
    curves = []
    straight = []
    Z = FreeCAD.Vector(0, 0, 1)
    for edge in fCmd.edges():
        if edge.curvatureAt(0) != 0:
            curves.append(edge)
        else:
            straight.append(edge)
    # define normal: 1st from face->2nd from curve->3rd from straight edges
    if fCmd.faces():
        normal = fCmd.faces()[0].normalAt(0, 0)
    elif curves:
        normal = curves[0].tangentAt(0).cross(curves[0].normalAt(0))
    elif len(straight) > 1:
        if straight and not fCmd.isParallel(straight[0].tangentAt(0),
                                            straight[1].tangentAt(0)):
            normal = straight[0].tangentAt(0).cross(straight[1].tangentAt(0))
    elif FreeCADGui.Selection.getSelection():
        normal = FreeCAD.DraftWorkingPlane.getRotation().multVec(Z)
    else:
        normal = Z
    # define point: 1st from vertex->2nd from centerOfCurvature->3rd from intersection->4th from center of edge
    points = [
        v.Point for sx in FreeCADGui.Selection.getSelectionEx()
        for v in sx.SubObjects if v.ShapeType == 'Vertex'
    ]
    if not points:
        points = [edge.centerOfCurvatureAt(0) for edge in curves]
    if not points and len(straight) > 1:
        inters = fCmd.intersectionCLines(straight[0], straight[1])
        if inters:
            points.append(inters)
    if not points and len(straight):
        points.append(straight[0].CenterOfMass)
    if points:
        point = points[0]
    else:
        point = FreeCAD.Vector()
    # move the draft WP
    FreeCAD.DraftWorkingPlane.alignToPointAndAxis(point, normal)
    FreeCADGui.Snapper.setGrid()
Exemplo n.º 24
0
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 fCmd.edges([objEx]):
      if edge.curvatureAt(0):
        disp=edge.centerOfCurvatureAt(0)-objEx.Object.Placement.Base
        break
      elif fCmd.beams([objEx.Object]):
        ax=fCmd.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)
Exemplo n.º 25
0
 def accept(self):
     fname = self.form.listFiles.currentItem().text()
     row = None
     pos = None
     Z = None
     if self.form.comboDirs.currentText() == '<shapes>': sdir = ''
     else: sdir = self.form.comboDirs.currentText()
     if fname in self.filesListed:
         for r in self.pipeDictList:
             if r["fileName"] == fname:
                 row = r
                 break
         name = row["name"]
         ports = row["ports"]
     else:
         name = fname.split('.')[0]
         ports = '0:0:0'
     selex = FreeCADGui.Selection.getSelectionEx()
     if selex:
         vxs = [
             v for sx in selex for so in sx.SubObjects for v in so.Vertexes
         ]
         cedges = [e for e in fCmd.edges() if e.curvatureAt(0) != 0]
         faces = fCmd.faces()
         if faces:
             x = (faces[0].ParameterRange[0] +
                  faces[0].ParameterRange[1]) / 2
             y = (faces[0].ParameterRange[2] +
                  faces[0].ParameterRange[3]) / 2
             pos = faces[0].valueAt(x, y)
             Z = faces[0].normalAt(x, y)
         elif cedges:
             pos = cedges[0].centerOfCurvatureAt(0)
             Z = cedges[0].tangentAt(0).cross(cedges[0].normalAt(0))
         elif vxs:
             pos = vxs[0].Point
     self.lastThing = makeThing(name, join(sdir, fname), ports, pos, Z)
     if row:
         self.lastThing.Kv = float(row["Kv"])
         self.lastThing.PSize = row["DN"]
         self.lastThing.PRating = row["PN"]
Exemplo n.º 26
0
 def addBeams(self):
   # find selected FB
   try:
     FB=findFB(baseName=FreeCADGui.Selection.getSelection()[0].Name)
   except:
     return
   if FB:
     beamsList=FB.Beams
     for edge in fCmd.edges():
       i=indexEdge(edge,FB.Base.Shape.Edges)
       beam=makeStructure(FB.Profile)
       beam.addProperty("App::PropertyFloat","tailOffset","FrameBranch","The extension of the tail")
       beam.addProperty("App::PropertyFloat","headOffset","FrameBranch","The extension of the head")
       beam.addProperty("App::PropertyFloat","spin","FrameBranch","The rotation of the section")
       beam.addExtension("Part::AttachExtensionPython",beam)
       beam.Support=[(FB.Base,'Edge'+str(i+1))]
       beam.MapMode='NormalToEdge'
       beam.MapReversed=True
       beamsList[i]=str(beam.Name)
     FB.Beams=beamsList
     FreeCAD.ActiveDocument.recompute()
     FreeCAD.ActiveDocument.recompute()
Exemplo n.º 27
0
 def insert(self):
   from pCmd import moveToPyLi
   if self.combo.currentText()=='<new>':
     name=self.edit1.text()
     if not name: name='Telaio'
     a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name)
     FrameLine(a)
     a.ViewObject.Proxy=0
     self.combo.addItem(a.Label)
     self.combo.setCurrentIndex(self.combo.count()-1)
     if self.sectList.selectedItems():
       self.getProfile()
   elif self.sectList.selectedItems():
     prof= FreeCAD.ActiveDocument.getObjectsByLabel(self.sectList.selectedItems()[0].text())[0]
     for e in fCmd.edges():
       if self.cb1.isChecked():
         s=makeStructure(FreeCAD.ActiveDocument.copyObject(prof))
       else:
         s=makeStructure(prof)
       fCmd.placeTheBeam(s,e)
       moveToPyLi(s,self.current.Name)
     FreeCAD.ActiveDocument.recompute()
Exemplo n.º 28
0
def makeRoute(n=Z):
  curvedEdges=[e for e in fCmd.edges() if e.curvatureAt(0)!=0]
  if curvedEdges:
    s=FreeCAD.ActiveDocument.addObject('Sketcher::SketchObject',translate("Sketcher::SketchObject",'pipeRoute'))
    s.MapMode = "SectionOfRevolution"
    sup=fCmd.edgeName()
    s.Support = [sup]
    if fCmd.isPartOfPart(sup[0]): #TARGET [working]: takes care if support belongs to App::Part
      part=fCmd.isPartOfPart(sup[0])
      FreeCAD.Console.PrintMessage('*** '+sup[0].Label+' is part of '+part.Label+' ***\n') #debug
      #s.AttachmentOffset=part.Placement.multiply(s.AttachmentOffset)
  else:
    return None
  if fCmd.faces():
    n=fCmd.faces()[0].normalAt(0,0)
  x=s.Placement.Rotation.multVec(X)
  z=s.Placement.Rotation.multVec(Z)
  t=x.dot(n)*x+z.dot(n)*z
  alfa=degrees(z.getAngle(t))
  if t.Length>0.000000001:
    s.AttachmentOffset.Rotation=s.AttachmentOffset.Rotation.multiply(FreeCAD.Rotation(Y,alfa))
  FreeCAD.ActiveDocument.recompute()
  FreeCADGui.activeDocument().setEdit(s.Name)
Exemplo n.º 29
0
def doValves(propList=["DN50", "ball", 72, 50, 40, 150],pypeline=None, pos=0):
  '''
    propList = [
      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) ]
    pypeline = string
    pos (]0..100[) = position along pipe or edge
  '''
  # self.lastValve=None
  color=0.05,0.3,0.75
  vlist=[]
  # d=self.pipeDictList[self.sizeList.currentRow()]
  FreeCAD.activeDocument().openTransaction('Insert valve')
  # propList=[d['PSize'],d['VType'],float(pq(d['OD'])),float(pq(d['ID'])),float(pq(d['H'])),float(pq(d['Kv']))]
  if 0 < pos < 100: # ..place the valve in the middle of pipe(s)
    pipes=[p for p in FreeCADGui.Selection.getSelection() if isPipe(p)]
    if pipes:
      for p1 in pipes:
        vlist.append(makeValve(propList))
        p2=breakTheTubes(float(p1.Height)*pos/100, pipes=[p1], gap=float(vlist[-1].Height))[0]
        if p2 and pypeline: moveToPyLi(p2,pypeline)
        vlist[-1].Placement=p1.Placement
        vlist[-1].Placement.move(portsDir(p1)[1]*float(p1.Height))
        vlist[-1].ViewObject.ShapeColor=color
        # if self.combo.currentText()!='<none>':
          # pCmd.moveToPyLi(self.lastValve,self.combo.currentText())
      # FreeCAD.ActiveDocument.recompute()
  elif len(fCmd.edges())==0: #..no edges selected
    vs=[v for sx in FreeCADGui.Selection.getSelectionEx() for so in sx.SubObjects for v in so.Vertexes]
    if len(vs)==0: # ...no vertexes selected
      vlist.append(makeValve(propList))
      vlist[-1].ViewObject.ShapeColor=color
      # if self.combo.currentText()!='<none>':
        # pCmd.moveToPyLi(self.lastValve,self.combo.currentText())
    else:
      for v in vs: # ... one or more vertexes
        vlist.append(makeValve(propList,v.Point))
        vlist[-1].ViewObject.ShapeColor=color
        # if self.combo.currentText()!='<none>':
          # pCmd.moveToPyLi(self.lastValve,self.combo.currentText())
  else:
    selex=FreeCADGui.Selection.getSelectionEx()
    for objex in selex:
      o=objex.Object
      for edge in fCmd.edges([objex]): # ...one or more edges...
        if edge.curvatureAt(0)==0: # ...straight edges
          vlist.append(makeValve(propList,edge.valueAt(edge.LastParameter/2-propList[4]/2),edge.tangentAt(0)))
          # if self.combo.currentText()!='<none>':
            # pCmd.moveToPyLi(self.lastValve,self.combo.currentText())
        else: # ...curved edges
          pos=edge.centerOfCurvatureAt(0) # SNIPPET TO ALIGN WITH THE PORTS OF Pype SELECTED: BEGIN...
          if hasattr(o,'PType') and len(o.Ports)==2:
            p0,p1=portsPos(o)
            if (p0-pos).Length<(p1-pos).Length:
              Z=portsDir(o)[0]
            else:
              Z=portsDir(o)[1]
          else:
            Z=edge.tangentAt(0).cross(edge.normalAt(0)) # ...END
          vlist.append(makeValve(propList,pos,Z))
          # if self.combo.currentText()!='<none>':
            # pCmd.moveToPyLi(self.lastValve,self.combo.currentText())
        vlist[-1].ViewObject.ShapeColor=color
  if pypeline:
    for v in vlist:
      moveToPyLi(v,pypeline)
  FreeCAD.activeDocument().commitTransaction()
  FreeCAD.activeDocument().recompute()
  return vlist
Exemplo n.º 30
0
def doElbow(propList=['DN50',60.3,3,90,45.225], pypeline=None):
  '''
    propList = [
      DN (string): nominal diameter
      OD (float): outside diameter
      thk (float): shell thickness
      BA (float): bend angle
      BR (float): bend radius ]
    pypeline = string
  '''
  elist=[]
  FreeCAD.activeDocument().openTransaction('Insert elbow')
  selex=FreeCADGui.Selection.getSelectionEx()
  if len(selex)==0:     # no selection -> insert one elbow at origin
    elist.append(makeElbow(propList))
  elif len(selex)==1 and len(selex[0].SubObjects)==1:  #one selection -> ...
    if selex[0].SubObjects[0].ShapeType=="Vertex":   # ...on vertex
      elist.append(makeElbow(propList,selex[0].SubObjects[0].Point))
    elif selex[0].SubObjects[0].ShapeType=="Edge" and  selex[0].SubObjects[0].curvatureAt(0)!=0: # ...on center of curved edge
      P=selex[0].SubObjects[0].centerOfCurvatureAt(0)
      N=selex[0].SubObjects[0].normalAt(0).cross(selex[0].SubObjects[0].tangentAt(0)).normalize()
      elb=makeElbow(propList,P)
      if isPipe(selex[0].Object): #..on the edge of a pipe
        ax=selex[0].Object.Shape.Solids[0].CenterOfMass-P
        rot=FreeCAD.Rotation(elb.Ports[0],ax)
        elb.Placement.Rotation=rot.multiply(elb.Placement.Rotation)
        Port0=getElbowPort(elb)
        elb.Placement.move(P-Port0)
      elif isElbow(selex[0].Object): #..on the edge of an elbow
        p0,p1=[selex[0].Object.Placement.Rotation.multVec(p) for p in selex[0].Object.Ports]
        if fCmd.isParallel(p0,N):
          elb.Placement.Rotation=FreeCAD.Rotation(elb.Ports[0],p0*-1)
        else:
          elb.Placement.Rotation=FreeCAD.Rotation(elb.Ports[0],p1*-1)
        delta=getElbowPort(elb)
        elb.Placement.move(P-delta)
      else: #..on any other curved edge
        print('hello')
        rot=FreeCAD.Rotation(elb.Ports[0],N)
        elb.Placement.Rotation=rot.multiply(elb.Placement.Rotation)
        # elb.Placement.move(elb.Placement.Rotation.multVec(elb.Ports[0])*-1)
        v=portsDir(elb)[0].negative()*elb.Ports[0].Length
        elb.Placement.move(v)
      elist.append(elb)
      FreeCAD.activeDocument().recompute()
  else:       # multiple selection -> insert one elbow at intersection of two edges or beams or pipes ##
    things=[]
    for objEx in selex:
      if len(fCmd.beams([objEx.Object]))==1:  # if the object is a beam or pipe, append it to the "things"..
        things.append(objEx.Object)
      else:                                   # ..else append its edges
        for edge in fCmd.edges([objEx]):
          things.append(edge)
      if len(things)>=2:
        break
    try:                                      #create the feature
      elb=elist.append(makeElbowBetweenThings(*things[:2],propList=propList))
    except:
      FreeCAD.Console.PrintError('Creation of elbow is failed\n')
  if pypeline:
    for e in elist:
      moveToPyLi(e,pypeline)
  FreeCAD.activeDocument().commitTransaction()
  FreeCAD.activeDocument().recompute()
  return elist