
New property 'Freeze' added to assembly container to freeze any update of the assembly. AsmPartGroup and AsmElement has been change to bind to Part::FeaturePython instead of App::FeaturePython, in order to be able to hold its own shape when frozen. The new ChildViewProvider feature in ViewProviderLink is used to display the native shape.
2294 lines
81 KiB
Python
2294 lines
81 KiB
Python
import os
|
|
from collections import namedtuple
|
|
import FreeCAD, FreeCADGui, Part
|
|
from PySide import QtCore, QtGui
|
|
from . import utils, gui
|
|
from .utils import logger, objName
|
|
from .constraint import Constraint, cstrName
|
|
from .system import System
|
|
|
|
def isTypeOf(obj,tp,resolve=False):
|
|
if not obj:
|
|
return False
|
|
if not tp:
|
|
return True
|
|
if resolve:
|
|
obj = obj.getLinkedObject(True)
|
|
return isinstance(getattr(obj,'Proxy',None),tp)
|
|
|
|
def checkType(obj,tp,resolve=False):
|
|
if not isTypeOf(obj,tp,resolve):
|
|
raise TypeError('Expect object {} to be of type "{}"'.format(
|
|
objName(obj),tp.__name__))
|
|
|
|
def getProxy(obj,tp):
|
|
checkType(obj,tp)
|
|
return obj.Proxy
|
|
|
|
def resolveAssembly(obj):
|
|
'''Try various ways to obtain an assembly from the input object
|
|
|
|
obj can be a link, a proxy, a child group of an assembly, or simply an
|
|
assembly
|
|
'''
|
|
func = getattr(obj,'getLinkedObject',None)
|
|
if func:
|
|
obj = func(True)
|
|
proxy = getattr(obj,'Proxy',None)
|
|
if proxy:
|
|
obj = proxy
|
|
if isinstance(obj,Assembly):
|
|
return obj
|
|
func = getattr(obj,'getAssembly',None)
|
|
if func:
|
|
return func()
|
|
raise TypeError('cannot resolve assembly from {}'.format(obj))
|
|
|
|
|
|
# For faking selection obtained from Gui.getSelectionEx()
|
|
Selection = namedtuple('AsmSelection',('Object','SubElementNames'))
|
|
|
|
_IgnoredProperties = set(['VisibilityList','Visibility',
|
|
'Label','_LinkRecomputed'])
|
|
|
|
class AsmBase(object):
|
|
def __init__(self):
|
|
self.Object = None
|
|
|
|
def __getstate__(self):
|
|
return
|
|
|
|
def __setstate__(self,_state):
|
|
return
|
|
|
|
def attach(self,obj):
|
|
obj.addExtension('App::LinkBaseExtensionPython', None)
|
|
self.linkSetup(obj)
|
|
|
|
def linkSetup(self,obj):
|
|
assert getattr(obj,'Proxy',None)==self
|
|
self.Object = obj
|
|
return
|
|
|
|
def getViewProviderName(self,_obj):
|
|
return 'Gui::ViewProviderLinkPython'
|
|
|
|
def onDocumentRestored(self, obj):
|
|
self.linkSetup(obj)
|
|
|
|
|
|
class ViewProviderAsmBase(object):
|
|
def __init__(self,vobj):
|
|
vobj.Visibility = False
|
|
vobj.Proxy = self
|
|
self.attach(vobj)
|
|
|
|
_addToSceneGraph = False
|
|
|
|
def attach(self,vobj):
|
|
self.ViewObject = vobj
|
|
vobj.signalChangeIcon()
|
|
vobj.setPropertyStatus('Visibility','Hidden')
|
|
if not self._addToSceneGraph:
|
|
vobj.Document.ActiveView.getSceneGraph().removeChild(vobj.RootNode)
|
|
|
|
def __getstate__(self):
|
|
return None
|
|
|
|
def __setstate__(self, _state):
|
|
return None
|
|
|
|
_iconName = None
|
|
|
|
@classmethod
|
|
def getIcon(cls):
|
|
if cls._iconName:
|
|
return utils.getIcon(cls)
|
|
|
|
def canDropObjects(self):
|
|
return True
|
|
|
|
def canDragObjects(self):
|
|
return False
|
|
|
|
def canDragAndDropObject(self,_obj):
|
|
return False
|
|
|
|
|
|
class ViewProviderAsmOnTop(ViewProviderAsmBase):
|
|
def __init__(self,vobj):
|
|
vobj.OnTopWhenSelected = 2
|
|
super(ViewProviderAsmOnTop,self).__init__(vobj)
|
|
|
|
|
|
class AsmGroup(AsmBase):
|
|
def linkSetup(self,obj):
|
|
super(AsmGroup,self).linkSetup(obj)
|
|
obj.configLinkProperty(
|
|
'VisibilityList',LinkMode='GroupMode',ElementList='Group')
|
|
self.groupSetup()
|
|
|
|
def groupSetup(self):
|
|
self.Object.setPropertyStatus('GroupMode','-Immutable')
|
|
self.Object.GroupMode = 1 # auto delete children
|
|
self.Object.setPropertyStatus('GroupMode',
|
|
('Hidden','Immutable','Transient'))
|
|
self.Object.setPropertyStatus('Group',('Hidden','Immutable'))
|
|
self.Object.setPropertyStatus('VisibilityList','Output')
|
|
|
|
def attach(self,obj):
|
|
obj.addProperty("App::PropertyLinkList","Group","Base",'')
|
|
obj.addProperty("App::PropertyBoolList","VisibilityList","Base",'')
|
|
obj.addProperty("App::PropertyEnumeration","GroupMode","Base",'')
|
|
super(AsmGroup,self).attach(obj)
|
|
|
|
def allowDuplicateLabel(self,_obj):
|
|
return True
|
|
|
|
|
|
class ViewProviderAsmGroup(ViewProviderAsmBase):
|
|
def claimChildren(self):
|
|
return self.ViewObject.Object.Group
|
|
|
|
def doubleClicked(self, _vobj):
|
|
return False
|
|
|
|
def canDropObject(self,_child):
|
|
return False
|
|
|
|
|
|
class ViewProviderAsmGroupOnTop(ViewProviderAsmGroup):
|
|
def __init__(self,vobj):
|
|
vobj.OnTopWhenSelected = 2
|
|
super(ViewProviderAsmGroupOnTop,self).__init__(vobj)
|
|
|
|
class AsmPartGroup(AsmGroup):
|
|
def __init__(self,parent):
|
|
self.parent = getProxy(parent,Assembly)
|
|
super(AsmPartGroup,self).__init__()
|
|
|
|
def getAssembly(self):
|
|
return self.parent
|
|
|
|
def groupSetup(self):
|
|
pass
|
|
|
|
def canLoadPartial(self,_obj):
|
|
return 1 if self.getAssembly().frozen else 0
|
|
|
|
@staticmethod
|
|
def make(parent,name='Parts'):
|
|
obj = parent.Document.addObject("Part::FeaturePython",name,
|
|
AsmPartGroup(parent),None,True)
|
|
obj.setPropertyStatus('Placement',('Output','Hidden'))
|
|
obj.setPropertyStatus('Shape','Output')
|
|
ViewProviderAsmPartGroup(obj.ViewObject)
|
|
obj.purgeTouched()
|
|
return obj
|
|
|
|
|
|
class ViewProviderAsmPartGroup(ViewProviderAsmGroup):
|
|
_iconName = 'Assembly_Assembly_Part_Tree.svg'
|
|
|
|
def onDelete(self,_obj,_subs):
|
|
return False
|
|
|
|
def canDropObjectEx(self,obj,_owner,_subname,_elements):
|
|
return isTypeOf(obj,Assembly, True) or not isTypeOf(obj,AsmBase)
|
|
|
|
def canDragObject(self,_obj):
|
|
return True
|
|
|
|
def canDragObjects(self):
|
|
return True
|
|
|
|
def canDragAndDropObject(self,_obj):
|
|
return True
|
|
|
|
def updateData(self,obj,prop):
|
|
if not hasattr(self,'ViewObject') or FreeCAD.isRestoring():
|
|
return
|
|
if prop == 'Shape':
|
|
cvp = obj.ViewObject.ChildViewProvider
|
|
if cvp:
|
|
cvp.mapShapeColors()
|
|
|
|
def showParts(self):
|
|
vobj = self.ViewObject
|
|
obj = vobj.Object
|
|
assembly = obj.Proxy.getAssembly().Object
|
|
if not assembly.ViewObject.ShowParts and \
|
|
(assembly.Freeze or (assembly.BuildShape!=BuildShapeNone and \
|
|
assembly.BuildShape!=BuildShapeCompound)):
|
|
mode = 1
|
|
else:
|
|
mode = 0
|
|
if not vobj.ChildViewProvider:
|
|
if not mode:
|
|
return
|
|
vobj.ChildViewProvider = 'PartGui::ViewProviderPartExt'
|
|
vobj.DefaultMode = mode
|
|
|
|
|
|
class AsmElement(AsmBase):
|
|
def __init__(self,parent):
|
|
self._initializing = True
|
|
self.shape = None
|
|
self.parent = getProxy(parent,AsmElementGroup)
|
|
super(AsmElement,self).__init__()
|
|
|
|
def linkSetup(self,obj):
|
|
super(AsmElement,self).linkSetup(obj)
|
|
if not hasattr(obj,'Offset'):
|
|
obj.addProperty("App::PropertyPlacement","Offset"," Link",'')
|
|
if not hasattr(obj,'Placement'):
|
|
obj.addProperty("App::PropertyPlacement","Placement"," Link",'')
|
|
obj.setPropertyStatus('Placement',['Immutable','Hidden'])
|
|
if not hasattr(obj,'LinkTransform'):
|
|
obj.addProperty("App::PropertyBool","LinkTransform"," Link",'')
|
|
obj.LinkTransform = True
|
|
obj.setPropertyStatus('LinkTransform',['Immutable','Hidden'])
|
|
obj.configLinkProperty('LinkedObject','Placement','LinkTransform')
|
|
obj.setPropertyStatus('LinkedObject','ReadOnly')
|
|
self.shape = None
|
|
|
|
def attach(self,obj):
|
|
obj.addProperty("App::PropertyXLink","LinkedObject"," Link",'')
|
|
super(AsmElement,self).attach(obj)
|
|
|
|
def canLinkProperties(self,_obj):
|
|
return False
|
|
|
|
def allowDuplicateLabel(self,_obj):
|
|
return True
|
|
|
|
def onBeforeChangeLabel(self,obj,label):
|
|
parent = getattr(self,'parent',None)
|
|
if parent and not getattr(self,'_initializing',False):
|
|
return parent.onChildLabelChange(obj,label)
|
|
|
|
def onChanged(self,_obj,prop):
|
|
parent = getattr(self,'parent',None)
|
|
if not parent or FreeCAD.isRestoring():
|
|
return
|
|
if prop=='Offset':
|
|
self.update()
|
|
elif prop == 'Label':
|
|
parent.Object.cacheChildLabel()
|
|
if prop not in _IgnoredProperties and \
|
|
not Constraint.isDisabled(parent.Object):
|
|
Assembly.autoSolve()
|
|
|
|
def execute(self,_obj):
|
|
self.updatePlacement()
|
|
return False
|
|
|
|
def updatePlacement(self):
|
|
obj = self.Object
|
|
info = getElementInfo(self.getAssembly().getPartGroup(),
|
|
self.getElementSubname(),offset=self.Object.Offset)
|
|
if not info:
|
|
return
|
|
self.shape = info.Shape
|
|
if not utils.isSamePlacement(info.PlacementOffset,obj.Placement):
|
|
obj.setPropertyStatus('Placement','-Immutable')
|
|
obj.Placement = info.PlacementOffset
|
|
obj.setPropertyStatus('Placement','Immutable')
|
|
|
|
def freeze(self):
|
|
obj = self.Object
|
|
if self.getAssembly().Freeze:
|
|
if not self.shape:
|
|
self.updatePlacement();
|
|
if self.shape:
|
|
# make a compound to contain the shape's transformation
|
|
shape = Part.makeCompound(self.shape)
|
|
shape.ElementMap = self.shape.ElementMap
|
|
obj.Shape = shape
|
|
elif not obj.Shape.isNull():
|
|
obj.Shape = Part.Shape()
|
|
|
|
def getAssembly(self):
|
|
return self.parent.parent
|
|
|
|
def getSubElement(self):
|
|
link = self.Object.LinkedObject
|
|
if isinstance(link,tuple):
|
|
return link[1].split('.')[-1]
|
|
return ''
|
|
|
|
def getSubName(self):
|
|
link = self.Object.LinkedObject
|
|
if not isinstance(link,tuple):
|
|
raise RuntimeError('Invalid element link "{}"'.format(
|
|
objName(self.Object)))
|
|
return link[1]
|
|
|
|
def getElementSubname(self):
|
|
'''
|
|
Resolve the geometry element link relative to the parent assembly's part
|
|
group
|
|
'''
|
|
|
|
subname = self.getSubName()
|
|
obj = self.Object.getLinkedObject(False)
|
|
if not obj or obj == self.Object:
|
|
raise RuntimeError('Borken element link')
|
|
if not isTypeOf(obj,AsmElement):
|
|
# If not pointing to another element, then assume we are directly
|
|
# pointing to the geometry element, just return as it is, which is a
|
|
# subname relative to the parent assembly part group
|
|
return subname
|
|
|
|
childElement = obj.Proxy
|
|
|
|
# If pointing to another element in the child assembly, first pop two
|
|
# names in the subname reference, i.e. element label and element group
|
|
# name
|
|
idx = subname.rfind('.',0,subname.rfind('.',0,-1))
|
|
subname = subname[:idx+1]
|
|
|
|
# append the child assembly part group name, and recursively call into
|
|
# child element
|
|
return subname+childElement.getAssembly().getPartGroup().Name+'.'+\
|
|
childElement.getElementSubname()
|
|
|
|
# Element: optional, if none, then a new element will be created if no
|
|
# pre-existing. Or else, it shall be the element to be amended
|
|
# Group: the immediate child object of an assembly (i.e. ConstraintGroup,
|
|
# ElementGroup, or PartGroup)
|
|
# Subname: the subname reference realtive to 'Group'
|
|
Selection = namedtuple('AsmElementSelection',('Element','Group','Subname'))
|
|
|
|
@staticmethod
|
|
def getSelection():
|
|
'''
|
|
Parse Gui.Selection for making an element
|
|
|
|
If there is only one selection, then the selection must refer to a sub
|
|
element of some part object of an assembly. We shall create a new
|
|
element beloning to the top-level assembly
|
|
|
|
If there are two selections, then first one shall be either the
|
|
element group or an individual element. The second selection shall
|
|
be a sub-element belong to a child assembly of the parent assembly of
|
|
the first selected element/element group
|
|
'''
|
|
sels = FreeCADGui.Selection.getSelectionEx('',False)
|
|
if not sels:
|
|
return
|
|
if len(sels)>1:
|
|
raise RuntimeError(
|
|
'The selections must have a common (grand)parent assembly')
|
|
|
|
sel = sels[0]
|
|
subs = list(sel.SubElementNames)
|
|
if not subs:
|
|
raise RuntimeError('no sub-object in selection')
|
|
if len(subs)>2:
|
|
raise RuntimeError('At most two selection is allowed.\n'
|
|
'The first selection must be a sub-element belonging to some '
|
|
'assembly. The optional second selection must be an element '
|
|
'belonging to the same assembly of the first selection')
|
|
if len(subs)==2:
|
|
if len(subs[0])<len(subs[1]):
|
|
subs = [subs[1],subs[2]]
|
|
|
|
if subs[0][-1] == '.':
|
|
if not utils.isElement((sel.Object,subs[0])):
|
|
raise RuntimeError('no sub-element (face, edge, vertex) in '
|
|
'{}.{}'.format(sel.Object.Name,subs[0]))
|
|
subElement = utils.deduceSelectedElement(sel.Object,subs[0])
|
|
if subElement:
|
|
subs[0] += subElement
|
|
|
|
link = Assembly.findPartGroup(sel.Object,subs[0])
|
|
if not link:
|
|
raise RuntimeError(
|
|
'Selected sub-element does not belong to an assembly')
|
|
|
|
element = None
|
|
if len(subs)>1:
|
|
ret = Assembly.findElementGroup(sel.Object,subs[1])
|
|
if not ret:
|
|
raise RuntimeError('The second selection must be an element')
|
|
|
|
if ret.Assembly != link.Assembly:
|
|
raise RuntimeError(
|
|
'The two selections must belong to the same assembly')
|
|
|
|
element = ret.Object.getSubObject(ret.Subname,1)
|
|
if not isTypeOf(element,AsmElement):
|
|
raise RuntimeError('The second selection must be an element')
|
|
|
|
return AsmElement.Selection(Element=element, Group=link.Object,
|
|
Subname=link.Subname+subElement)
|
|
|
|
@classmethod
|
|
def create(cls,name,elements):
|
|
element = elements.Document.addObject("Part::FeaturePython",
|
|
name,cls(elements),None,True)
|
|
ViewProviderAsmElement(element.ViewObject)
|
|
return element
|
|
|
|
@staticmethod
|
|
def make(selection=None,name='Element',undo=False):
|
|
'''Add/get/modify an element with the given selected object'''
|
|
if not selection:
|
|
selection = AsmElement.getSelection()
|
|
|
|
group = selection.Group
|
|
subname = selection.Subname
|
|
|
|
if isTypeOf(group,AsmElementGroup):
|
|
# if the selected object is an element of the owner assembly, simply
|
|
# return that element
|
|
element = group.getSubObject(subname,1)
|
|
if not isTypeOf(element,AsmElement):
|
|
raise RuntimeError('Invalid element reference {}.{}'.format(
|
|
group.Name,subname))
|
|
return element
|
|
|
|
if isTypeOf(group,AsmConstraintGroup):
|
|
# if the selected object is an element link of a constraint of the
|
|
# current assembly, then try to import its linked element if it is
|
|
# not already imported
|
|
link = group.getSubObject(subname,1)
|
|
if not isTypeOf(link,AsmElementLink):
|
|
raise RuntimeError('Invalid element link {}.{}'.format(
|
|
group.Name,subname))
|
|
ref = link.LinkedObject
|
|
if not isinstance(ref,tuple):
|
|
raise RuntimeError('Invalid link reference {}.{}'.format(
|
|
group.Name,subname))
|
|
if ref[1][0]=='$':
|
|
# this means the element is in the current assembly already
|
|
element = link.getLinkedObject(False)
|
|
if not isTypeOf(element,AsmElement):
|
|
raise RuntimeError('broken element link {}.{}'.format(
|
|
group.Name,subname))
|
|
return element
|
|
|
|
subname = ref[1]
|
|
group = group.getAssembly().getPartGroup()
|
|
|
|
elif isTypeOf(group,AsmPartGroup):
|
|
# If the selection come from the part group, first check for any
|
|
# intermediate child assembly
|
|
ret = Assembly.find(group,subname)
|
|
if not ret:
|
|
# If no child assembly in 'subname', simply assign the link as
|
|
# it is, after making sure it is referencing an sub-element
|
|
if not utils.isElement((group,subname)):
|
|
raise RuntimeError( 'Element must reference a geometry '
|
|
'element {} {}'.format(objName(group),subname))
|
|
else:
|
|
# In case there are intermediate assembly inside subname, we'll
|
|
# recursively export the element in child assemblies first, and
|
|
# then import that element to the current assembly.
|
|
sel = AsmElement.Selection(Element=None,
|
|
Group=ret.Object, Subname=ret.Subname)
|
|
element = AsmElement.make(sel)
|
|
|
|
# now generate the subname reference
|
|
|
|
# This give us reference to child assembly's immediate child
|
|
# without trailing dot.
|
|
prefix = subname[:len(subname)-len(ret.Subname)-1]
|
|
|
|
# Pop the immediate child name, and replace it with child
|
|
# assembly's element group name
|
|
prefix = prefix[:prefix.rfind('.')+1] + \
|
|
resolveAssembly(ret.Assembly).getElementGroup().Name
|
|
|
|
subname = '{}.${}.'.format(prefix,element.Label)
|
|
|
|
else:
|
|
raise RuntimeError('Invalid selection {}.{}'.format(
|
|
group.Name,subname))
|
|
|
|
element = selection.Element
|
|
|
|
sobj = group.getSubObject(subname,1)
|
|
if not sobj:
|
|
raise RuntimeError('invalid link {}.{}'.format(
|
|
objName(group),subname))
|
|
|
|
# With the new SketchExport, we don't need special treatment of sketch,
|
|
# AsmSketchElement is only kept for backward compatibility.
|
|
isSketch = False
|
|
# isSketch = not isTypeOf(sobj,AsmElement) and sobj and \
|
|
# sobj.getLinkedObject(True).isDerivedFrom('Sketcher::SketchObject')
|
|
|
|
try:
|
|
if undo:
|
|
FreeCAD.setActiveTransaction('Assembly change element' \
|
|
if element else 'Assembly create element')
|
|
|
|
elements = group.Proxy.getAssembly().getElementGroup()
|
|
oldLabel = None
|
|
idx = -1
|
|
if element and isSketch!=isinstance(element,AsmElementSketch):
|
|
# Check if element type is changed. We need special treatment
|
|
# for element from sketch object
|
|
for i,e in enumerate(elements.Group):
|
|
if e == element:
|
|
idx = i
|
|
oldLabel = element.Label
|
|
break
|
|
element = None
|
|
|
|
if not element:
|
|
# try to search the element group for an existing element
|
|
for e in elements.Group:
|
|
if not e.Offset.isIdentity():
|
|
continue
|
|
sub = logger.catch('',e.Proxy.getSubName)
|
|
if sub == subname:
|
|
return e
|
|
if isSketch:
|
|
element = AsmElementSketch.create(name,elements)
|
|
else:
|
|
element = AsmElement.create(name,elements)
|
|
if oldLabel:
|
|
element.Label = oldLabel
|
|
elements.setLink({idx:element})
|
|
elements.setElementVisible(element.Name,False)
|
|
element.Proxy._initializing = False
|
|
elements.cacheChildLabel()
|
|
element.setLink(group,subname)
|
|
element.recompute()
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction()
|
|
except Exception:
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction(True)
|
|
raise
|
|
return element
|
|
|
|
|
|
class ViewProviderAsmElement(ViewProviderAsmOnTop):
|
|
def __init__(self,vobj):
|
|
if hasattr(vobj,'OverrideMaterial'):
|
|
vobj.OverrideMaterial = True
|
|
vobj.ShapeMaterial.DiffuseColor = \
|
|
vobj.ShapeMaterial.EmissiveColor = self.getDefaultColor()
|
|
vobj.DrawStyle = 1
|
|
else:
|
|
vobj.DiffuseColor = \
|
|
vobj.LineColor = \
|
|
vobj.PointColor = self.getDefaultColor()
|
|
vobj.LineWidth = 4
|
|
vobj.PointSize = 4
|
|
super(ViewProviderAsmElement,self).__init__(vobj)
|
|
|
|
def attach(self,vobj):
|
|
super(ViewProviderAsmElement,self).attach(vobj)
|
|
if gui.AsmCmdManager.AutoElementVis:
|
|
vobj.OnTopWhenSelected = 2
|
|
|
|
def getDefaultColor(self):
|
|
return (60.0/255.0,1.0,1.0)
|
|
|
|
def canDropObjectEx(self,_obj,owner,_subname,elements):
|
|
if not elements:
|
|
return False
|
|
proxy = self.ViewObject.Object.Proxy
|
|
return proxy.getAssembly().getPartGroup()==owner
|
|
|
|
def dropObjectEx(self,vobj,_obj,owner,subname,elements):
|
|
if not elements:
|
|
return
|
|
for element in elements:
|
|
AsmElement.make(AsmElement.Selection(Element=vobj.Object,
|
|
Group=owner, Subname=subname+element),undo=True)
|
|
|
|
def updateData(self,obj,prop):
|
|
if not hasattr(self,'ViewObject') or FreeCAD.isRestoring():
|
|
return
|
|
if prop == 'Shape':
|
|
vobj = obj.ViewObject
|
|
if obj.Shape.isNull():
|
|
vobj.ChildViewProvider = ''
|
|
elif not vobj.ChildViewProvider:
|
|
vobj.ChildViewProvider = 'PartGui::ViewProviderPartExt'
|
|
vobj.DefaultMode = 1
|
|
|
|
def onFinishRestoring(self):
|
|
vobj = self.ViewObject
|
|
if getattr(vobj,'ChildViewProvider',None):
|
|
vobj.DefaultMode = 1
|
|
|
|
|
|
class AsmElementSketch(AsmElement):
|
|
def __init__(self,obj,parent):
|
|
super(AsmElementSketch,self).__init__(parent)
|
|
obj.Proxy = self
|
|
self.attach(obj)
|
|
|
|
def linkSetup(self,obj):
|
|
super(AsmElementSketch,self).linkSetup(obj)
|
|
obj.setPropertyStatus('Placement',('Hidden','-Immutable'))
|
|
|
|
@classmethod
|
|
def create(cls,name,parent):
|
|
element = parent.Document.addObject("Part::FeaturePython", name)
|
|
cls(element,parent)
|
|
ViewProviderAsmElementSketch(element.ViewObject)
|
|
return element
|
|
|
|
def execute(self,obj):
|
|
shape = utils.getElementShape(obj.LinkedObject)
|
|
obj.Placement = shape.Placement
|
|
obj.Shape = shape
|
|
return False
|
|
|
|
def getSubObject(self,obj,subname,retType,mat,transform,depth):
|
|
link = obj.LinkedObject
|
|
if isinstance(link,tuple) and \
|
|
(not subname or subname==link[1]):
|
|
ret = link[0].getSubObject(subname,retType,mat,transform,depth+1)
|
|
if ret == link[0]:
|
|
ret = obj
|
|
elif isinstance(ret,(tuple,list)):
|
|
ret = list(ret)
|
|
ret[0] = obj
|
|
return ret
|
|
|
|
def freeze(self):
|
|
pass
|
|
|
|
|
|
class ViewProviderAsmElementSketch(ViewProviderAsmElement):
|
|
def getIcon(self):
|
|
return ":/icons/Sketcher_Sketch.svg"
|
|
|
|
def getDetail(self,_name):
|
|
pass
|
|
|
|
def getElement(self,_det):
|
|
link = self.ViewObject.Object.LinkedObject
|
|
if isinstance(link,tuple):
|
|
subs = link[1].split('.')
|
|
if subs:
|
|
return subs[-1]
|
|
return ''
|
|
|
|
def updateData(self,obj,prop):
|
|
_ = obj
|
|
_ = prop
|
|
|
|
|
|
ElementInfo = namedtuple('AsmElementInfo', ('Parent','SubnameRef','Part',
|
|
'PartName','Placement','Object','Subname','Shape','PlacementOffset'))
|
|
|
|
def getElementInfo(parent,subname,checkPlacement=False,shape=None,offset=None):
|
|
'''Return a named tuple containing the part object element information
|
|
|
|
Parameters:
|
|
|
|
parent: the parent document object, either an assembly, or a part group
|
|
|
|
subname: subname reference to the part element (i.e. edge, face, vertex)
|
|
|
|
shape: caller can pass in a pre-obtained element shape. The shape is
|
|
assumed ot be in the assembly coordinate space. This function will then
|
|
transform the shape into the its owner part's coordinate space. If
|
|
'shape' is not given, then the output shape will be obtained through
|
|
'parent' and 'subname'
|
|
|
|
offset: an optional offset in the element shape's coordinate space
|
|
|
|
Return a named tuple with the following fields:
|
|
|
|
Parent: set to the input parent object
|
|
|
|
SubnameRef: set to the input subname reference
|
|
|
|
Part: either the part object, or a tuple(obj, idx) to refer to an element in
|
|
an link array,
|
|
|
|
PartName: a string name for the part
|
|
|
|
Placement: the placement of the part
|
|
|
|
Object: the object that owns the element. In case 'Part' is an assembly, the
|
|
element owner will always be some (grand)child of the 'Part'
|
|
|
|
Subname: the subname reference to the element owner object. The reference is
|
|
realtive to the 'Part', i.e. Object = Part.getSubObject(subname), or if
|
|
'Part' is a tuple, Object = Part[0].getSubObject(str(Part[1]) + '.' +
|
|
subname)
|
|
|
|
Shape: Part.Shape of the linked element. The shape's placement is relative
|
|
to the owner Part.
|
|
|
|
PlacementOffset: if 'offset' is given, then this field holds the necessary
|
|
placement offset in assembly coordinate space to achieve an equivalant
|
|
'offset', which is in element shape's coordinate space.
|
|
'''
|
|
|
|
subnameRef = subname
|
|
|
|
names = subname.split('.')
|
|
if isTypeOf(parent,Assembly,True):
|
|
partGroup = None
|
|
child = parent.getSubObject(names[0]+'.',1)
|
|
if isTypeOf(child,(AsmElementGroup,AsmConstraintGroup)):
|
|
child = parent.getSubObject(subname,1)
|
|
if not child:
|
|
raise RuntimeError('Invalid sub-object {}, {}'.format(
|
|
objName(parent), subname))
|
|
if not isTypeOf(child,(AsmElement,AsmElementLink)):
|
|
raise RuntimeError('{} cannot be moved'.format(objName(child)))
|
|
subname = child.Proxy.getElementSubname()
|
|
names = subname.split('.')
|
|
partGroup = parent.Proxy.getPartGroup()
|
|
|
|
elif isTypeOf(child,AsmPartGroup):
|
|
partGroup = child
|
|
names = names[1:]
|
|
subname = '.'.join(names)
|
|
|
|
if not partGroup:
|
|
raise RuntimeError('Invalid sub-object {}, {}'.format(
|
|
objName(parent), subname))
|
|
|
|
elif isTypeOf(parent,AsmPartGroup):
|
|
partGroup = parent
|
|
else:
|
|
raise RuntimeError('{} is not Assembly or PartGroup'.format(
|
|
objName(parent)))
|
|
|
|
part = partGroup.getSubObject(names[0]+'.',1)
|
|
if not part:
|
|
raise RuntimeError('Invalid sub-object {}, {}'.format(
|
|
objName(parent), subnameRef))
|
|
|
|
transformShape = True if shape else False
|
|
|
|
# For storing the placement of the movable part
|
|
pla = None
|
|
# For storing the actual geometry object of the part, in case 'part' is
|
|
# a link
|
|
obj = None
|
|
|
|
if not isTypeOf(part,Assembly,True):
|
|
getter = getattr(part.getLinkedObject(True),
|
|
'getLinkExtProperty',None)
|
|
|
|
# special treatment of link array (i.e. when ElementCount!=0), we
|
|
# allow the array element to be moveable by the solver
|
|
if getter and getter('ElementCount'):
|
|
|
|
# store both the part (i.e. the link array), and the array
|
|
# element object
|
|
part = (part,part.getSubObject(names[1]+'.',1))
|
|
|
|
# trim the subname to be after the array element
|
|
sub = '.'.join(names[2:])
|
|
|
|
# There are two states of an link array.
|
|
if getter('ElementList'):
|
|
# a) The elements are expanded as individual objects, i.e
|
|
# when ElementList has members, then the moveable Placement
|
|
# is a property of the array element. So we obtain the shape
|
|
# before 'Placement' by setting 'transform' set to False.
|
|
if not shape:
|
|
shape=part[1].getSubObject(sub,transform=False)
|
|
pla = part[1].Placement
|
|
obj = part[0].getLinkedObject(False)
|
|
partName = part[1].Name
|
|
part = part[1]
|
|
else:
|
|
# b) The elements are collapsed. Then the moveable Placement
|
|
# is stored inside link object's PlacementList property. So,
|
|
# the shape obtained below is already before 'Placement',
|
|
# i.e. no need to set 'transform' to False.
|
|
if not shape:
|
|
shape=part[1].getSubObject(sub)
|
|
obj = part[1]
|
|
try:
|
|
idx = names[1].split('_i')[-1]
|
|
# we store the array index instead, in order to modified
|
|
# Placement later when the solver is done. Also because
|
|
# that when the elements are collapsed, there is really
|
|
# no element object here.
|
|
part = (part[0],int(idx),part[1])
|
|
pla = part[0].PlacementList[idx]
|
|
except ValueError:
|
|
raise RuntimeError('invalid array subname of element {}: '
|
|
'{}'.format(objName(parent),subnameRef))
|
|
|
|
partName = '{}.{}.'.format(part[0].Name,idx)
|
|
|
|
subname = sub
|
|
|
|
if not obj:
|
|
# Here means, either the 'part' is an assembly or it is a non array
|
|
# object. We trim the subname reference to be relative to the part
|
|
# object. And obtain the shape before part's Placement by setting
|
|
# 'transform' to False
|
|
if checkPlacement and not hasattr(part,'Placement'):
|
|
raise RuntimeError('part has no placement')
|
|
subname = '.'.join(names[1:])
|
|
if not shape:
|
|
shape = utils.getElementShape((part,subname))
|
|
if not shape:
|
|
raise RuntimeError('cannot get geometry element from {}.{}'.format(
|
|
part.Name,subname))
|
|
pla = getattr(part,'Placement',FreeCAD.Placement())
|
|
obj = part.getLinkedObject(False)
|
|
partName = part.Name
|
|
|
|
if transformShape:
|
|
shape.transformShape(pla.toMatrix().inverse())
|
|
|
|
if not offset or offset.isIdentity():
|
|
plaOffset = FreeCAD.Placement()
|
|
else:
|
|
mat = utils.getElementPlacement(shape).toMatrix()
|
|
shape.transformShape(mat*offset.toMatrix()*mat.inverse())
|
|
mat = pla.toMatrix()*mat
|
|
plaOffset = FreeCAD.Placement(mat*offset.toMatrix()*mat.inverse())
|
|
|
|
return ElementInfo(Parent = parent,
|
|
SubnameRef = subnameRef,
|
|
Part = part,
|
|
PartName = partName,
|
|
Placement = pla.copy(),
|
|
Object = obj,
|
|
Subname = subname,
|
|
Shape = shape,
|
|
PlacementOffset = plaOffset)
|
|
|
|
|
|
class AsmElementLink(AsmBase):
|
|
def __init__(self,parent):
|
|
super(AsmElementLink,self).__init__()
|
|
self.info = None
|
|
self.parent = getProxy(parent,AsmConstraint)
|
|
|
|
def linkSetup(self,obj):
|
|
super(AsmElementLink,self).linkSetup(obj)
|
|
obj.configLinkProperty('LinkedObject')
|
|
obj.setPropertyStatus('LinkedObject','ReadOnly')
|
|
self.info = None
|
|
|
|
def attach(self,obj):
|
|
obj.addProperty("App::PropertyXLink","LinkedObject"," Link",'')
|
|
super(AsmElementLink,self).attach(obj)
|
|
|
|
def canLinkProperties(self,_obj):
|
|
return False
|
|
|
|
def execute(self,_obj):
|
|
self.info = None
|
|
return False
|
|
|
|
def onChanged(self,_obj,prop):
|
|
if not getattr(self,'parent',None) or FreeCAD.isRestoring():
|
|
return
|
|
if prop not in _IgnoredProperties and \
|
|
not Constraint.isDisabled(self.parent.Object):
|
|
Assembly.autoSolve()
|
|
|
|
def getAssembly(self):
|
|
return self.parent.parent.parent
|
|
|
|
def getElementSubname(self):
|
|
'Resolve element link subname'
|
|
|
|
# AsmElementLink is used by constraint to link to a geometry link. It
|
|
# does so by indirectly linking to an AsmElement object belonging to
|
|
# the same parent assembly. AsmElement is also a link, which again
|
|
# links to another AsmElement of a child assembly or the actual
|
|
# geometry element of a child feature. This function is for resolving
|
|
# the AsmElementLink's subname reference to the actual part object
|
|
# subname reference relative to the parent assembly's part group
|
|
|
|
linked = self.Object.getLinkedObject(False)
|
|
if not linked or linked == self.Object:
|
|
raise RuntimeError('Element link broken')
|
|
element = getProxy(linked,AsmElement)
|
|
assembly = element.getAssembly()
|
|
if assembly == self.getAssembly():
|
|
return element.getElementSubname()
|
|
|
|
# The reference stored inside this ElementLink. We need the sub-assembly
|
|
# name, which is the name before the first dot. This name may be
|
|
# different from the actual assembly object's name, in case where the
|
|
# assembly is accessed through a link. And the sub-assembly may be
|
|
# inside a link array, which we don't know for sure. But we do know that
|
|
# the last two names are element group and element label. So just pop
|
|
# two names.
|
|
ref = self.Object.LinkedObject[1]
|
|
prefix = ref[0:ref.rfind('.',0,ref.rfind('.',0,-1))]
|
|
return '{}.{}.{}'.format(prefix, assembly.getPartGroup().Name,
|
|
element.getElementSubname())
|
|
|
|
def setLink(self,owner,subname,checkOnly=False):
|
|
# check if there is any sub-assembly in the reference
|
|
ret = Assembly.find(owner,subname)
|
|
if not ret:
|
|
# if not, add/get an element in our own element group
|
|
sel = AsmElement.Selection(Element=None, Group=owner,
|
|
Subname=subname)
|
|
element = AsmElement.make(sel)
|
|
owner = element.Proxy.parent.Object
|
|
subname = '${}.'.format(element.Label)
|
|
else:
|
|
# if so, add/get an element from the sub-assembly
|
|
sel = AsmElement.Selection(Element=None, Group=ret.Object,
|
|
Subname=ret.Subname)
|
|
element = AsmElement.make(sel)
|
|
owner = owner.Proxy.getAssembly().getPartGroup()
|
|
|
|
# This give us reference to child assembly's immediate child
|
|
# without trailing dot.
|
|
prefix = subname[:len(subname)-len(ret.Subname)-1]
|
|
|
|
# Pop the immediate child name, and replace it with child
|
|
# assembly's element group name
|
|
prefix = prefix[:prefix.rfind('.')+1] + \
|
|
resolveAssembly(ret.Assembly).getElementGroup().Name
|
|
|
|
subname = '{}.${}.'.format(prefix, element.Label)
|
|
|
|
for sibling in self.parent.Object.Group:
|
|
if sibling == self.Object:
|
|
continue
|
|
linked = sibling.LinkedObject
|
|
if isinstance(linked,tuple) and \
|
|
linked[0]==owner and linked[1]==subname:
|
|
raise RuntimeError('duplicate element link {} in constraint '
|
|
'{}'.format(objName(sibling),objName(self.parent.Object)))
|
|
if not checkOnly:
|
|
self.Object.setLink(owner,subname)
|
|
|
|
def getInfo(self,refresh=False):
|
|
if not refresh:
|
|
ret = getattr(self,'info',None)
|
|
if ret:
|
|
return ret
|
|
self.info = None
|
|
obj = getattr(self,'Object',None)
|
|
if not obj:
|
|
return
|
|
self.info = getElementInfo(self.getAssembly().getPartGroup(),
|
|
self.getElementSubname(),shape=obj.getSubObject(''))
|
|
if hasattr(obj,'Shape') and self.getAssembly().Freeze:
|
|
# make a compound to contain the shape's transformation
|
|
obj.Shape = Part.makeCompound(self.info.Shape)
|
|
return self.info
|
|
|
|
@staticmethod
|
|
def setPlacement(part,pla):
|
|
'''
|
|
called by solver after solving to adjust the placement.
|
|
|
|
part: obtained by AsmConstraint.getInfo().Part
|
|
pla: the new placement
|
|
'''
|
|
if isinstance(part,tuple):
|
|
if isinstance(part[1],int):
|
|
part[0].PlacementList = {part[1]:pla}
|
|
else:
|
|
part[1].Placement = pla
|
|
else:
|
|
part.Placement = pla
|
|
|
|
MakeInfo = namedtuple('AsmElementLinkMakeInfo',
|
|
('Constraint','Owner','Subname'))
|
|
|
|
@staticmethod
|
|
def make(info,name='ElementLink'):
|
|
link = info.Constraint.Document.addObject("App::FeaturePython",
|
|
name,AsmElementLink(info.Constraint),None,True)
|
|
ViewProviderAsmElementLink(link.ViewObject)
|
|
info.Constraint.setLink({-1:link})
|
|
link.Proxy.setLink(info.Owner,info.Subname)
|
|
if not gui.AsmCmdManager.AutoElementVis:
|
|
info.Constraint.setElementVisible(link.Name,False)
|
|
return link
|
|
|
|
|
|
def setPlacement(part,pla):
|
|
AsmElementLink.setPlacement(part,pla)
|
|
|
|
|
|
class ViewProviderAsmElementLink(ViewProviderAsmOnTop):
|
|
def __init__(self,vobj):
|
|
vobj.OverrideMaterial = True
|
|
vobj.ShapeMaterial.DiffuseColor = self.getDefaultColor()
|
|
vobj.ShapeMaterial.EmissiveColor = self.getDefaultColor()
|
|
super(ViewProviderAsmElementLink,self).__init__(vobj)
|
|
|
|
def attach(self,vobj):
|
|
super(ViewProviderAsmElementLink,self).attach(vobj)
|
|
if gui.AsmCmdManager.AutoElementVis:
|
|
vobj.OnTopWhenSelected = 2
|
|
|
|
def getDefaultColor(self):
|
|
return (1.0,60.0/255.0,60.0/255.0)
|
|
|
|
def doubleClicked(self,_vobj):
|
|
from . import mover
|
|
return mover.movePart()
|
|
|
|
def canDropObjectEx(self,_obj,owner,subname,elements):
|
|
if not elements:
|
|
elements = ['']
|
|
obj = self.ViewObject.Object
|
|
msg = 'Cannot drop to AsmLink {}'.format(objName(obj))
|
|
for element in elements:
|
|
if not logger.catchTrace(msg, obj.Proxy.setLink,
|
|
owner,subname+element,True):
|
|
return False
|
|
return True
|
|
|
|
def dropObjectEx(self,vobj,_obj,owner,subname,elements):
|
|
if not elements:
|
|
elements = ['']
|
|
for element in elements:
|
|
vobj.Object.Proxy.setLink(owner,subname+element)
|
|
|
|
|
|
class AsmConstraint(AsmGroup):
|
|
|
|
def __init__(self,parent):
|
|
self._initializing = True
|
|
self.elements = None
|
|
self.parent = getProxy(parent,AsmConstraintGroup)
|
|
super(AsmConstraint,self).__init__()
|
|
|
|
def getAssembly(self):
|
|
return self.parent.parent
|
|
|
|
def checkSupport(self):
|
|
# this function maybe called during document restore, hence the
|
|
# extensive check below
|
|
obj = getattr(self,'Object',None)
|
|
if not obj:
|
|
return
|
|
if Constraint.isDisabled(obj):
|
|
return
|
|
parent = getattr(self,'parent',None)
|
|
if not parent:
|
|
return
|
|
parent = getattr(parent,'parent',None)
|
|
if not parent:
|
|
return
|
|
assembly = getattr(parent,'Object',None)
|
|
if not assembly or \
|
|
System.isConstraintSupported(assembly,Constraint.getTypeName(obj)):
|
|
return
|
|
raise RuntimeError('Constraint type "{}" is not supported by '
|
|
'solver "{}"'.format(Constraint.getTypeName(obj),
|
|
System.getTypeName(assembly)))
|
|
|
|
def onChanged(self,obj,prop):
|
|
if prop not in _IgnoredProperties:
|
|
Constraint.onChanged(obj,prop)
|
|
Assembly.autoSolve()
|
|
|
|
def linkSetup(self,obj):
|
|
self.elements = None
|
|
super(AsmConstraint,self).linkSetup(obj)
|
|
group = obj.Group
|
|
for o in group:
|
|
getProxy(o,AsmElementLink).parent = self
|
|
if gui.AsmCmdManager.AutoElementVis:
|
|
obj.setPropertyStatus('VisibilityList','-Immutable')
|
|
obj.VisibilityList = [False]*len(group)
|
|
obj.setPropertyStatus('VisibilityList','Immutable')
|
|
obj.setPropertyStatus('VisibilityList','NoModify')
|
|
Constraint.attach(obj)
|
|
obj.recompute()
|
|
|
|
def execute(self,_obj):
|
|
if not getattr(self,'_initializing',False) and\
|
|
getattr(self,'parent',None):
|
|
self.checkSupport()
|
|
self.getElements(True)
|
|
return False
|
|
|
|
def getElements(self,refresh=False):
|
|
if refresh:
|
|
self.elements = None
|
|
obj = getattr(self,'Object',None)
|
|
if not obj:
|
|
return
|
|
ret = getattr(self,'elements',None)
|
|
if ret or Constraint.isDisabled(obj):
|
|
return ret
|
|
elementInfo = []
|
|
elements = []
|
|
for o in obj.Group:
|
|
checkType(o,AsmElementLink)
|
|
info = o.Proxy.getInfo()
|
|
if not info:
|
|
return
|
|
elementInfo.append(info)
|
|
elements.append(o)
|
|
Constraint.check(obj,elementInfo,True)
|
|
self.elements = elements
|
|
return self.elements
|
|
|
|
def getElementsInfo(self):
|
|
return [ e.Proxy.getInfo() for e in self.getElements() ]
|
|
|
|
Selection = namedtuple('AsmConstraintSelection',
|
|
('SelObject','SelSubname','Assembly','Constraint','Elements'))
|
|
|
|
@staticmethod
|
|
def getSelection(typeid=0,sels=None):
|
|
'''
|
|
Parse Gui.Selection for making a constraint
|
|
|
|
The selected elements must all belong to the same immediate parent
|
|
assembly.
|
|
'''
|
|
if not sels:
|
|
sels = FreeCADGui.Selection.getSelectionEx('',False)
|
|
if not sels:
|
|
raise RuntimeError('no selection')
|
|
if len(sels)>1:
|
|
raise RuntimeError(
|
|
'The selections must have a common (grand)parent assembly')
|
|
sel = sels[0]
|
|
subs = sel.SubElementNames
|
|
if not subs:
|
|
subs = ['']
|
|
|
|
cstr = None
|
|
elements = []
|
|
elementInfo = []
|
|
assembly = None
|
|
selSubname = None
|
|
infos = []
|
|
# first pass, collect hierarchy information, and find active assemble to
|
|
# use, i.e. which assembly to constraint
|
|
for sub in subs:
|
|
sobj = sel.Object.getSubObject(sub,1)
|
|
if not sobj:
|
|
raise RuntimeError('Cannot find sub-object {}.{}'.format(
|
|
sel.Object.Name,sub))
|
|
ret = Assembly.find(sel.Object,sub,
|
|
recursive=True,relativeToChild=False,keepEmptyChild=True)
|
|
if not ret:
|
|
raise RuntimeError('Selection {}.{} is not from an '
|
|
'assembly'.format(sel.Object.Name,sub))
|
|
|
|
infos.append((sub,sobj,ret))
|
|
|
|
if isTypeOf(sobj,Assembly,True):
|
|
assembly = ret[-1].Assembly
|
|
if sub:
|
|
selSubname = sub
|
|
elif isTypeOf(sobj,(AsmConstraintGroup,AsmConstraint)):
|
|
assembly = ret[-1].Assembly
|
|
selSubname = sub[:-len(ret[-1].Subname)]
|
|
elif not assembly:
|
|
assembly = ret[0].Assembly
|
|
selSubname = sub[:-len(ret[0].Subname)]
|
|
|
|
# second pass, collect element information
|
|
for sub,sobj,ret in infos:
|
|
found = None
|
|
for r in ret:
|
|
if r.Assembly == assembly:
|
|
found = r
|
|
break
|
|
if not found:
|
|
raise RuntimeError('Selection {}.{} is not from the target '
|
|
'assembly {}'.format(
|
|
sel.Object.Name,sub,objName(assembly)))
|
|
|
|
if isTypeOf(sobj,Assembly,True) or \
|
|
isTypeOf(sobj,AsmConstraintGroup):
|
|
continue
|
|
|
|
if isTypeOf(sobj,AsmConstraint):
|
|
if cstr:
|
|
raise RuntimeError('more than one constraint selected')
|
|
cstr = sobj
|
|
continue
|
|
|
|
# because we call Assembly.find() above with relativeToChild=False,
|
|
# we shall adjust the element subname by popping the first '.'
|
|
sub = found.Subname
|
|
sub = sub[sub.index('.')+1:]
|
|
if sub[-1] == '.' and \
|
|
not isTypeOf(sobj,(AsmElement,AsmElementLink)):
|
|
# Too bad, its a full selection, let's guess the sub-element
|
|
if not utils.isElement((found.Object,sub)):
|
|
raise RuntimeError('no sub-element (face, edge, vertex) in '
|
|
'{}.{}'.format(found.Object.Name,sub))
|
|
subElement = utils.deduceSelectedElement(found.Object,sub)
|
|
if subElement:
|
|
sub += subElement
|
|
|
|
elements.append((found.Object,sub))
|
|
|
|
elementInfo.append(getElementInfo(
|
|
assembly,found.Object.Name+'.'+sub))
|
|
|
|
if not Constraint.isDisabled(cstr):
|
|
if cstr:
|
|
typeid = Constraint.getTypeID(cstr)
|
|
check = []
|
|
for o in cstr.Group:
|
|
check.append(o.Proxy.getInfo())
|
|
elementInfo = check + elementInfo
|
|
|
|
Constraint.check(typeid,elementInfo)
|
|
|
|
return AsmConstraint.Selection(SelObject=sel.Object,
|
|
SelSubname=selSubname,
|
|
Assembly = assembly,
|
|
Constraint = cstr,
|
|
Elements = elements)
|
|
|
|
@staticmethod
|
|
def make(typeid,sel=None,name='Constraint',undo=True):
|
|
if not sel:
|
|
sel = AsmConstraint.getSelection(typeid)
|
|
if sel.Constraint:
|
|
if undo:
|
|
FreeCAD.setActiveTransaction('Assembly change constraint')
|
|
cstr = sel.Constraint
|
|
else:
|
|
if undo:
|
|
FreeCAD.setActiveTransaction('Assembly create constraint')
|
|
constraints = sel.Assembly.Proxy.getConstraintGroup()
|
|
cstr = constraints.Document.addObject("App::FeaturePython",
|
|
name,AsmConstraint(constraints),None,True)
|
|
ViewProviderAsmConstraint(cstr.ViewObject)
|
|
constraints.setLink({-1:cstr})
|
|
Constraint.setTypeID(cstr,typeid)
|
|
cstr.Label = Constraint.getTypeName(cstr)
|
|
|
|
try:
|
|
for e in sel.Elements:
|
|
AsmElementLink.make(AsmElementLink.MakeInfo(cstr,*e))
|
|
logger.catchDebug('init constraint', Constraint.init,cstr)
|
|
cstr.Proxy._initializing = False
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction()
|
|
undo = False
|
|
|
|
if sel.SelObject:
|
|
FreeCADGui.Selection.clearSelection()
|
|
if sel.SelSubname:
|
|
subname = sel.SelSubname
|
|
else:
|
|
subname = ''
|
|
subname += sel.Assembly.Proxy.getConstraintGroup().Name + \
|
|
'.' + cstr.Name + '.'
|
|
FreeCADGui.Selection.addSelection(sel.SelObject,subname)
|
|
FreeCADGui.runCommand('Std_TreeSelection')
|
|
return cstr
|
|
|
|
except Exception:
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction(True)
|
|
raise
|
|
|
|
|
|
class ViewProviderAsmConstraint(ViewProviderAsmGroup):
|
|
def attach(self,vobj):
|
|
super(ViewProviderAsmConstraint,self).attach(vobj)
|
|
if gui.AsmCmdManager.AutoElementVis:
|
|
vobj.OnTopWhenSelected = 2
|
|
|
|
def getIcon(self):
|
|
return Constraint.getIcon(self.ViewObject.Object)
|
|
|
|
def _getSelection(self,owner,subname,elements):
|
|
if not owner:
|
|
raise RuntimeError('no owner')
|
|
parent = getattr(owner.Proxy,'parent',None)
|
|
if isinstance(parent,AsmConstraintGroup):
|
|
# This can happen when we are dropping another element link from the
|
|
# same constraint group, in which case, 'owner' here will be the
|
|
# parent constraint of the dropping element link
|
|
subname = owner.Name + '.' + subname
|
|
owner = parent.Object
|
|
parent = parent.parent # ascend to the parent assembly
|
|
if not isinstance(parent,Assembly):
|
|
raise RuntimeError('not from the same assembly')
|
|
subname = owner.Name + '.' + subname
|
|
obj = self.ViewObject.Object
|
|
mysub = parent.getConstraintGroup().Name + '.' + obj.Name + '.'
|
|
sel = []
|
|
if not elements:
|
|
elements = ['']
|
|
elements = [subname+element for element in elements]
|
|
elements.append(mysub)
|
|
sel = [Selection(Object=parent.Object,SubElementNames=elements)]
|
|
typeid = Constraint.getTypeID(obj)
|
|
return AsmConstraint.getSelection(typeid,sel)
|
|
|
|
def canDropObjectEx(self,_obj,owner,subname,elements):
|
|
cstr = self.ViewObject.Object
|
|
if logger.catchTrace('Cannot drop to AsmConstraint '
|
|
'{}'.format(cstr),self._getSelection,owner,subname,elements):
|
|
return True
|
|
return False
|
|
|
|
def dropObjectEx(self,_vobj,_obj,owner,subname,elements):
|
|
sel = self._getSelection(owner,subname,elements)
|
|
cstr = self.ViewObject.Object
|
|
typeid = Constraint.getTypeID(cstr)
|
|
sel = AsmConstraint.Selection(SelObject=None,
|
|
SelSubname=None,
|
|
Assembly=sel.Assembly,
|
|
Constraint=cstr,
|
|
Elements=sel.Elements)
|
|
AsmConstraint.make(typeid,sel,undo=False)
|
|
|
|
|
|
class AsmConstraintGroup(AsmGroup):
|
|
def __init__(self,parent):
|
|
self.parent = getProxy(parent,Assembly)
|
|
super(AsmConstraintGroup,self).__init__()
|
|
|
|
def getAssembly(self):
|
|
return self.parent
|
|
|
|
def canLoadPartial(self,_obj):
|
|
return 2 if self.getAssembly().frozen else 0
|
|
|
|
def linkSetup(self,obj):
|
|
super(AsmConstraintGroup,self).linkSetup(obj)
|
|
for o in obj.Group:
|
|
cstr = getProxy(o,AsmConstraint)
|
|
if cstr:
|
|
cstr.parent = self
|
|
obj.recompute()
|
|
|
|
@staticmethod
|
|
def make(parent,name='Constraints'):
|
|
obj = parent.Document.addObject("App::FeaturePython",name,
|
|
AsmConstraintGroup(parent),None,True)
|
|
ViewProviderAsmConstraintGroup(obj.ViewObject)
|
|
obj.purgeTouched()
|
|
return obj
|
|
|
|
|
|
class ViewProviderAsmConstraintGroup(ViewProviderAsmGroup):
|
|
_iconName = 'Assembly_Assembly_Constraints_Tree.svg'
|
|
|
|
def canDropObjects(self):
|
|
return False
|
|
|
|
def onDelete(self,_obj,_subs):
|
|
return False
|
|
|
|
|
|
class AsmElementGroup(AsmGroup):
|
|
def __init__(self,parent):
|
|
self.parent = getProxy(parent,Assembly)
|
|
super(AsmElementGroup,self).__init__()
|
|
|
|
def linkSetup(self,obj):
|
|
super(AsmElementGroup,self).linkSetup(obj)
|
|
for o in obj.Group:
|
|
getProxy(o,AsmElement).parent = self
|
|
obj.cacheChildLabel()
|
|
if gui.AsmCmdManager.AutoElementVis:
|
|
obj.setPropertyStatus('VisibilityList','NoModify')
|
|
|
|
def getAssembly(self):
|
|
return self.parent
|
|
|
|
def onChildLabelChange(self,obj,label):
|
|
names = set()
|
|
for o in self.Object.Group:
|
|
if o != obj:
|
|
names.add(o.Name)
|
|
if label not in names:
|
|
return
|
|
for i,c in enumerate(reversed(label)):
|
|
if not c.isdigit():
|
|
if i:
|
|
label = label[:-i]
|
|
break;
|
|
i=0
|
|
while True:
|
|
i=i+1;
|
|
newLabel = '{}{03d}'.format(label,i);
|
|
if newLabel!=obj.Label and newLabel not in names:
|
|
return newLabel
|
|
|
|
@staticmethod
|
|
def make(parent,name='Elements'):
|
|
obj = parent.Document.addObject("App::FeaturePython",name,
|
|
AsmElementGroup(parent),None,True)
|
|
ViewProviderAsmElementGroup(obj.ViewObject)
|
|
obj.purgeTouched()
|
|
return obj
|
|
|
|
|
|
class ViewProviderAsmElementGroup(ViewProviderAsmGroup):
|
|
_iconName = 'Assembly_Assembly_Element_Tree.svg'
|
|
|
|
def onDelete(self,_obj,_subs):
|
|
return False
|
|
|
|
def canDropObjectEx(self,_obj,owner,_subname,elements):
|
|
if not owner or not elements:
|
|
return False
|
|
proxy = self.ViewObject.Object.Proxy
|
|
return proxy.getAssembly().getPartGroup()==owner
|
|
|
|
def dropObjectEx(self,vobj,_obj,owner,subname,elements):
|
|
sels = FreeCADGui.Selection.getSelectionEx('*',False)
|
|
if len(sels)==1 and \
|
|
len(sels[0].SubElementNames)==1 and \
|
|
sels[0].Object.getSubObject(
|
|
sels[0].SubElementNames[0],1)==vobj.Object:
|
|
sel = sels[0]
|
|
else:
|
|
sel = None
|
|
FreeCADGui.Selection.clearSelection()
|
|
for element in elements:
|
|
obj = AsmElement.make(AsmElement.Selection(
|
|
Element=None, Group=owner, Subname=subname+element))
|
|
if obj and sel:
|
|
FreeCADGui.Selection.addSelection(sel.Object,
|
|
sel.SubElementNames[0]+obj.Name+'.')
|
|
|
|
|
|
BuildShapeNone = 'None'
|
|
BuildShapeCompound = 'Compound'
|
|
BuildShapeFuse = 'Fuse'
|
|
BuildShapeCut = 'Cut'
|
|
BuildShapeCommon = 'Common'
|
|
BuildShapeNames = (BuildShapeNone,BuildShapeCompound,
|
|
BuildShapeFuse,BuildShapeCut,BuildShapeCommon)
|
|
|
|
class Assembly(AsmGroup):
|
|
_Timer = QtCore.QTimer()
|
|
_PartMap = {} # maps part to assembly
|
|
_PartArrayMap = {} # maps array part to assembly
|
|
|
|
def __init__(self):
|
|
self.parts = set()
|
|
self.partArrays = set()
|
|
self.constraints = None
|
|
self.frozen = False
|
|
super(Assembly,self).__init__()
|
|
|
|
def allowDuplicateLabel(self,_obj):
|
|
return False
|
|
|
|
def getSubObjects(self,_obj,reason):
|
|
partGroup = self.getPartGroup()
|
|
return ['{}.{}'.format(partGroup.Name,name)
|
|
for name in partGroup.getSubObjects(reason)]
|
|
|
|
def _collectParts(self,oldParts,newParts,partMap):
|
|
for part in newParts:
|
|
try:
|
|
oldParts.remove(part)
|
|
except KeyError:
|
|
partMap[part] = self
|
|
for part in oldParts:
|
|
del partMap[part]
|
|
|
|
def execute(self,obj):
|
|
parts = set()
|
|
partArrays = set()
|
|
self.constraints = None
|
|
|
|
if not self.frozen:
|
|
self.buildShape()
|
|
System.touch(obj)
|
|
obj.ViewObject.Proxy.onExecute()
|
|
|
|
# collect the part objects of this assembly
|
|
for cstr in self.getConstraints():
|
|
for element in cstr.Proxy.getElements():
|
|
info = element.Proxy.getInfo()
|
|
if isinstance(info.Part,tuple):
|
|
partArrays.add(info.Part[0])
|
|
parts.add(info.Part[0])
|
|
else:
|
|
parts.add(info.Part)
|
|
|
|
# Update the global part object list for auto solving
|
|
#
|
|
# Assembly._PartMap is used to track normal part object for change in
|
|
# its 'Placement'
|
|
#
|
|
# Assembly._PartArrayMap is for tracking link array for change in its
|
|
# 'PlacementList'
|
|
|
|
self._collectParts(self.parts,parts,Assembly._PartMap)
|
|
self.parts = parts
|
|
self._collectParts(self.partArrays,partArrays,Assembly._PartArrayMap)
|
|
self.partArrays = partArrays
|
|
|
|
return False # return False to call LinkBaseExtension::execute()
|
|
|
|
@classmethod
|
|
def canAutoSolve(cls):
|
|
from . import solver
|
|
return gui.AsmCmdManager.AutoRecompute and \
|
|
not FreeCADGui.ActiveDocument.Transacting and \
|
|
not FreeCAD.isRestoring() and \
|
|
not solver.isBusy() and \
|
|
not ViewProviderAssembly.isBusy()
|
|
|
|
@classmethod
|
|
def checkPartChange(cls, obj, prop):
|
|
if not cls.canAutoSolve() or prop in _IgnoredProperties:
|
|
return
|
|
assembly = None
|
|
if prop == 'Placement':
|
|
partMap = cls._PartMap
|
|
assembly = partMap.get(obj,None)
|
|
elif prop == 'PlacementList':
|
|
partMap = cls._PartArrayMap
|
|
assembly = partMap.get(obj,None)
|
|
if assembly:
|
|
try:
|
|
# This will fail if assembly got deleted
|
|
assembly.Object.Name
|
|
except Exception:
|
|
del partMap[obj]
|
|
else:
|
|
cls.autoSolve(True)
|
|
|
|
@classmethod
|
|
def autoSolve(cls,force=False):
|
|
if force or cls.canAutoSolve():
|
|
if not cls._Timer.isSingleShot():
|
|
cls._Timer.setSingleShot(True)
|
|
cls._Timer.timeout.connect(Assembly.onSolverTimer)
|
|
logger.debug('auto solve scheduled',frame=1)
|
|
cls._Timer.start(300)
|
|
|
|
@classmethod
|
|
def cancelAutoSolve(cls):
|
|
cls._Timer.stop()
|
|
|
|
@classmethod
|
|
def onSolverTimer(cls):
|
|
if not cls.canAutoSolve():
|
|
return
|
|
ret = FreeCAD.getActiveTransaction()
|
|
# if ret:
|
|
# logger.debug('skip auto solve because of active transaction '
|
|
# '{}'.format(ret))
|
|
# return
|
|
from . import solver
|
|
if not ret:
|
|
FreeCAD.setActiveTransaction('Assembly auto recompute')
|
|
logger.catch('solver exception when auto recompute',
|
|
solver.solve, FreeCAD.ActiveDocument.Objects, True)
|
|
if not ret:
|
|
FreeCAD.closeActiveTransaction()
|
|
|
|
def onSolverChanged(self):
|
|
for obj in self.getConstraintGroup().Group:
|
|
# setup==True usually means we are restoring, so try to restore the
|
|
# non-touched state if possible, since recompute() below will touch
|
|
# the constraint object
|
|
touched = 'Touched' in obj.State
|
|
obj.recompute()
|
|
if not touched:
|
|
obj.purgeTouched()
|
|
|
|
def upgrade(self):
|
|
'Upgrade old assembly objects to the new version'
|
|
partGroup = self.getPartGroup()
|
|
if hasattr(partGroup,'Shape'):
|
|
return
|
|
partGroup.setPropertyStatus('GroupMode','-Immutable')
|
|
partGroup.GroupMode = 0 # prevent auto delete children
|
|
newPartGroup = AsmPartGroup.make(self.Object)
|
|
newPartGroup.Group = partGroup.Group
|
|
newPartGroup.VisibilityList = partGroup.VisibilityList
|
|
|
|
elementGroup = self.getElementGroup()
|
|
vis = elementGroup.VisibilityList
|
|
elements = []
|
|
old = elementGroup.Group
|
|
for element in old:
|
|
copy = AsmElement.create('Element',elementGroup)
|
|
link = element.LinkedObject
|
|
if isinstance(link,tuple):
|
|
copy.LinkedObject = (newPartGroup,link[1])
|
|
copy.Label = element.Label
|
|
copy.Proxy._initializing = False
|
|
elements.append(copy)
|
|
|
|
elementGroup.Group = elements
|
|
elementGroup.setPropertyStatus('VisibilityList','-Immutable')
|
|
elementGroup.VisibilityList = vis
|
|
elementGroup.cacheChildLabel()
|
|
|
|
for element in old:
|
|
old.Document.removeObject(old)
|
|
|
|
self.Object.setLink({2:newPartGroup})
|
|
partGroup.Document.removeObject(partGroup)
|
|
|
|
def buildShape(self):
|
|
obj = self.Object
|
|
partGroup = self.getPartGroup()
|
|
if not obj.Freeze and obj.BuildShape==BuildShapeNone:
|
|
obj.Shape = Part.Shape();
|
|
if hasattr(partGroup, 'Shape'):
|
|
partGroup.Shape = Part.Shape()
|
|
return
|
|
|
|
group = partGroup.Group
|
|
|
|
shapes = []
|
|
if obj.BuildShape == BuildShapeCompound:
|
|
for o in group:
|
|
if obj.isElementVisible(o.Name):
|
|
shape = Part.getShape(o)
|
|
if not shape.isNull():
|
|
shapes.append(shape)
|
|
else:
|
|
# first shape is always included regardless of its visibility
|
|
solids = Part.getShape(group[0]).Solids
|
|
if solids:
|
|
if len(solids)>1 and obj.BuildShape!=BuildShapeFuse:
|
|
shapes.append(solids[0].fuse(solids[1:]))
|
|
else:
|
|
shapes += solids
|
|
group = group[1:]
|
|
for o in group:
|
|
if obj.isElementVisible(o.Name):
|
|
shape = Part.getShape(o)
|
|
# in case the first part have solids, we only include
|
|
# subsequent part containing solid
|
|
if solids:
|
|
shapes += shape.Solids
|
|
else:
|
|
shapes += shape
|
|
if not shapes:
|
|
raise RuntimeError('No shape found in parts')
|
|
if len(shapes) == 1:
|
|
shape = shapes[0]
|
|
# make sure the 'shape' has identity transform to prevent it from
|
|
# messing up with assembly's or partGroup's Placement
|
|
if not shape.Placement.isIdentity():
|
|
shape = Part.makeCompound(shape)
|
|
elif obj.BuildShape == BuildShapeFuse:
|
|
shape = shapes[0].fuse(shapes[1:])
|
|
elif obj.BuildShape == BuildShapeCut:
|
|
shape = shapes[0].cut(shapes[1:])
|
|
elif obj.BuildShape == BuildShapeCommon:
|
|
shape = shapes[0].common(shapes[1:])
|
|
else:
|
|
shape = Part.makeCompound(shapes)
|
|
|
|
if obj.Freeze or obj.BuildShape!=BuildShapeCompound:
|
|
partGroup.Shape = shape
|
|
elif hasattr(partGroup,'Shape'):
|
|
partGroup.Shape = Part.Shape()
|
|
|
|
shape.Placement = obj.Placement
|
|
obj.Shape = shape
|
|
|
|
def attach(self, obj):
|
|
obj.addProperty("App::PropertyEnumeration","BuildShape","Base",'')
|
|
obj.BuildShape = BuildShapeNames
|
|
super(Assembly,self).attach(obj)
|
|
|
|
def linkSetup(self,obj):
|
|
self.parts = set()
|
|
self.partArrays = set()
|
|
obj.configLinkProperty('Placement')
|
|
if not hasattr(obj,'ColoredElements'):
|
|
obj.addProperty("App::PropertyLinkSubHidden",
|
|
"ColoredElements","Base",'')
|
|
obj.setPropertyStatus('ColoredElements',('Hidden','Immutable'))
|
|
if not hasattr(obj,'Freeze'):
|
|
obj.addProperty('App::PropertyBool','Freeze','Base','')
|
|
obj.configLinkProperty('ColoredElements')
|
|
super(Assembly,self).linkSetup(obj)
|
|
System.attach(obj)
|
|
|
|
# make sure all children are there, first constraint group, then element
|
|
# group, and finally part group. Call getPartGroup below will make sure
|
|
# all groups exist. The order of the group is important to make sure
|
|
# correct rendering and picking behavior
|
|
self.getPartGroup(True)
|
|
|
|
self.onChanged(obj,'BuildShape')
|
|
|
|
def onChanged(self, obj, prop):
|
|
if not getattr(self,'Object',None) or FreeCAD.isRestoring():
|
|
return
|
|
if prop == 'BuildShape':
|
|
self.buildShape()
|
|
return
|
|
if prop == 'Freeze':
|
|
if obj.Freeze == self.frozen:
|
|
return
|
|
self.upgrade()
|
|
for o in self.getElementGroup().Group:
|
|
self.freeze(o)
|
|
if obj.BuildShape==BuildShapeNone:
|
|
self.buildShape()
|
|
elif obj.Freeze:
|
|
self.getPartGroup().Shape = obj.Shape
|
|
else:
|
|
self.getPartGroup().Shape = Part.Shape()
|
|
return
|
|
if prop not in _IgnoredProperties:
|
|
System.onChanged(obj,prop)
|
|
Assembly.autoSolve()
|
|
|
|
def onDocumentRestored(self,obj):
|
|
super(Assembly,self).onDocumentRestored(obj)
|
|
partGroup = self.getPartGroup()
|
|
self.frozen = obj.Freeze
|
|
if self.frozen or hasattr(partGroup,'Shape'):
|
|
obj.Shape = partGroup.Shape
|
|
elif obj.Shape.isNull() and \
|
|
obj.BuildShape == BuildShapeCompound:
|
|
self.buildShape()
|
|
|
|
def getConstraintGroup(self, create=False):
|
|
obj = self.Object
|
|
if obj.Freeze:
|
|
return None
|
|
try:
|
|
ret = obj.Group[0]
|
|
checkType(ret,AsmConstraintGroup)
|
|
parent = getattr(ret.Proxy,'parent',None)
|
|
if not parent:
|
|
ret.Proxy.parent = self
|
|
elif parent!=self:
|
|
raise RuntimeError('invalid parent of constraint group '
|
|
'{}'.format(objName(ret)))
|
|
return ret
|
|
except IndexError:
|
|
if not create or obj.Group:
|
|
raise RuntimeError('Invalid assembly')
|
|
ret = AsmConstraintGroup.make(obj)
|
|
obj.setLink({0:ret})
|
|
return ret
|
|
|
|
def getConstraints(self,refresh=False):
|
|
if not refresh:
|
|
ret = getattr(self,'constraints',None)
|
|
if ret:
|
|
return ret
|
|
self.constraints = None
|
|
cstrGroup = self.getConstraintGroup()
|
|
if not cstrGroup:
|
|
return
|
|
ret = []
|
|
for o in cstrGroup.Group:
|
|
checkType(o,AsmConstraint)
|
|
if Constraint.isDisabled(o):
|
|
logger.debug('skip constraint {}'.format(cstrName(o)))
|
|
continue
|
|
if not System.isConstraintSupported(self.Object,
|
|
Constraint.getTypeName(o)):
|
|
logger.debug('skip unsupported constraint '
|
|
'{}'.format(cstrName(o)))
|
|
continue
|
|
ret.append(o)
|
|
self.constraints = ret
|
|
return self.constraints
|
|
|
|
def getElementGroup(self,create=False):
|
|
obj = self.Object
|
|
if create:
|
|
# make sure previous group exists
|
|
self.getConstraintGroup(True)
|
|
try:
|
|
ret = obj.Group[1]
|
|
checkType(ret,AsmElementGroup)
|
|
parent = getattr(ret.Proxy,'parent',None)
|
|
if not parent:
|
|
ret.Proxy.parent = self
|
|
elif parent!=self:
|
|
raise RuntimeError('invalid parent of element group '
|
|
'{}'.format(objName(ret)))
|
|
return ret
|
|
except IndexError:
|
|
if not create:
|
|
raise RuntimeError('Missing element group')
|
|
ret = AsmElementGroup.make(obj)
|
|
obj.setLink({1:ret})
|
|
return ret
|
|
|
|
def getPartGroup(self,create=False):
|
|
obj = self.Object
|
|
if create:
|
|
# make sure previous group exists
|
|
self.getElementGroup(True)
|
|
try:
|
|
ret = obj.Group[2]
|
|
checkType(ret,AsmPartGroup)
|
|
parent = getattr(ret.Proxy,'parent',None)
|
|
if not parent:
|
|
ret.Proxy.parent = self
|
|
elif parent!=self:
|
|
raise RuntimeError(
|
|
'invalid parent of part group {}'.format(objName(ret)))
|
|
return ret
|
|
except IndexError:
|
|
if not create:
|
|
raise RuntimeError('Missing part group')
|
|
ret = AsmPartGroup.make(obj)
|
|
obj.setLink({2:ret})
|
|
return ret
|
|
|
|
@staticmethod
|
|
def make(doc=None,name='Assembly',undo=True):
|
|
if not doc:
|
|
doc = FreeCAD.ActiveDocument
|
|
if not doc:
|
|
raise RuntimeError('No active document')
|
|
if undo:
|
|
FreeCAD.setActiveTransaction('Create assembly')
|
|
try:
|
|
obj = doc.addObject("Part::FeaturePython",name,Assembly(),None,True)
|
|
obj.setPropertyStatus('Shape','Transient')
|
|
ViewProviderAssembly(obj.ViewObject)
|
|
obj.Visibility = True
|
|
obj.purgeTouched()
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction()
|
|
except Exception:
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction(True)
|
|
raise
|
|
return obj
|
|
|
|
Info = namedtuple('AssemblyInfo',('Assembly','Object','Subname'))
|
|
|
|
@staticmethod
|
|
def getSelection(sels=None):
|
|
'Find all assembly objects among the current selection'
|
|
objs = set()
|
|
if sels is None:
|
|
sels = FreeCADGui.Selection.getSelectionEx('',False)
|
|
for sel in sels:
|
|
if not sel.SubElementNames:
|
|
if isTypeOf(sel.Object,Assembly,True):
|
|
objs.add(sel.Object)
|
|
continue
|
|
for subname in sel.SubElementNames:
|
|
ret = Assembly.find(sel.Object,subname,keepEmptyChild=True)
|
|
if ret:
|
|
objs.add(ret.Assembly)
|
|
return tuple(objs)
|
|
|
|
@staticmethod
|
|
def find(obj,subname,childType=None,
|
|
recursive=False,relativeToChild=True,keepEmptyChild=False):
|
|
'''
|
|
Find the immediate child of the first Assembly referenced in 'subs'
|
|
|
|
obj: the parent object
|
|
|
|
subname: '.' separated sub-object reference, or string list of
|
|
sub-object names. Must contain no sub-element name.
|
|
|
|
childType: optional checking of the child type.
|
|
|
|
recursive: If True, continue finding the child of the next assembly.
|
|
|
|
relativeToChild: If True, the returned subname is realtive to the child
|
|
object found, or else, it is relative to the assembly, i.e., including
|
|
the child's name
|
|
|
|
Return None if not found, or (assembly,child,sub), where 'sub' is the
|
|
remaining sub name list. If recursive is True, then return a list of
|
|
tuples
|
|
'''
|
|
assembly = None
|
|
child = None
|
|
if isTypeOf(obj,Assembly,True):
|
|
assembly = obj
|
|
subs = subname if isinstance(subname,list) else subname.split('.')
|
|
i= 0
|
|
for i,name in enumerate(subs[:-1]):
|
|
sobj = obj.getSubObject(name+'.',1)
|
|
if not sobj:
|
|
raise RuntimeError('Cannot find sub-object {}, '
|
|
'{}'.format(objName(obj),name))
|
|
obj = sobj
|
|
if assembly and isTypeOf(obj,childType):
|
|
child = obj
|
|
break
|
|
assembly = obj if isTypeOf(obj,Assembly,True) else None
|
|
|
|
if not child:
|
|
if keepEmptyChild and assembly:
|
|
ret = Assembly.Info(Assembly=assembly,Object=None,Subname='')
|
|
return [ret] if recursive else ret
|
|
return
|
|
|
|
ret = Assembly.Info(Assembly = assembly, Object = child,
|
|
Subname = '.'.join(subs[i+1:] if relativeToChild else subs[i:]))
|
|
|
|
if not recursive:
|
|
return ret
|
|
|
|
nret = Assembly.find(child, subs[i+1:], childType, recursive,
|
|
relativeToChild, keepEmptyChild)
|
|
if nret:
|
|
return [ret] + nret
|
|
return [ret]
|
|
|
|
@staticmethod
|
|
def findChildren(obj,subname,tp=None):
|
|
return Assembly.find(obj,subname,tp,True,False,True)
|
|
|
|
@staticmethod
|
|
def findPartGroup(obj,subname='2.',recursive=False,relativeToChild=True):
|
|
return Assembly.find(
|
|
obj,subname,AsmPartGroup,recursive,relativeToChild)
|
|
|
|
@staticmethod
|
|
def findElementGroup(obj,subname='1.',relativeToChild=True):
|
|
return Assembly.find(
|
|
obj,subname,AsmElementGroup,False,relativeToChild)
|
|
|
|
@staticmethod
|
|
def findConstraintGroup(obj,subname='0.',relativeToChild=True):
|
|
return Assembly.find(
|
|
obj,subname,AsmConstraintGroup,False,relativeToChild)
|
|
|
|
|
|
class ViewProviderAssembly(ViewProviderAsmGroup):
|
|
_iconName = 'Assembly_Assembly_Frozen_Tree.svg'
|
|
_addToSceneGraph = True
|
|
|
|
def __init__(self,vobj):
|
|
self._movingPart = None
|
|
super(ViewProviderAssembly,self).__init__(vobj)
|
|
|
|
def attach(self,vobj):
|
|
super(ViewProviderAssembly,self).attach(vobj)
|
|
if not hasattr(vobj,'ShowParts'):
|
|
vobj.addProperty("App::PropertyBool","ShowParts"," Link")
|
|
|
|
def onDelete(self,vobj,_subs):
|
|
for o in vobj.Object.Proxy.getPartGroup().Group:
|
|
if o.TypeId == 'App::Origin':
|
|
o.Document.removeObject(o.Name)
|
|
break
|
|
return True
|
|
|
|
def _convertSubname(self,owner,subname):
|
|
sub = subname.split('.')
|
|
if not sub:
|
|
return
|
|
me = self.ViewObject.Object
|
|
partGroup = me.Proxy.getPartGroup().ViewObject
|
|
if sub[0] == me.Name:
|
|
return partGroup,partGroup,subname[len(sub[0])+1:]
|
|
return partGroup,owner,subname
|
|
|
|
def canDropObjectEx(self,obj,owner,subname,_elements):
|
|
info = self._convertSubname(owner,subname)
|
|
if not info:
|
|
return False
|
|
partGroup,owner,subname = info
|
|
return partGroup.canDropObject(obj,owner,subname)
|
|
|
|
def canDragAndDropObject(self,_obj):
|
|
return True
|
|
|
|
def dropObjectEx(self,_vobj,obj,owner,subname,_elements):
|
|
info = self._convertSubname(owner,subname)
|
|
if not info:
|
|
return False
|
|
partGroup,owner,subname = info
|
|
partGroup.dropObject(obj,owner,subname)
|
|
|
|
def updateData(self,obj,prop):
|
|
if prop == 'Freeze':
|
|
obj.ViewObject.signalChangeIcon()
|
|
|
|
def getIcon(self):
|
|
if getattr(self.ViewObject.Object,'Freeze',False):
|
|
return utils.getIcon(self.__class__)
|
|
return System.getIcon(self.ViewObject.Object)
|
|
|
|
def doubleClicked(self, _vobj):
|
|
from . import mover
|
|
return mover.movePart()
|
|
|
|
def onExecute(self):
|
|
if not getattr(self,'_movingPart',None):
|
|
return
|
|
|
|
pla = logger.catch('exception when update moving part',
|
|
self._movingPart.update)
|
|
if pla:
|
|
self.ViewObject.DraggingPlacement = pla
|
|
return
|
|
|
|
# Must NOT call resetEdit() here. Because we are called through dragger
|
|
# callback, meaning that we are called during coin node traversal.
|
|
# resetEdit() will cause View3DInventorView to reset editing root node.
|
|
# And disaster will happen when modifying coin node tree while
|
|
# traversing.
|
|
#
|
|
# doc = FreeCADGui.editDocument()
|
|
# if doc:
|
|
# doc.resetEdit()
|
|
|
|
def initDraggingPlacement(self):
|
|
if not getattr(self,'_movingPart',None):
|
|
return
|
|
self._movingPart.begin()
|
|
return (FreeCADGui.editDocument().EditingTransform,
|
|
self._movingPart.draggerPlacement,
|
|
self._movingPart.bbox)
|
|
|
|
_Busy = False
|
|
|
|
def onDragStart(self):
|
|
Assembly.cancelAutoSolve();
|
|
FreeCADGui.Selection.clearSelection()
|
|
self.__class__._Busy = True
|
|
FreeCAD.setActiveTransaction('Assembly move')
|
|
|
|
def onDragMotion(self):
|
|
return self._movingPart.move()
|
|
|
|
def onDragEnd(self):
|
|
self.__class__._Busy = False
|
|
FreeCAD.closeActiveTransaction()
|
|
|
|
def unsetEdit(self,_vobj,_mode):
|
|
self._movingPart = None
|
|
return False
|
|
|
|
def showParts(self):
|
|
self.ViewObject.Object.Proxy.getPartGroup().ViewObject.Proxy.showParts()
|
|
|
|
def updateData(self,_obj,prop):
|
|
if not hasattr(self,'ViewObject') or FreeCAD.isRestoring():
|
|
return
|
|
if prop=='Freeze' or prop=='BuildShape':
|
|
self.showParts()
|
|
|
|
def onChanged(self,_vobj,prop):
|
|
if not hasattr(self,'ViewObject') or FreeCAD.isRestoring():
|
|
return
|
|
if prop=='ShowParts':
|
|
self.showParts()
|
|
|
|
def onFinishRestoring(self):
|
|
self.showParts()
|
|
|
|
@classmethod
|
|
def isBusy(cls):
|
|
return cls._Busy
|
|
|
|
|
|
class AsmWorkPlane(object):
|
|
def __init__(self,obj):
|
|
obj.addProperty("App::PropertyLength","Length","Base")
|
|
obj.addProperty("App::PropertyLength","Width","Base")
|
|
obj.addProperty("App::PropertyBool","Fixed","Base")
|
|
obj.Fixed = True
|
|
obj.Length = 10
|
|
obj.Width = 10
|
|
obj.Proxy = self
|
|
|
|
def execute(self,obj):
|
|
length = obj.Length.Value
|
|
width = obj.Width.Value
|
|
if not length:
|
|
if not width:
|
|
obj.Shape = Part.Vertex(FreeCAD.Vector())
|
|
else:
|
|
obj.Shape = Part.makeLine(FreeCAD.Vector(0,-width/2,0),
|
|
FreeCAD.Vector(0,width/2,0))
|
|
elif not width:
|
|
obj.Shape = Part.makeLine(FreeCAD.Vector(-length/2,0,0),
|
|
FreeCAD.Vector(length/2,0,0))
|
|
else:
|
|
obj.Shape = Part.makePlane(length,width,
|
|
FreeCAD.Vector(-length/2,-width/2,0))
|
|
|
|
def __getstate__(self):
|
|
return
|
|
|
|
def __setstate__(self,_state):
|
|
return
|
|
|
|
Info = namedtuple('AsmWorkPlaneSelectionInfo',
|
|
('SelObj','SelSubname','PartGroup','Placement','Shape','BoundBox'))
|
|
|
|
@staticmethod
|
|
def getSelection(sels=None):
|
|
if not sels:
|
|
sels = FreeCADGui.Selection.getSelectionEx('',False)
|
|
if not sels:
|
|
raise RuntimeError('no selection')
|
|
elements = []
|
|
objs = []
|
|
for sel in sels:
|
|
if not sel.SubElementNames:
|
|
elements.append((sel.Object,''))
|
|
objs.append(sel.Object)
|
|
continue
|
|
for sub in sel.SubElementNames:
|
|
elements.append((sel.Object,sub))
|
|
objs.append(sel.Object.getSubObject(sub,1))
|
|
if len(elements) > 2:
|
|
raise RuntimeError('Too many selection')
|
|
elif len(elements)==2:
|
|
if isTypeOf(objs[0],Assembly,True):
|
|
assembly = objs[0]
|
|
selObj,sub = elements[0]
|
|
element = elements[1]
|
|
elif isTypeOf(objs[1],Assembly,True):
|
|
assembly = objs[1]
|
|
selObj,sub = elements[1]
|
|
element = elements[0]
|
|
else:
|
|
raise RuntimeError('For two selections, one of the selections '
|
|
'must be of an assembly container')
|
|
_,mat = selObj.getSubObject(sub,1,FreeCAD.Matrix())
|
|
shape = utils.getElementShape(element,transform=True)
|
|
bbox = shape.BoundBox
|
|
pla = utils.getElementPlacement(shape,mat)
|
|
else:
|
|
shape = None
|
|
element = elements[0]
|
|
ret = Assembly.find(element[0],element[1],
|
|
relativeToChild=False,keepEmptyChild=True)
|
|
if not ret:
|
|
raise RuntimeError('Single selection must be an assembly or '
|
|
'an object inside of an assembly')
|
|
assembly = ret.Assembly
|
|
sub = element[1][:-len(ret.Subname)]
|
|
selObj = element[0]
|
|
if not ret.Subname:
|
|
pla = FreeCAD.Placement()
|
|
bbox = assembly.ViewObject.getBoundingBox()
|
|
else:
|
|
shape = utils.getElementShape((assembly,ret.Subname),
|
|
transform=True)
|
|
bbox = shape.BoundBox
|
|
pla = utils.getElementPlacement(shape,
|
|
ret.Assembly.Placement.toMatrix())
|
|
|
|
return AsmWorkPlane.Info(
|
|
SelObj = selObj,
|
|
SelSubname = sub,
|
|
PartGroup = assembly.Proxy.getPartGroup(),
|
|
Shape = shape,
|
|
Placement = pla,
|
|
BoundBox = bbox)
|
|
|
|
@staticmethod
|
|
def make(sels=None,name=None, tp=0, undo=True):
|
|
info = AsmWorkPlane.getSelection(sels)
|
|
doc = info.PartGroup.Document
|
|
if undo:
|
|
FreeCAD.setActiveTransaction('Assembly create workplane')
|
|
try:
|
|
logger.debug('make {}'.format(tp))
|
|
if tp == 3:
|
|
obj = None
|
|
for o in info.PartGroup.Group:
|
|
if o.TypeId == 'App::Origin':
|
|
obj = o
|
|
break
|
|
if not obj:
|
|
if not name:
|
|
name = 'Origin'
|
|
obj = doc.addObject('App::Origin',name)
|
|
info.PartGroup.setLink({-1:obj})
|
|
|
|
info.PartGroup.recompute(True)
|
|
shape = Part.getShape(info.PartGroup)
|
|
if not shape.isNull():
|
|
bbox = shape.BoundBox
|
|
if bbox.isValid():
|
|
obj.ViewObject.Size = tuple([
|
|
max(abs(a),abs(b)) for a,b in (
|
|
(bbox.XMin,bbox.XMax),
|
|
(bbox.YMin,bbox.YMax),
|
|
(bbox.ZMin,bbox.ZMax)) ])
|
|
else:
|
|
if not name:
|
|
name = 'Workplane'
|
|
obj = doc.addObject('Part::FeaturePython',name)
|
|
AsmWorkPlane(obj)
|
|
ViewProviderAsmWorkPlane(obj.ViewObject)
|
|
if tp==1:
|
|
pla = FreeCAD.Placement(info.Placement.Base,
|
|
FreeCAD.Rotation(FreeCAD.Vector(0,1,0),-90))
|
|
elif tp==2:
|
|
pla = FreeCAD.Placement(info.Placement.Base,
|
|
FreeCAD.Rotation(FreeCAD.Vector(1,0,0),90))
|
|
else:
|
|
pla = info.Placement
|
|
|
|
if utils.isVertex(info.Shape):
|
|
obj.Length = obj.Width = 0
|
|
elif utils.isLinearEdge(info.Shape):
|
|
if info.BoundBox.isValid():
|
|
obj.Length = info.BoundBox.DiagonalLength
|
|
obj.Width = 0
|
|
pla = FreeCAD.Placement(pla.Base,pla.Rotation.multiply(
|
|
FreeCAD.Rotation(FreeCAD.Vector(0,1,0),90)))
|
|
elif info.BoundBox.isValid():
|
|
obj.Length = obj.Width = info.BoundBox.DiagonalLength
|
|
|
|
obj.Placement = pla
|
|
|
|
obj.recompute(True)
|
|
info.PartGroup.setLink({-1:obj})
|
|
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction()
|
|
|
|
FreeCADGui.Selection.clearSelection()
|
|
FreeCADGui.Selection.addSelection(info.SelObj,
|
|
info.SelSubname + info.PartGroup.Name + '.' + obj.Name + '.')
|
|
FreeCADGui.runCommand('Std_TreeSelection')
|
|
FreeCADGui.Selection.setVisible(True)
|
|
return obj
|
|
except Exception:
|
|
if undo:
|
|
FreeCAD.closeActiveTransaction(True)
|
|
raise
|
|
|
|
|
|
class ViewProviderAsmWorkPlane(ViewProviderAsmBase):
|
|
_iconName = 'Assembly_Workplane.svg'
|
|
|
|
def __init__(self,vobj):
|
|
vobj.Transparency = 50
|
|
color = (0.0,0.33,1.0,1.0)
|
|
vobj.LineColor = color
|
|
vobj.PointColor = color
|
|
vobj.OnTopWhenSelected = 1
|
|
super(ViewProviderAsmWorkPlane,self).__init__(vobj)
|
|
|
|
def canDropObjects(self):
|
|
return False
|
|
|
|
def getDisplayModes(self, _vobj):
|
|
modes=[]
|
|
return modes
|
|
|
|
def setDisplayMode(self, mode):
|
|
return mode
|
|
|