-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCurvedArray.py
More file actions
367 lines (281 loc) · 16.4 KB
/
Copy pathCurvedArray.py
File metadata and controls
367 lines (281 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# -*- coding: utf-8 -*-
from PySide.QtCore import QT_TRANSLATE_NOOP
__title__ = "CurvedArray"
__author__ = "Christian Bergmann"
__license__ = "LGPL 2.1"
__doc__ = QT_TRANSLATE_NOOP("CurvedArray", "Creates an array and resizes the items in the bounds of curves in the XY, XZ or YZ plane.")
import os
import FreeCAD
from FreeCAD import Vector
import Part
import CompoundTools.Explode
import CurvedShapes
if FreeCAD.GuiUp:
import FreeCADGui
epsilon = CurvedShapes.epsilon
translate = FreeCAD.Qt.translate
class CurvedArray:
def __init__(self,
obj,
base = None,
hullcurves=[],
axis=Vector(0.0,0.0,0.0),
items=2,
Positions = [],
OffsetStart=0, OffsetEnd=0,
Twist=0.0,
Surface=True,
Solid = False,
Distribution = 'linear',
DistributionReverse = False,
extract=False,
Twists = [],
LoftMaxDegree=5,
MaxLoftSize=16,
KeepBase='None',
PreserveAspectRatio=False):
CurvedShapes.addObjectProperty(obj, "App::PropertyLink", "Base", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "The object to make an array from")).Base = base
CurvedShapes.addObjectProperty(obj, "App::PropertyLinkList", "Hullcurves", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Bounding curves. Use a single curve with PreserveAspectRatio to scale the Base shape uniformly.")).Hullcurves = hullcurves
CurvedShapes.addObjectProperty(obj, "App::PropertyVector", "Axis", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Direction axis")).Axis = axis
CurvedShapes.addObjectProperty(obj, "App::PropertyQuantity", "Items", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Nr. of array items")).Items = items
CurvedShapes.addObjectProperty(obj, "App::PropertyFloatList", "Positions", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Positions for ribs (as floats from 0.0 to 1.0) -- overrides Items")).Positions = Positions
CurvedShapes.addObjectProperty(obj, "App::PropertyFloat", "OffsetStart", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Offset of the first part in Axis direction")).OffsetStart = OffsetStart
CurvedShapes.addObjectProperty(obj, "App::PropertyFloat", "OffsetEnd", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Offset of the last part from the end in opposite Axis direction")).OffsetEnd = OffsetEnd
CurvedShapes.addObjectProperty(obj, "App::PropertyFloat", "Twist", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Rotate around Axis in degrees")).Twist = Twist
CurvedShapes.addObjectProperty(obj, "App::PropertyFloatList", "Twists", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Rotate around Axis in degrees for each item -- overrides Twist")).Twists = Twists
CurvedShapes.addObjectProperty(obj, "App::PropertyEnumeration", "KeepBase", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Include the base shape unmodified and where"))
CurvedShapes.addObjectProperty(obj, "App::PropertyBool", "Surface", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Make a surface")).Surface = Surface
CurvedShapes.addObjectProperty(obj, "App::PropertyBool", "Solid", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Make a solid")).Solid = Solid
CurvedShapes.addObjectProperty(obj, "App::PropertyEnumeration", "Distribution", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Algorithm for distance between elements"))
CurvedShapes.addObjectProperty(obj, "App::PropertyBool", "DistributionReverse", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Reverses direction of Distribution algorithm")).DistributionReverse = DistributionReverse
CurvedShapes.addObjectProperty(obj, "App::PropertyInteger", "LoftMaxDegree", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Max Degree for Surface or Solid")).LoftMaxDegree = LoftMaxDegree
CurvedShapes.addObjectProperty(obj, "App::PropertyInteger", "MaxLoftSize", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Max Size of a Loft in Segments.")).MaxLoftSize = MaxLoftSize
CurvedShapes.addObjectProperty(obj, "App::PropertyBool", "PreserveAspectRatio", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Scale the Base shape uniformly based on the single Hullcurve, preserving its aspect ratio. Requires exactly one Hullcurve.")).PreserveAspectRatio = PreserveAspectRatio
obj.Distribution = ['linear', 'parabolic', 'x³', 'sinusoidal', 'asinusoidal', 'elliptic']
obj.Distribution = Distribution
obj.KeepBase = ['None', 'First', 'Last']
obj.KeepBase = KeepBase
self.extract = extract
self.doScaleXYZ = []
self.doScaleXYZsum = [False, False, False]
obj.Proxy = self
def makeRibs(self, obj):
pl = obj.Placement
ribs = []
curvebox = FreeCAD.BoundBox(float("-inf"), float("-inf"), float("-inf"), float("inf"), float("inf"), float("inf"))
for n in range(0, len(obj.Hullcurves)):
cbbx = obj.Hullcurves[n].Shape.BoundBox
if self.doScaleXYZ[n][0]:
if cbbx.XMin > curvebox.XMin: curvebox.XMin = cbbx.XMin
if cbbx.XMax < curvebox.XMax: curvebox.XMax = cbbx.XMax
if self.doScaleXYZ[n][1]:
if cbbx.YMin > curvebox.YMin: curvebox.YMin = cbbx.YMin
if cbbx.YMax < curvebox.YMax: curvebox.YMax = cbbx.YMax
if self.doScaleXYZ[n][2]:
if cbbx.ZMin > curvebox.ZMin: curvebox.ZMin = cbbx.ZMin
if cbbx.ZMax < curvebox.ZMax: curvebox.ZMax = cbbx.ZMax
if curvebox.XMin == float("-inf"):
curvebox.XMin = obj.Hullcurves[0].Shape.BoundBox.XMin
if curvebox.XMax == float("inf"):
curvebox.XMax = obj.Hullcurves[0].Shape.BoundBox.XMax
if curvebox.YMin == float("-inf"):
curvebox.YMin = obj.Hullcurves[0].Shape.BoundBox.YMin
if curvebox.YMax == float("inf"):
curvebox.YMax = obj.Hullcurves[0].Shape.BoundBox.YMax
if curvebox.ZMin == float("-inf"):
curvebox.ZMin = obj.Hullcurves[0].Shape.BoundBox.ZMin
if curvebox.ZMax == float("inf"):
curvebox.ZMax = obj.Hullcurves[0].Shape.BoundBox.ZMax
areavec = Vector(curvebox.XLength, curvebox.YLength, curvebox.ZLength)
deltavec = areavec.scale(obj.Axis.x, obj.Axis.y ,obj.Axis.z) - (obj.OffsetStart + obj.OffsetEnd) * obj.Axis
sections = int(obj.Items)
startvec = Vector(curvebox.XMin, curvebox.YMin, curvebox.ZMin)
if obj.Axis.x < 0: startvec.x = curvebox.XMax
if obj.Axis.y < 0: startvec.y = curvebox.YMax
if obj.Axis.z < 0: startvec.z = curvebox.ZMax
pos0 = startvec + (obj.OffsetStart * obj.Axis)
if (not hasattr(obj,"Positions") or len(obj.Positions) == 0):
for x in range(0, sections):
if sections > 1:
d = CurvedShapes.distribute(x / (sections - 1), obj.Distribution, obj.DistributionReverse)
posvec = pos0 + (deltavec * d)
else:
posvec = pos0
rib = self.makeRibRotate(obj, posvec, x, d, ribs)
else:
x = 0
for p in obj.Positions:
posvec = pos0 + (deltavec * p)
rib = self.makeRibRotate(obj, posvec, x, x / len(obj.Positions), ribs)
x = x + 1
if (obj.KeepBase == 'First'):
ribs[0] = obj.Base.Shape.copy()
elif (obj.KeepBase == 'Last'):
ribs[-1] = obj.Base.Shape.copy()
if (obj.Surface or obj.Solid) and obj.Items > 1:
obj.Shape = CurvedShapes.makeSurfaceSolid(ribs, obj.Solid, maxDegree=obj.LoftMaxDegree, maxLoftSize=obj.MaxLoftSize)
else:
obj.Shape = Part.makeCompound(ribs)
obj.Placement = pl
if self.extract:
CompoundTools.Explode.explodeCompound(obj)
obj.ViewObject.hide()
def makeRibRotate(self, obj, posvec, x, d, ribs):
dolly = self.makeRib(obj, posvec)
if dolly:
if x < len(obj.Twists):
dolly = dolly.rotate(dolly.BoundBox.Center, obj.Axis, obj.Twists[x])
elif not obj.Twist == 0:
dolly = dolly.rotate(dolly.BoundBox.Center, obj.Axis, obj.Twist * d)
ribs.append(dolly)
def makeRib(self, obj, posvec):
bbox = CurvedShapes.boundbox_from_intersect(obj.Hullcurves, posvec, obj.Axis, self.doScaleXYZ, False)
if not bbox:
return None
#box = Part.makeBox(max(bbox.XLength, 0.1), max(bbox.YLength, 0.1), max(bbox.ZLength, 0.1))
#box.Placement.Base.x = bbox.XMin
#box.Placement.Base.y = bbox.YMin
#box.Placement.Base.z = bbox.ZMin
#Part.show(box)
doScaleXYZ = self.doScaleXYZsum
if hasattr(obj, 'PreserveAspectRatio') and obj.PreserveAspectRatio and len(obj.Hullcurves) == 1:
bbox, doScaleXYZ = self._applyAspectRatio(obj, bbox, list(self.doScaleXYZsum))
return CurvedShapes.scaleByBoundbox(obj.Base.Shape, bbox, doScaleXYZ, copy=True)
def _applyAspectRatio(self, obj, bbox, doScaleXYZ):
basebbox = obj.Base.Shape.BoundBox
ax = obj.Axis
axabs = [abs(ax.x), abs(ax.y), abs(ax.z)]
sorted_abs = sorted(axabs, reverse=True)
if sorted_abs[0] - sorted_abs[1] < 0.1:
FreeCAD.Console.PrintWarning(translate("Curved Shapes", "PreserveAspectRatio: Axis is not clearly aligned with a coordinate axis — aspect ratio adjustment skipped.\n"))
return bbox, doScaleXYZ
primary = axabs.index(max(axabs))
cross_axes = [i for i in range(3) if i != primary]
constrained = [i for i in cross_axes if doScaleXYZ[i]]
unconstrained = [i for i in cross_axes if not doScaleXYZ[i]]
if len(constrained) != 1 or len(unconstrained) != 1:
return bbox, doScaleXYZ
c = constrained[0]
u = unconstrained[0]
base_lengths = [basebbox.XLength, basebbox.YLength, basebbox.ZLength]
bbox_lengths = [bbox.XLength, bbox.YLength, bbox.ZLength]
if base_lengths[c] <= epsilon:
return bbox, doScaleXYZ
scale_factor = bbox_lengths[c] / base_lengths[c]
base_mins = [basebbox.XMin, basebbox.YMin, basebbox.ZMin]
base_maxs = [basebbox.XMax, basebbox.YMax, basebbox.ZMax]
mins = [bbox.XMin, bbox.YMin, bbox.ZMin]
maxs = [bbox.XMax, bbox.YMax, bbox.ZMax]
new_length = base_lengths[u] * scale_factor
center = (base_mins[u] + base_maxs[u]) / 2
mins[u] = center - new_length / 2
maxs[u] = center + new_length / 2
doScaleXYZ[u] = True
return FreeCAD.BoundBox(mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]), doScaleXYZ
def execute(self, prop):
if prop.Base and prop.Axis == Vector(0.0,0.0,0.0):
prop.Axis = CurvedShapes.getNormal(prop.Base)
return
self.doScaleXYZ = []
self.doScaleXYZsum = [False, False, False]
sumbbox=None #Define the variable other wise it causes error
for h in prop.Hullcurves:
bbox = h.Shape.BoundBox
if h == prop.Hullcurves[0]:
sumbbox = bbox
else:
sumbbox.add(bbox)
doScale = [False, False, False]
if bbox.XLength > epsilon:
doScale[0] = True
if bbox.YLength > epsilon:
doScale[1] = True
if bbox.ZLength > epsilon:
doScale[2] = True
self.doScaleXYZ.append(doScale)
if sumbbox:
if sumbbox.XLength > epsilon:
self.doScaleXYZsum[0] = True
if sumbbox.YLength > epsilon:
self.doScaleXYZsum[1] = True
if sumbbox.ZLength > epsilon:
self.doScaleXYZsum[2] = True
if hasattr(prop, 'PreserveAspectRatio') and prop.PreserveAspectRatio and len(prop.Hullcurves) != 1:
FreeCAD.Console.PrintWarning(translate("Curved Shapes", "PreserveAspectRatio requires exactly one Hullcurve — ignored.\n"))
if (hasattr(prop,"Positions") and len(prop.Positions) != 0) or (prop.Items and prop.Base and hasattr(prop.Base, "Shape") and len(prop.Hullcurves) > 0):
self.makeRibs(prop)
return
def onChanged(self, fp, prop):
if not hasattr(fp, 'LoftMaxDegree'):
CurvedShapes.addObjectProperty(fp, "App::PropertyInteger", "LoftMaxDegree", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Max Degree for Surface or Solid"), init_val=5) # backwards compatibility - this upgrades older documents
if not hasattr(fp, 'MaxLoftSize'):
CurvedShapes.addObjectProperty(fp, "App::PropertyInteger", "MaxLoftSize", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Max Size of a Loft in Segments."), init_val=-1) # backwards compatibility - this upgrades older documents
if not hasattr(fp, 'KeepBase'):
CurvedShapes.addObjectProperty(fp, "App::PropertyEnumeration", "KeepBase", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Include the base shape unmodified and where"))
fp.KeepBase = ['None', 'First', 'Last']
fp.KeepBase = 'None'
if not hasattr(fp, 'PreserveAspectRatio'):
CurvedShapes.addObjectProperty(fp, "App::PropertyBool", "PreserveAspectRatio", "CurvedArray", QT_TRANSLATE_NOOP("App::Property", "Scale the Base shape uniformly based on the single Hullcurve, preserving its aspect ratio. Requires exactly one Hullcurve."), init_val=False)
if "Positions" in prop and len(fp.Positions) != 0:
setattr(fp,"Items",str(len(fp.Positions)))
outOfBounds = False
for p in fp.Positions:
if (p < 0.0 or p > 1.0):
outOfBounds = True
break
if outOfBounds:
FreeCAD.Console.PrintWarning(translate("Curved Shapes", "Some positions are out of bounds, should all be between 0.0 and 1.0, inclusive\n"))
#background compatibility
CurvedArrayWorker = CurvedArray
class CurvedArrayViewProvider:
def __init__(self, vobj):
vobj.Proxy = self
self.Object = vobj.Object
def getIcon(self):
return (os.path.join(CurvedShapes.get_module_path(), "Resources", "icons", "curvedArray.svg"))
def attach(self, vobj):
self.Object = vobj.Object
self.onChanged(vobj, "Base")
def claimChildren(self):
return [self.Object.Base] + self.Object.Hullcurves
def onDelete(self, feature, subelements):
return True
def onChanged(self, fp, prop):
pass
def loads(self, state):
return None
def dumps(self):
return None
def __getstate__(self):
return None
def __setstate__(self,state):
return None
if FreeCAD.GuiUp:
class CurvedArrayCommand():
def Activated(self):
FreeCADGui.doCommand("import CurvedShapes")
selection = FreeCADGui.Selection.getSelectionEx()
options = ""
for sel in selection:
if sel == selection[0]:
options += "Base=base, "
FreeCADGui.doCommand("base = FreeCAD.ActiveDocument.getObject('%s')"%(selection[0].ObjectName))
FreeCADGui.doCommand("hullcurves = []");
options += "Hullcurves=hullcurves, "
else:
FreeCADGui.doCommand("hullcurves.append(FreeCAD.ActiveDocument.getObject('%s'))"%(sel.ObjectName))
FreeCADGui.doCommand("CurvedShapes.makeCurvedArray(%sItems=4, OffsetStart=0, OffsetEnd=0, Surface=False)"%(options))
FreeCAD.ActiveDocument.recompute()
def IsActive(self):
"""Here you can define if the command must be active or not (greyed) if certain conditions
are met or not. This function is optional."""
#if FreeCAD.ActiveDocument:
return(True)
#else:
# return(False)
def GetResources(self):
return {'Pixmap' : os.path.join(CurvedShapes.get_module_path(), "Resources", "icons", "curvedArray.svg"),
'Accel' : "", # a default shortcut (optional)
'MenuText': QT_TRANSLATE_NOOP("CurvedArray", "Curved Array"),
'ToolTip' : __doc__}
FreeCADGui.addCommand('CurvedArray', CurvedArrayCommand())