import FreeCAD as App
import DraftVecUtils
import lazy_loader.lazy_loader as lz
from draftutils.messages import _err, _log, _wrn
from draftutils.translate import translate
def QT_TRANSLATE_NOOP(ctx, txt):
return txt
from draftobjects.base import DraftObject
from draftobjects.draftlink import DraftLink
Part = lz.LazyLoader("Part", globals(), "Part")
DraftGeomUtils = lz.LazyLoader("DraftGeomUtils", globals(), "DraftGeomUtils")
class PathArray(DraftLink):
def __init__(self, obj):
super().__init__(obj, "PathArray")
def attach(self, obj):
self.set_properties(obj)
super().attach(obj)
def set_properties(self, obj):
if not obj:
return
if hasattr(obj, "PropertiesList"):
properties = obj.PropertiesList
else:
properties = []
self.set_general_properties(obj, properties)
self.set_spacing_properties(obj, properties)
self.set_align_properties(obj, properties)
def set_general_properties(self, obj, properties):
if "Base" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "The base object that will be duplicated")
obj.addProperty("App::PropertyLinkGlobal", "Base", "Objects", _tip, locked=True)
obj.Base = None
if "PathObject" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"The object along which the copies will be distributed. It must contain 'Edges'.",
)
obj.addProperty("App::PropertyLinkGlobal", "PathObject", "Objects", _tip, locked=True)
obj.PathObject = None
if "PathSubelements" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"List of connected edges in the 'Path Object'.\nIf these are present, the copies will be created along these subelements only.\nLeave this property empty to create copies along the entire 'Path Object'.",
)
obj.addProperty(
"App::PropertyLinkSubListGlobal", "PathSubelements", "Objects", _tip, locked=True
)
obj.PathSubelements = []
if "Fuse" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"Specifies if the copies "
"should be fused together "
"if they touch each other (slower)",
)
obj.addProperty("App::PropertyBool", "Fuse", "Objects", _tip, locked=True)
obj.Fuse = False
if self.use_link and "ExpandArray" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Show the individual array elements (only for Link arrays)"
)
obj.addProperty("App::PropertyBool", "ExpandArray", "Objects", _tip, locked=True)
obj.ExpandArray = False
obj.setPropertyStatus("Shape", "Transient")
if not self.use_link:
if "PlacementList" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "The placement for each array element")
obj.addProperty(
"App::PropertyPlacementList", "PlacementList", "Objects", _tip, locked=True
)
obj.PlacementList = []
def set_align_properties(self, obj, properties):
if "ExtraTranslation" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"Additional translation that will be applied to each copy.\nThis is useful to adjust for the difference between shape centre and shape reference point.",
)
obj.addProperty(
"App::PropertyVectorDistance", "ExtraTranslation", "Alignment", _tip, locked=True
)
obj.ExtraTranslation = App.Vector(0, 0, 0)
if "TangentVector" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "Alignment vector for 'Tangent' mode")
obj.addProperty("App::PropertyVector", "TangentVector", "Alignment", _tip, locked=True)
obj.TangentVector = App.Vector(1, 0, 0)
if "ForceVertical" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"Force use of 'Vertical Vector' as local Z-direction when using 'Original' or 'Tangent' alignment mode",
)
obj.addProperty("App::PropertyBool", "ForceVertical", "Alignment", _tip, locked=True)
obj.ForceVertical = False
if "VerticalVector" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Direction of the local Z axis when 'Force Vertical' is true"
)
obj.addProperty("App::PropertyVector", "VerticalVector", "Alignment", _tip, locked=True)
obj.VerticalVector = App.Vector(0, 0, 1)
if "AlignMode" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"Method to orient the copies along the path.\n- Original: X is curve tangent, Y is normal, and Z is the cross product.\n- Frenet: aligns the object following the local coordinate system along the path.\n- Tangent: similar to 'Original' but the local X axis is pre-aligned to 'Tangent Vector'.\n\nTo get better results with 'Original' or 'Tangent' you may have to set 'Force Vertical' to true.",
)
obj.addProperty("App::PropertyEnumeration", "AlignMode", "Alignment", _tip, locked=True)
obj.AlignMode = ["Original", "Frenet", "Tangent"]
obj.AlignMode = "Original"
if "ReversePath" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "Walk the path backwards.")
obj.addProperty("App::PropertyBool", "ReversePath", "Alignment", _tip, locked=True)
obj.ReversePath = False
if "Align" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"Orient the copies along the path depending on the 'Align Mode'.\nOtherwise the copies will have the same orientation as the original Base object.",
)
obj.addProperty("App::PropertyBool", "Align", "Alignment", _tip, locked=True)
obj.Align = False
def set_spacing_properties(self, obj, properties):
if "Count" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "Number of copies to create")
obj.addProperty("App::PropertyInteger", "Count", "Spacing", _tip, locked=True)
obj.Count = 4
if "SpacingMode" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property",
"How copies are spaced.\n"
+ " - Fixed count: available path length (minus start and end offsets) is evenly divided into n.\n"
+ ' - Fixed spacing: start at "Start offset" and place new copies after traveling a fixed distance along the path.\n'
+ ' - Fixed count and spacing: same as "Fixed spacing", but also stop at given number of copies.',
)
obj.addProperty("App::PropertyEnumeration", "SpacingMode", "Spacing", _tip, locked=True)
obj.SpacingMode = ["Fixed count", "Fixed spacing", "Fixed count and spacing"]
obj.SpacingMode = "Fixed count"
if "SpacingUnit" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "Base fixed distance between elements.")
obj.addProperty("App::PropertyLength", "SpacingUnit", "Spacing", _tip, locked=True)
obj.SpacingUnit = 20.0
obj.setPropertyStatus("SpacingUnit", "Hidden")
if "UseSpacingPattern" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Use repeating spacing patterns instead of uniform spacing."
)
obj.addProperty("App::PropertyBool", "UseSpacingPattern", "Spacing", _tip, locked=True)
obj.UseSpacingPattern = False
if "SpacingPattern" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Spacing is multiplied by a corresponding number in this sequence."
)
obj.addProperty(
"App::PropertyFloatList", "SpacingPattern", "Spacing", _tip, locked=True
)
obj.SpacingPattern = [1, 2]
obj.setPropertyStatus("SpacingPattern", "Hidden")
if "StartOffset" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Length from the start of the path to the first copy."
)
obj.addProperty("App::PropertyLength", "StartOffset", "Spacing", _tip, locked=True)
obj.StartOffset = 0.0
if "EndOffset" not in properties:
_tip = QT_TRANSLATE_NOOP(
"App::Property", "Length from the end of the path to the last copy."
)
obj.addProperty("App::PropertyLength", "EndOffset", "Spacing", _tip, locked=True)
obj.EndOffset = 0.0
def linkSetup(self, obj):
super().linkSetup(obj)
obj.configLinkProperty(ElementCount="Count")
def execute(self, obj):
if self.props_changed_placement_only(obj) or not obj.Base or not obj.PathObject:
self.props_changed_clear()
return
array_placement = obj.Placement
w = self.get_wires(obj.PathObject, obj.PathSubelements)
if not w:
_err(obj.PathObject.Label + translate("draft", ", path object does not have 'Edges'."))
return
base_rotation = obj.Base.Shape.Placement.Rotation
final_rotation = base_rotation
if obj.Align and obj.AlignMode == "Tangent" and hasattr(obj, "TangentVector"):
Xaxis = App.Vector(1.0, 0.0, 0.0)
if not DraftVecUtils.equals(Xaxis, obj.TangentVector):
pre_rotation = App.Rotation(obj.TangentVector, Xaxis)
final_rotation = base_rotation.multiply(pre_rotation)
copy_placements = placements_on_path(
final_rotation,
w,
obj.Count,
obj.ExtraTranslation,
obj.Align,
obj.AlignMode,
obj.ForceVertical,
obj.VerticalVector,
obj.StartOffset.Value,
obj.EndOffset.Value,
obj.ReversePath,
obj.SpacingMode,
obj.SpacingUnit.Value,
obj.UseSpacingPattern,
obj.SpacingPattern,
)
self.buildShape(obj, array_placement, copy_placements)
self.props_changed_clear()
return not self.use_link
def get_wires(self, path_object, subelements):
if subelements:
w = self.get_wire_from_subelements(subelements)
elif hasattr(path_object.Shape, "Wires") and path_object.Shape.Wires:
w = path_object.Shape.Wires[0]
elif path_object.Shape.Edges:
w = Part.Wire(path_object.Shape.Edges)
else:
w = None
return w
def get_wire_from_subelements(self, subelements):
sl = []
for sub in subelements:
edgeNames = sub[1]
for n in edgeNames:
e = sub[0].Shape.getElement(n)
sl.append(e)
return Part.Wire(Part.__sortEdges__(sl))
def onChanged(self, obj, prop):
super().onChanged(obj, prop)
self.show_and_hide(obj, prop)
def show_and_hide(self, obj, prop):
if prop == "SpacingMode":
for pr in ("SpacingMode", "SpacingUnit", "UseSpacingPattern", "SpacingPattern"):
if not hasattr(obj, pr):
return
if obj.SpacingMode == "Fixed spacing":
obj.setPropertyStatus("Count", "Hidden")
obj.setPropertyStatus("SpacingUnit", "-Hidden")
elif obj.SpacingMode == "Fixed count":
obj.setPropertyStatus("Count", "-Hidden")
obj.setPropertyStatus("SpacingUnit", "Hidden")
elif obj.SpacingMode == "Fixed count and spacing":
obj.setPropertyStatus("Count", "-Hidden")
obj.setPropertyStatus("SpacingUnit", "-Hidden")
if prop == "UseSpacingPattern":
if not hasattr(obj, "SpacingPattern"):
return
if obj.UseSpacingPattern:
obj.setPropertyStatus("SpacingPattern", "-Hidden")
else:
obj.setPropertyStatus("SpacingPattern", "Hidden")
if prop in ("Align", "AlignMode"):
for pr in ("Align", "AlignMode", "ForceVertical", "VerticalVector", "TangentVector"):
if not hasattr(obj, pr):
return
if obj.Align:
obj.setPropertyStatus("AlignMode", "-Hidden")
if obj.AlignMode == "Frenet":
for pr in ("ForceVertical", "VerticalVector"):
obj.setPropertyStatus(pr, "Hidden")
else:
for pr in ("ForceVertical", "VerticalVector"):
obj.setPropertyStatus(pr, "-Hidden")
if obj.AlignMode == "Tangent":
obj.setPropertyStatus("TangentVector", "-Hidden")
else:
obj.setPropertyStatus("TangentVector", "Hidden")
else:
for pr in ("AlignMode", "ForceVertical", "VerticalVector", "TangentVector"):
obj.setPropertyStatus(pr, "Hidden")
def onDocumentRestored(self, obj):
super().onDocumentRestored(obj)
if hasattr(obj, "ReversePath") and hasattr(obj, "PlacementList"):
return
if hasattr(obj, "PathObj"):
_log("v0.19, " + obj.Name + ", migrated 'PathObj' property to 'PathObject'")
if hasattr(obj, "PathSubs"):
_log("v0.19, " + obj.Name + ", migrated 'PathSubs' property to 'PathSubelements'")
if hasattr(obj, "Xlate"):
_log("v0.19, " + obj.Name + ", migrated 'Xlate' property to 'ExtraTranslation'")
if not hasattr(obj, "Fuse"):
_log("v1.0, " + obj.Name + ", added 'Fuse' property")
if obj.getGroupOfProperty("Count") != "Spacing":
_log("v1.1, " + obj.Name + ", moved 'Count' property to 'Spacing' subsection")
if not hasattr(obj, "ReversePath"):
_log(
"v1.1, "
+ obj.Name
+ ", "
+ "added 'ReversePath', 'SpacingMode', 'SpacingUnit', 'UseSpacingPattern' "
+ "and 'SpacingPattern' properties"
)
if not hasattr(obj, "PlacementList"):
_log("v1.1, " + obj.Name + ", added hidden property 'PlacementList'")
self.set_properties(obj)
obj.setGroupOfProperty("Count", "Spacing")
if hasattr(obj, "PathObj"):
obj.PathObject = obj.PathObj
obj.removeProperty("PathObj")
if hasattr(obj, "PathSubs"):
obj.PathSubelements = obj.PathSubs
obj.removeProperty("PathSubs")
if hasattr(obj, "Xlate"):
obj.ExtraTranslation = obj.Xlate
obj.removeProperty("Xlate")
self.execute(obj)
_PathArray = PathArray
def placements_on_path(
shapeRotation,
pathwire,
count,
xlate,
align,
mode="Original",
forceNormal=False,
normalOverride=None,
startOffset=0.0,
endOffset=0.0,
reversePath=False,
spacingMode="Fixed count",
spacingUnit=20.0,
useSpacingPattern=False,
spacingPattern=[1, 1, 1, 1],
):
if mode == "Frenet":
forceNormal = False
if forceNormal and normalOverride:
normal = normalOverride
else:
normal = DraftGeomUtils.get_shape_normal(pathwire)
if normal is None:
normal = App.Vector(0, 0, 1)
path = Part.__sortEdges__(pathwire.Edges)
if reversePath:
path = path[::-1]
totalDist = 0
ends = []
for e in path:
totalDist += e.Length
ends.append(totalDist)
minLength = 1e-6 if align else -1e-12
if startOffset > (totalDist - minLength):
if startOffset != 0:
_wrn(translate("draft", "Start Offset too large for path length. Using 0 instead."))
startOffset = 0
if endOffset > (totalDist - startOffset - minLength):
if endOffset != 0:
_wrn(
translate(
"draft",
"End Offset too large for path length minus Start Offset. Using 0 instead.",
)
)
endOffset = 0
totalDist = totalDist - startOffset - endOffset
useFlexibleSpacing = spacingMode == "Fixed count"
useFixedSpacing = spacingMode in ("Fixed spacing", "Fixed count and spacing")
stopAfterCount = spacingMode in ("Fixed count", "Fixed count and spacing")
stopAfterDistance = spacingMode in ("Fixed spacing", "Fixed count and spacing")
spacingUnit = max(spacingUnit, 0)
if spacingUnit == 0:
_wrn(translate("draft", "Spacing unit of 0 is not allowed, using default"))
spacingUnit = totalDist
spacingPattern = [abs(w) for w in spacingPattern]
if sum(spacingPattern) == 0:
spacingPattern = [spacingUnit]
isClosedPath = DraftGeomUtils.isReallyClosed(pathwire) and not (startOffset or endOffset)
count = max(count, 1)
if useFlexibleSpacing:
segCount = count if isClosedPath else count - 1
segCount = max(segCount, 1)
if useSpacingPattern:
fullSpacingPattern = [spacingPattern[i % len(spacingPattern)] for i in range(segCount)]
sumWeights = sum(fullSpacingPattern)
distPerWeightUnit = totalDist / sumWeights
steps = [distPerWeightUnit * weight for weight in fullSpacingPattern]
else:
steps = [totalDist / segCount]
if useFixedSpacing:
if useSpacingPattern:
steps = [spacingUnit * mult for mult in spacingPattern]
else:
steps = [spacingUnit]
remains = 0
travel = startOffset
endTravel = startOffset + totalDist
placements = []
i = 0
while True:
for j in range(len(ends)):
if travel <= ends[j]:
iend = j
remains = ends[iend] - travel
offset = path[iend].Length - remains if not reversePath else remains
break
else:
iend = len(ends) - 1
offset = path[iend].Length if not reversePath else 0
pt = path[iend].valueAt(get_parameter_from_v0(path[iend], offset))
place = calculate_placement(
shapeRotation,
path[iend],
offset,
pt,
xlate,
align,
normal,
mode,
forceNormal,
reversePath,
)
placements.append(place)
travel += steps[i % len(steps)]
i = i + 1
if stopAfterDistance and travel > endTravel:
break
if stopAfterCount and i >= count:
break
if i > 10_000:
_wrn(translate("draft", "Operation would generate too many objects. Aborting"))
return placements[0:1]
return placements
calculatePlacementsOnPath = placements_on_path
def calculate_placement(
globalRotation,
edge,
offset,
RefPt,
xlate,
align,
normal=App.Vector(0.0, 0.0, 1.0),
mode="Original",
overrideNormal=False,
reversePath=False,
):
placement = App.Placement()
placement.Rotation = globalRotation.inverted() if reversePath else globalRotation
placement.Base = RefPt + placement.Rotation.multVec(xlate)
if not align:
return placement
tol = 1e-6 nullv = App.Vector()
t = edge.tangentAt(get_parameter_from_v0(edge, offset))
if t.isEqual(nullv, tol):
_wrn(translate("draft", "Length of tangent vector is 0. Copy not aligned."))
return placement
if reversePath:
t.multiply(-1)
if mode in ("Original", "Tangent"):
n = normal
if n.isEqual(nullv, tol):
_wrn(translate("draft", "Length of normal vector is 0. Using a default axis instead."))
n = t
else:
n_nor = n.normalize()
t_nor = t.normalize()
if n_nor.isEqual(t_nor, tol) or n_nor.isEqual(t_nor.negative(), tol):
_wrn(
translate(
"draft",
"Tangent and normal vectors are parallel. Normal replaced by a default axis.",
)
)
n = t
if overrideNormal:
onPathRotation = App.Rotation(t, nullv, n, "XZY") else:
onPathRotation = App.Rotation(t, n, nullv, "XYZ")
elif mode == "Frenet":
try:
n = edge.normalAt(get_parameter_from_v0(edge, offset))
except App.Base.FreeCADError: _wrn(
translate(
"draft", "Cannot calculate normal vector. Using the default normal instead."
)
)
n = normal
if n.isEqual(nullv, tol):
_wrn(translate("draft", "Length of normal vector is 0. Using a default axis instead."))
n = t
else:
n_nor = n.normalize()
t_nor = t.normalize()
if n_nor.isEqual(t_nor, tol) or n_nor.isEqual(t_nor.negative(), tol):
_wrn(
translate(
"draft",
"Tangent and normal vectors are parallel. Normal replaced by a default axis.",
)
)
n = t
onPathRotation = App.Rotation(t, n, nullv, "XYZ")
else:
_err(translate("draft", "AlignMode {} is not implemented").format(mode))
return placement
placement.Rotation = onPathRotation.multiply(globalRotation)
placement.Base = RefPt + placement.Rotation.multVec(xlate)
return placement
calculatePlacement = calculate_placement
def get_parameter_from_v0(edge, offset):
lpt = edge.valueAt(edge.getParameterByLength(0))
vpt = edge.Vertexes[0].Point
if not DraftVecUtils.equals(vpt, lpt):
length = edge.Length - offset
else:
length = offset
return edge.getParameterByLength(length)
getParameterFromV0 = get_parameter_from_v0