/
BoxMaker.py
289 lines (224 loc) · 8.97 KB
/
BoxMaker.py
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
import adsk.core
import adsk.fusion
import traceback
import os
import sys
sys.path.append(os.path.dirname(__file__))
from BMLib import (
genFrontPoints,
genBackPoints,
genLeftPoints,
genRightPoints,
genBottomPoints,
genTopPoints,
)
# global set of event handlers to keep them referenced for the duration of the command
handlers = []
app = adsk.core.Application.get()
if app:
ui = app.userInterface
DEFAULT_WIDTH = '500 mm'
DEFAULT_HEIGHT = '300 mm'
DEFAULT_DEPTH = '400 mm'
DEFAULT_THICKNESS = '6 mm'
DEFAULT_COMPONENT = app.activeProduct.rootComponent
def buildAll(component, w, h, d, thickness):
buildFront(component, w, h, d, thickness)
buildBack(component, w, h, d, thickness)
buildLeft(component, w, h, d, thickness)
buildRight(component, w, h, d, thickness)
buildBottom(component, w, h, d, thickness)
buildTop(component, w, h, d, thickness)
def buildFront(component, w, h, d, thickness):
sketch = component.sketches.add(component.xYConstructionPlane)
sketchPoints(sketch, genFrontPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Front"
moveExt(component, e, 'z', d - thickness)
def buildBack(component, w, h, d, thickness):
sketch = component.sketches.add(component.xYConstructionPlane)
sketchPoints(sketch, genBackPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Back"
def buildLeft(component, w, h, d, thickness):
sketch = component.sketches.add(component.yZConstructionPlane)
sketchPoints(sketch, genLeftPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Left"
def buildRight(component, w, h, d, thickness):
sketch = component.sketches.add(component.yZConstructionPlane)
sketchPoints(sketch, genRightPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Right"
moveExt(component, e, 'x', w - thickness)
def buildBottom(component, w, h, d, thickness):
sketch = component.sketches.add(component.xZConstructionPlane)
sketchPoints(sketch, genBottomPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Bottom"
def buildTop(component, w, h, d, thickness):
sketch = component.sketches.add(component.xZConstructionPlane)
sketchPoints(sketch, genTopPoints(w, h, d, thickness))
e = extrudeSketch(component, sketch, thickness)
e.faces[0].body.name = "Top"
moveExt(component, e, 'y', h - thickness)
def moveExt(component, ext, axis, distance):
if axis not in ('x', 'y', 'z'):
raise ValueError("Axis must be one of x, y, z.")
entities1 = adsk.core.ObjectCollection.create()
entities1.add(ext.bodies.item(0))
# Create a transform to do move
transform = adsk.core.Matrix3D.create()
transform.translation = adsk.core.Vector3D.create(
distance if axis == 'x' else 0.0,
distance if axis == 'y' else 0.0,
distance if axis == 'z' else 0.0,
)
# Create a move feature
moveFeats = component.features.moveFeatures
moveFeatureInput = moveFeats.createInput(entities1, transform)
moveFeats.add(moveFeatureInput)
def sketchPoints(sketch, points):
lines = sketch.sketchCurves.sketchLines
points = list(points)
lastX, lastY = points[-1]
for (x, y) in points:
lines.addByTwoPoints(
adsk.core.Point3D.create(lastX, lastY, 0),
adsk.core.Point3D.create(x, y, 0),
)
lastX, lastY = x, y
def extrudeSketch(component, sketch, thickness):
# Get the profile defined by item#0.
prof = sketch.profiles.item(0)
# Create an extrusion feature
extrudes = component.features.extrudeFeatures
extInput = extrudes.createInput(
prof,
adsk.fusion.FeatureOperations.NewBodyFeatureOperation
)
# Define the extrude distance based on thickness
distance = adsk.core.ValueInput.createByReal(thickness)
extInput.setDistanceExtent(False, distance)
# Create the extrusion.
return extrudes.add(extInput)
class BoxMakerCommandExecuteHandler(adsk.core.CommandEventHandler):
def notify(self, args):
try:
unitsMgr = app.activeProduct.unitsManager
command = args.firingEvent.sender
inputs = {}
for input in command.commandInputs:
inputs[input.id] = input
# Ensure all inputs were provided
requiredInputs = ['widthInput', 'heightInput', 'depthInput', 'thicknessInput']
missingInputs = set(requiredInputs) - set(inputs.keys())
if missingInputs:
ui.messageBox("Missing inputs: {}".format(missingInputs))
return
# Get current design
design = app.activeProduct
if not design:
ui.messageBox('No active Fusion design', 'No Design')
return
if not inputs['componentInput'].value == '':
# Get the root component of the active design
rootComp = DEFAULT_COMPONENT
allOccs = rootComp.occurrences
transform = adsk.core.Matrix3D.create()
# Create a component under root component
occ1 = allOccs.addNewComponent(transform)
occ1.component.name = inputs['componentInput'].value
component=occ1.component
else:
component = DEFAULT_COMPONENT
# Built it!
buildAll(
component,
unitsMgr.evaluateExpression(inputs['widthInput'].expression, "mm"),
unitsMgr.evaluateExpression(inputs['heightInput'].expression, "mm"),
unitsMgr.evaluateExpression(inputs['depthInput'].expression, "mm"),
unitsMgr.evaluateExpression(inputs['thicknessInput'].expression, "mm")
)
args.isValidResult = True
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class BoxMakerCommandDestroyHandler(adsk.core.CommandEventHandler):
def notify(self, args):
try:
# when the command is done, terminate the script
# this will release all globals which will remove all event handlers
adsk.terminate()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class BoxMakerCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
def notify(self, args):
try:
cmd = args.command
onExecute = BoxMakerCommandExecuteHandler()
onDestroy = BoxMakerCommandDestroyHandler()
cmd.execute.add(onExecute)
cmd.destroy.add(onDestroy)
# keep the handler referenced globally
handlers.append(onExecute)
handlers.append(onDestroy)
cmd.commandInputs.addValueInput(
'widthInput',
'Width (mm)',
'mm',
adsk.core.ValueInput.createByString(DEFAULT_WIDTH)
)
cmd.commandInputs.addValueInput(
'heightInput',
'Height (mm)',
'mm',
adsk.core.ValueInput.createByString(DEFAULT_HEIGHT)
)
cmd.commandInputs.addValueInput(
'depthInput',
'Depth (mm)',
'mm',
adsk.core.ValueInput.createByString(DEFAULT_DEPTH)
)
cmd.commandInputs.addValueInput(
'thicknessInput',
'Wall Thickness',
'mm',
adsk.core.ValueInput.createByString(DEFAULT_THICKNESS)
)
cmd.commandInputs.addStringValueInput(
'componentInput',
'Component,empty for root',
''
)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def main():
try:
commandId = 'BoxMaker'
commandName = 'BoxMaker'
commandDescription = 'Create boxes with notched box-joint panels.'
cmdDef = ui.commandDefinitions.itemById(commandId)
if not cmdDef:
cmdDef = ui.commandDefinitions.addButtonDefinition(
commandId,
commandName,
commandDescription,
'./resources'
)
onCommandCreated = BoxMakerCommandCreatedHandler()
cmdDef.commandCreated.add(onCommandCreated)
# keep the handler referenced globally
handlers.append(onCommandCreated)
inputs = adsk.core.NamedValues.create()
cmdDef.execute(inputs)
# prevent this module from being terminated when the script returns,
# because we are waiting for event handlers to fire
adsk.autoTerminate(False)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
main()