def match_transform(src, dst):
"""Transform `src` to `dst`, taking worldspace into account
Arguments:
src (str): Absolute path to source transform
dst (str): Absolute path to destination transform
"""
try:
parent = cmds.listRelatives(src, parent=True)[0]
except Exception:
parent = None
node_decompose = cmds.createNode("decomposeMatrix")
node_multmatrix = cmds.createNode("multMatrix")
connections = {
dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]",
node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix",
node_decompose + ".outputTranslate": src + ".translate",
node_decompose + ".outputRotate": src + ".rotate",
node_decompose + ".outputScale": src + ".scale",
}
if parent:
connections.update({
parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]"
})
for s, d in connections.iteritems():
cmds.connectAttr(s, d, force=True)
cmds.refresh()
cmds.delete([node_decompose, node_multmatrix])
python类refresh()的实例源码
def rigUpdate(self):
#disable refresh until the rig update is complete
cmds.refresh(su=True)
rigNodeFound = False
try:
rigGuiNode = self.scene.sceneNodes["Rig"]
rigNodeFound = True
except KeyError:
rigNodeFound = False
if rigNodeFound:
#kill all script jobs created by controllers to avoid
#an update loop which the rig is updated
for jobNum in self.scriptJobNumbers:
if jobNum != globals.currentScriptJobNum:
cmds.scriptJob(k=jobNum)
self.scriptJobNumbers = []
rigGuiNode.updateVersion += 0.1
rootElem = self.recursiveGetXML(rigGuiNode)
self.indent(rootElem)
tree = xml.ElementTree(rootElem)
file = open(self.updateXmlPath, 'w')
tree.write(file)
file.close()
self.recursiveZeroOutControllers(rigGuiNode)
if rigGuiNode.metaNodeName is not None and rigGuiNode.metaNodeName != "":
self.rootNodeName = mel.eval("updateMetaDataManager -n \""+rigGuiNode.metaNodeName+"\";")
else:
self.rootNodeName = mel.eval("loadRig -p \""+self.updateXmlPath+"\";")
cmds.select(cl=True)
self.recursiveUpdateMetaNodes(rigGuiNode,self.rootNodeName)
self.recursiveSetupScriptJobs(rigGuiNode)
cmds.refresh(su=False)
def updateSelected(self):
current = self.rigList.currentItem()
if current is not None:
rigName = current.text()
name = "MRN_" + rigName
#disable refresh until the rig update is complete
cmds.refresh(su=True)
mel.eval(self.updateString)
cmds.select(cl=True)
#enable refresh after update
cmds.refresh(su=False)
self.refreshListWidget()
self.populateVersionBox(rigName)
self.updateSelectedBtn.setStyleSheet("")
def refresh():
cmds.refresh()
def refresh():
cmds.refresh()
def suspended_refresh():
"""Suspend viewport refreshes"""
try:
cmds.refresh(suspend=True)
yield
finally:
cmds.refresh(suspend=False)
def create_and_animate_trees():
"""
Function uses the create_palm() support function to create and animate some palm trees.
It was created to show how to create basic geometry objects, use instances and use modificators.
"""
palm1 = create_palm(diameter=1.3, segs_num=20, leafs_num=9, bending=34, id_num=1, anim_start=11, anim_end=26)
palm2 = create_palm(diameter=1.6, segs_num=20, leafs_num=9, bending=34, id_num=2, anim_start=40, anim_end=45)
palm3 = create_palm(diameter=1.1, segs_num=18, leafs_num=9, bending=24, id_num=3, anim_start=20, anim_end=35)
palm4 = create_palm(diameter=1.1, segs_num=24, leafs_num=9, bending=24, id_num=4, anim_start=25, anim_end=40)
cmds.currentTime(55) # The removal of history had strange effect when it was applied before tree animation
# Next line is intended to avoid a bug. If the history has to be deleted with a cmds.delete function. If it
# would not be modified then the bend modifictor would have to be moved wit an object or it would affect an object
# in different ways then desired during a changes in its position. The problem is, that during that an evaluation
# of commands may take some time and the removing of history resulted in not deformed mesh or a partialy
# deformed mesh. This is why cmds.refresh() ommand was used.
cmds.refresh(f=True)
cmds.delete(palm1, ch=True)
cmds.rotate(0.197, 105, 0.558, palm1, absolute=True) # Rotate the palm
cmds.move(-8.5, -4.538, 18.1, palm1, absolute=True) # Position the palm
cmds.parent(palm1, 'land', relative=True) # Rename it
cmds.delete(palm2, ch=True)
cmds.rotate(-16.935, 74.246, -23.907, palm2)
cmds.move(29.393, -3.990, 4.526, palm2)
cmds.parent(palm2, 'land', relative=True)
cmds.delete(palm3, ch=True)
cmds.move(24.498, -3.322, 36.057, palm3)
cmds.rotate(0.023, 0.248, -1.950, palm3)
cmds.parent(palm3, 'land', relative=True)
cmds.delete(palm4, ch=True)
cmds.move(4.353, -1.083, 22.68, palm4)
cmds.rotate(-150, -102.569, 872.616, palm4)
cmds.parent(palm4, 'land', relative=True)
def drag(self, *args):
'''
This is what is actually run during the drag, updating the coordinates and calling the
placeholder drag functions depending on which button is pressed.
'''
self.dragPoint = mc.draggerContext(self.draggerContext, query=True, dragPoint=True)
#if this doesn't work, try getmodifier
self.modifier = mc.draggerContext(self.draggerContext, query=True, modifier=True)
self.x = ((self.dragPoint[0] - self.anchorPoint[0]) * self.multiplier) + self.defaultValue
self.y = ((self.dragPoint[1] - self.anchorPoint[1]) * self.multiplier) + self.defaultValue
if self.minValue is not None and self.x < self.minValue:
self.x = self.minValue
if self.maxValue is not None and self.x > self.maxValue:
self.x = self.maxValue
#dragString
if self.modifier == 'control':
if self.button == 1:
self.dragControlLeft(*args)
elif self.button == 2:
self.dragControlMiddle(*args)
elif self.modifier == 'shift':
if self.button == 1:
self.dragShiftLeft(*args)
elif self.button == 2:
self.dragShiftMiddle(*args)
else:
if self.button == 1:
self.dragLeft()
elif self.button == 2:
self.dragMiddle()
mc.refresh()
def doEditPivotDriver(self, *args):
newValue = mc.floatSliderButtonGrp(self.floatSlider, query=True, value=True)
try:
mc.deleteUI(self.pivotDriverWindow)
except:
pass
currentValue = mc.getAttr(self.pivotDriver)
if newValue == currentValue:
return
oldRP = mc.getAttr(self.node+'.rotatePivot')[0]
mc.setAttr(self.pivotDriver, newValue)
newRP = mc.getAttr(self.node+'.rotatePivot')[0]
mc.setAttr(self.pivotDriver, currentValue)
parentPosition = mc.group(em=True)
offsetPosition = mc.group(em=True)
offsetPosition = mc.parent(offsetPosition, parentPosition)[0]
mc.setAttr(offsetPosition+'.translate', newRP[0]-oldRP[0], newRP[1]-oldRP[1], newRP[2]-oldRP[2])
mc.delete(mc.parentConstraint(self.node, parentPosition))
utl.matchBake(source=[self.node], destination=[parentPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False)
mc.cutKey(self.pivotDriver)
mc.setAttr(self.pivotDriver, newValue)
mc.refresh()
utl.matchBake(source=[offsetPosition], destination=[self.node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)
mc.delete(parentPosition)
def prepare_scene(path):
"""
The function sets the basic parameters of the scene: time range and render settings.
:param path: string - The directory with necessary files
"""
cmds.playbackOptions(min=0, max=260) # Set the animation range
cmds.autoKeyframe(state=False) # Make sure, that the AutoKey button is disabled
plugins_dirs = mel.getenv("MAYA_PLUG_IN_PATH") # Mental Ray plugin is necessaryfor this script to run propperly.
# Next lines check if the plugin is avaible and installs it or displays an allert window.
# The plugins are accualy files placed in "MAYA_PLUG_IN_PATH" directories, so this script gets those paths
# and checks if there is a mental ray plugin file.
for plugins_dir in plugins_dirs.split(';'):
for filename in glob.glob(plugins_dir + '/*'): # For every filename in every directory of MAYA_PLUG_IN_PATH
if 'Mayatomr.mll' in filename: # if there is a mental ray plugin file then make sure it is loaded
if not cmds.pluginInfo('Mayatomr', query=True, loaded=True):
cmds.loadPlugin('Mayatomr', quiet=True)
cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string') # Set the render engine to MR
# Next lines are a workaround for some bugs. The first one is that the render settings window has to be
# opened before setting attributes of the render. If it would not be, thhen Maya would display an error
# saying that such options do not exist.
# The second bug is that after running this scrpt the window was blank and it was impossible to set
# parameters. This is a common bug and it can be repaired by closing this window with
# cmds.deleteUI('unifiedRenderGlobalsWindow') command
cmds.RenderGlobalsWindow()
cmds.refresh(f=True)
cmds.deleteUI('unifiedRenderGlobalsWindow')
cmds.setAttr('miDefaultOptions.finalGather', 1)
cmds.setAttr('miDefaultOptions.miSamplesQualityR', 1)
cmds.setAttr('miDefaultOptions.lightImportanceSamplingQuality', 2)
cmds.setAttr('miDefaultOptions.finalGather', 1)
break
else:
continue
break
else:
print("Mental Ray plugin is not avaible. It can be found on the Autodesk website: ",
"https://knowledge.autodesk.com/support/maya/downloads/caas/downloads/content/",
"mental-ray-plugin-for-maya-2016.html")
alert_box = QtGui.QMessageBox()
alert_box.setText("Mental Ray plugin is not avaible. It can be found on the Autodesk website: " +
"https://knowledge.autodesk.com/support/maya/downloads/caas/downloads/content/" +
"mental-ray-plugin-for-maya-2016.html")
alert_box.exec_()
cam = cmds.camera(name="RenderCamera", focusDistance=35, position=[-224.354, 79.508, 3.569],
rotation=[-19.999,-90,0]) # create camera to set background (imageplane)
# Set Image Plane for camera background
cmds.imagePlane(camera=cmds.ls(cam)[1], fileName=(path.replace("\\", "/") + '/bg.bmp'))
cmds.setAttr("imagePlaneShape1.depth", 400)
cmds.setAttr("imagePlaneShape1.fit", 4)
def createCenterOfMass(*args):
'''
Create a center of mass node, and constrain it to the
character based on the selected root node.
'''
sel = mc.ls(sl=True)
if not len(sel) == 1:
raise RuntimeError('Please select the root control of your puppet.')
print 'Create Center Of Mass Node'
print '--------------------------'
meshes = meshesFromReference(sel[0]) or meshesFromHistory(sel[0])
if not meshes:
raise RuntimeError('Could not determine geomerty from selected control. Make sure geo is visible.')
mc.select(meshes)
mc.refresh()
print 'Discovered Meshes:'
for mesh in meshes:
print '\t',mesh
skinnedMeshes = []
for mesh in meshes:
if utl.getSkinCluster(mesh):
skinnedMeshes.append(mesh)
continue
hist = mc.listHistory(mesh, breadthFirst=True)
skins = mc.ls(hist, type='skinCluster')
if not skins:
warnings.warn('Could not find a skinned mesh affecting {}'.format(mesh))
continue
outGeo = mc.listConnections(skins[0]+'.outputGeometry[0]', source=False)
outGeo = mc.ls(outGeo, type=['mesh','transform'])
if not outGeo:
warnings.warn('Could not find a skinned mesh affecting {}'.format(mesh))
continue
skinnedMeshes.append(outGeo[0])
if not skinnedMeshes:
raise RuntimeError('Could not determine skinned geometry from selected control. This tool will only work if geo is skinned.')
locator = centerOfMassLocator(skinnedMeshes)
mc.addAttr(locator, longName=COM_ATTR, attributeType='message')
mc.connectAttr('.'.join((sel[0],'message')), '.'.join((locator,COM_ATTR)))
mc.select(sel)
return locator
def reset_pivot(*args):
sel = mc.ls(sl=True)
if not sel:
om.MGlobal.displayWarning('Nothing selected.')
return
if len(sel) > 1:
om.MGlobal.displayWarning('Only works on one node at a time.')
return
node = sel[0]
driver = None
driver_value = None
driver_default = None
if is_pivot_connected(node):
driver = pivot_driver_attr(node)
if driver:
dNode,dAttr = driver.split('.',1)
driver_value = mc.getAttr(driver)
driver_default = mc.attributeQuery(dAttr, node=dNode, listDefault=True)[0]
if driver_default == driver_value:
return
else:
om.MGlobal.displayWarning('Pivot attribute is connected, unable to edit.')
return
if not driver:
pivotPosition = mc.getAttr(node+'.rotatePivot')[0]
if pivotPosition == (0.0,0.0,0.0):
return
tempPosition = mc.group(em=True)
tempPivot = mc.group(em=True)
tempPivot = mc.parent(tempPivot, node)[0]
if driver:
mc.setAttr(driver, driver_default)
newRP = mc.getAttr(node+'.rotatePivot')[0]
mc.setAttr(driver, driver_value)
mc.setAttr(tempPivot+'.translate', *newRP)
else:
mc.setAttr(tempPivot+'.translate', 0,0,0)
mc.setAttr(tempPivot+'.rotate', 0,0,0)
utl.matchBake(source=[tempPivot], destination=[tempPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)
if driver:
mc.setAttr(driver, driver_default)
else:
mc.setAttr(node+'.rotatePivot', 0,0,0)
mc.refresh()
utl.matchBake(source=[tempPosition], destination=[node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)
mc.delete(tempPosition,tempPivot)
mc.select(node)