-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPiston_plugin.py
414 lines (345 loc) · 14.8 KB
/
Piston_plugin.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
from maya.api import OpenMaya
import math
import pymel.core as pm
import importlib
import sys
import Piston_UI
maya_useNewAPI = True
# This Plugin is an auto-rig for pistons movements,
# I created it to exercise myself with python / pymel / OpenMaya scripting.
# Here are declared the commands to generate the rig, and some custom utility nodes.
# In order to avoid conflict with other utility plugins the nodes are prefixed with "piston".
# I will maybe add, in the future, "legacy" commands that doesnt use the plugin nodes and therefore doesnt create
# a dependency to this plug-in.
# Author : Baptiste Fraboul
def buildEffectorJoints(start, end):
start_joint = pm.PyNode(start)
end_joint = pm.PyNode(end)
start_pos = (pm.getAttr(start_joint.translateX),
pm.getAttr(start_joint.translateY),
pm.getAttr(start_joint.translateZ))
end_pos = pm.xform(end_joint, q=True, t=True, ws=True)
pm.select(cl=True)
effector_start = pm.joint(name='TranslationStartJoint', p=start_pos)
effectort_end = pm.joint(name='TranslateEndJoint', p=end_pos)
pm.joint(effector_start, edit=True, oj='xyz', sao='yup')
pm.joint(effectort_end, edit=True, o=(0, 0, 0))
return effector_start, effectort_end
def doPistonGraph(base_joint, crank_end_joint, shaft_end_joint, effector_end):
axis = [
'translateX',
'translateY',
'translateZ'
]
angle_between_inputs = [
'.vector1X',
'.vector1Y',
'.vector1Z'
]
vector_inputs = [
'.input_x',
'.input_y',
'.input_z'
]
solver = pm.createNode('pistonNode', name='pistonSolver')
offset_angle = pm.createNode('angleBetween', name='offsetWithCrankEnd')
neutral_rot = pm.createNode('addDoubleLinear', name='rotateToNeutralPoint')
shaft_length = pm.createNode('pistonVectorLength', name='shaftLength')
crank_length = pm.createNode('pistonVectorLength', name='crankLength')
plus_minus = pm.createNode('plusMinusAverage', name='substractOffset')
for i in range(0, 3):
crank_end_joint.attr(axis[i]).connect(crank_length + vector_inputs[i])
shaft_end_joint.attr(axis[i]).connect(shaft_length + vector_inputs[i])
crank_end_joint.attr(axis[i]).connect(offset_angle.vector1 + angle_between_inputs[i])
base_joint.rotateZ.connect(plus_minus.input1D[0])
offset_angle.euler.eulerZ.connect(plus_minus.input1D[1])
# plus_minus.operation.set(2)
plus_minus.output1D.connect(neutral_rot.input1)
neutral_rot.input2.set(90)
neutral_rot.output.connect(solver.inputAngle)
shaft_length.output.connect(solver.shaftLength)
crank_length.output.connect(solver.crankLength)
solver.output.connect(effector_end.translateX)
class pistonVectorLengthNode(OpenMaya.MPxNode):
'''A node that return the length of a given vector'''
type_id = OpenMaya.MTypeId(0x900FF)
type_name = 'pistonVectorLength'
input_x = None
input_y = None
input_z = None
output = None
def __init__(self):
OpenMaya.MPxNode.__init__(self)
@classmethod
def creator(cls):
return cls()
@classmethod
def initialize(cls):
print('Plugin init : {} '.format(pistonVectorLengthNode.type_name))
numeric_attribute = OpenMaya.MFnNumericAttribute()
cls.input_x = numeric_attribute.create(
'input_x',
'x',
OpenMaya.MFnNumericData.kFloat
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_x)
cls.input_y = numeric_attribute.create(
'input_y',
'y',
OpenMaya.MFnNumericData.kFloat
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_y)
cls.input_z = numeric_attribute.create(
'input_z',
'z',
OpenMaya.MFnNumericData.kFloat
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_z)
cls.output = numeric_attribute.create(
'Output', # longname
'output', # shortname
OpenMaya.MFnNumericData.kFloat # attribute type
)
numeric_attribute.readable = True
numeric_attribute.writable = False
cls.addAttribute(cls.output)
cls.attributeAffects(cls.input_x, cls.output)
cls.attributeAffects(cls.input_y, cls.output)
cls.attributeAffects(cls.input_z, cls.output)
def compute(self, plug, datablock):
if plug == self.output:
inputX = datablock.inputValue(self.input_x).asFloat()
inputY = datablock.inputValue(self.input_y).asFloat()
inputZ = datablock.inputValue(self.input_z).asFloat()
result = math.sqrt(math.pow(inputX,2) + (math.pow(inputY,2))+ (math.pow(inputZ,2)))
output_handle = datablock.outputValue(self.output)
output_handle.setFloat(result)
output_handle.setClean()
class pistonNode(OpenMaya.MPxNode):
''' New solver for piston rig'''
type_id = OpenMaya.MTypeId(0x00000001)
type_name = 'pistonNode'
# Attribute
input_crank_length = None
input_shaft_length = None
input_angle = None
output = None
def __init__(self):
OpenMaya.MPxNode.__init__(self)
@classmethod
def creator(cls):
'''Create a node instance'''
return cls()
@classmethod
def initialize(cls):
'''Create plugin attributes with dependencies'''
print('Plugin init : {} '.format(pistonNode.type_name))
# Type of attribute to create
numeric_attribute = OpenMaya.MFnNumericAttribute()
# first attribute of the node
cls.input_crank_length = numeric_attribute.create(
'crankLength', # longname
'crank_l', # shortname
OpenMaya.MFnNumericData.kFloat # attribute type
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_crank_length)
# second attribute of the node
cls.input_shaft_length = numeric_attribute.create(
'shaftLength', # longname
'shaft_l', # shortname
OpenMaya.MFnNumericData.kFloat # attribute type
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_shaft_length)
# third attribute of the node
cls.input_angle = numeric_attribute.create(
'inputAngle', # longname
'input_angle', # shortname
OpenMaya.MFnNumericData.kFloat # attribute type
)
numeric_attribute.readable = False
numeric_attribute.writable = True
numeric_attribute.keyable = True
cls.addAttribute(cls.input_angle)
# output attribute of the node
cls.output = numeric_attribute.create(
'Output', # longname
'output', # shortname
OpenMaya.MFnNumericData.kFloat # attribute type
)
numeric_attribute.readable = True
numeric_attribute.writable = False
cls.addAttribute(cls.output)
# add dependencies
cls.attributeAffects(cls.input_angle, cls.output)
cls.attributeAffects(cls.input_shaft_length, cls.output)
cls.attributeAffects(cls.input_crank_length, cls.output)
def compute(self, plug, data_block):
'''
COpenMayapute the output of the node
:param plug: MPlug representing the attributes to recOpenMayapute
:param data_block: MDataBlockis the storage of datas for the node's attribute
:return:
'''
if plug == self.output:
angle_value = data_block.inputValue(self.input_angle).asFloat() + 90
shaft_length_value = data_block.inputValue(self.input_shaft_length).asFloat()
crank_length_value = data_block.inputValue(self.input_crank_length).asFloat()
piston_move = math.sin(math.radians(angle_value)) * crank_length_value + math.sqrt(
pow(shaft_length_value, 2) - pow(math.cos(math.radians(angle_value )), 2) * pow(crank_length_value, 2))
# get the output handdle, set its new value and set it as clean
output_handle = data_block.outputValue(self.output)
output_handle.setFloat(piston_move)
output_handle.setClean()
class legacyPistonLength(OpenMaya.MPxCommand):
"""
Generate a tree graph that output the length of a vector-type unit (rotation, translation, color etc.) using
only maya regular nodes. Work in progress
"""
kPluginCmdName = 'legacyPistonLengthTree'
def __init__(self):
OpenMaya.MPxCommand.__init__(self)
@classmethod
def cmdCreator(cls):
return legacyPistonLength()
def doIt(self, args):
print("This does nothing work in progress")
class generatePiston(OpenMaya.MPxCommand):
"""
This command generate the node tree for a piston after selecting start and end joint.
It does use the custom nodes created with this pugin
"""
kPluginCmdName = 'generatePiston'
def __init__(self):
OpenMaya.MPxCommand.__init__(self)
@classmethod
def cmdCreator(cls):
return generatePiston()
def doIt(self, args):
# get selection
selection = pm.ls(selection=True, type='joint')
# test if selected is a joint and that it has only 2 children that are also joints
if selection:
print(pm.nodeType(selection[0]))
if len(selection) == 2 and pm.nodeType(selection[0]) == 'joint':
base_joint = selection[0]
direct_child = pm.listRelatives(base_joint, type='joint')
base_joint.setAttr('displayLocalAxis', True)
if len(direct_child) == 1:
base_joint.rotateX.unlock()
base_joint.rotateY.unlock()
shaft_end = selection[1]
print('shaft_end joint = {}'.format(shaft_end))
crank_end = direct_child[0]
print('crank_end joint = {}'.format(crank_end))
pm.parent((base_joint, shaft_end, crank_end), world=True)
# do the aim constraint to properly align basejoint to children
temp_constraint = pm.aimConstraint(shaft_end, base_joint, worldUpType='object',
worldUpObject=crank_end)
pm.refresh()
pm.delete(temp_constraint)
effector_start, effector_end = buildEffectorJoints(base_joint, shaft_end)
pm.delete(shaft_end)
pm.select(clear=True)
start_pos = pm.xform(effector_end, q=True, t=True, ws=True)
end_pos = pm.xform(crank_end, q=True, t=True, ws=True)
shaft_start = pm.joint(name='shaft_start_joint', p=end_pos)
shaft_end = pm.joint(name='shaft_end_joint', p=start_pos)
pm.aimConstraint(crank_end, shaft_end)
pm.parent(shaft_end, effector_end)
pm.parent(shaft_start, shaft_end)
root_joint = pm.duplicate(base_joint, name='Root_joint')[0]
root_joint.radius.set(2 * base_joint.radius.get())
pm.parent(effector_start, root_joint)
pm.parent(base_joint, root_joint)
pm.makeIdentity(base_joint, apply=True)
pm.parent(crank_end, base_joint)
doPistonGraph(base_joint, crank_end, shaft_start, effector_end)
base_joint.rotateX.lock()
base_joint.rotateY.lock()
pm.select(base_joint, replace = True)
else:
OpenMaya.MGlobal.displayError('First joint must have only children to generate piston rig')
else:
OpenMaya.MGlobal.displayError('You must select only 2 joint : start and end joints')
# no selection
else:
OpenMaya.MGlobal.displayError('Empty selection')
def initializePlugin(plugin):
'''
Called when the plugin is initialized
:param Plugin: MObject the plugin to initialize
:return:
'''
plugin_fn = OpenMaya.MFnPlugin(plugin, 'Baptiste Fraboul', '0.0.1')
try :
Piston_UI.generate_shelf()
except :
print(r'Couldn\'t create UI')
try:
plugin_fn.registerCommand(generatePiston.kPluginCmdName,
generatePiston.cmdCreator)
except :
OpenMaya.MGlobal.displayError('Failed to initialize command : {}'.format(generatePiston.kPluginCmdName))
raise
try :
plugin_fn.registerNode(
pistonNode.type_name,
pistonNode.type_id,
pistonNode.creator,
pistonNode.initialize,
OpenMaya.MPxNode.kDependNode
)
except:
print('Failed to initialize the plugin : {} !'.format(pistonNode.type_name))
raise
try :
plugin_fn.registerNode(
pistonVectorLengthNode.type_name,
pistonVectorLengthNode.type_id,
pistonVectorLengthNode.creator,
pistonVectorLengthNode.initialize,
OpenMaya.MPxNode.kDependNode
)
except :
print('Failed to initialize the plugin : {} !'.format(pistonVectorLengthNode.type_name))
raise
def uninitializePlugin(plugin):
'''
Called when the plugin is unloaded in Maya
:param plugin: the MObject plugin to uninitialize
:return:
'''
plugin_fn = OpenMaya.MFnPlugin(plugin)
# We completely unload modules to avoid error
try :
for module in sys.modules.copy():
if module.startswith('Piston_UI'):
del sys.modules[module]
except :
print('Cant\'t delete module Piston_UI')
try :
pm.deleteUI('Piston_plugin')
except :
print("Can't delete UI")
try:
plugin_fn.deregisterCommand(generatePiston.kPluginCmdName)
plugin_fn.deregisterNode(pistonVectorLengthNode.type_id)
plugin_fn.deregisterNode(pistonNode.type_id)
except:
print('Failed to uninitialize the plugin : {} !'.format(pistonNode.type_name))
raise