def create_preset(self): ''' # creates the file for the preset ****** # file pattern # data = ['preset name', 'light type', 'description', xform_attrs[], shape_attrs[]] ****** ''' sel = pm.ls(selection= True)[0] sel_shape = sel.getShape() node_type = pm.nodeType(sel_shape) if 'Light' not in node_type: return data = [] data.append('%s' % (self.field.getText())) data.append('%s' % (node_type)) data.append('%s' % (self.scroll.getText())) sel_data = [] sel_shape_data = [] sel_attrs = pm.listAttr(sel) sel_shape_attrs = pm.listAttr(sel_shape) for attr in sel_attrs: try : value = pm.getAttr('%s.%s' % (sel, attr)) temp_data = (attr , value) sel_data.append(temp_data) except: pass for attr in sel_shape_attrs: try: value = pm.getAttr('%s.%s' % (sel_shape, attr)) temp_data = (attr , value) sel_shape_data.append(temp_data) except: pass data.append(sel_data) data.append(sel_shape_data) name ='%s.light' % (self.field.getText()) full_path = os.path.join(self.path, name) f = open(full_path, 'w') pickle_data = pickle.dump(data, f) f.close() preset_ui() # this will list will update the preset section
def ChangeNumberOfJoints(self, *args): self.blueprint_UI_instance.DeleteScriptJob() # Collect information from current spline module joints = self.GetJoints() numJoints = len(joints) newNumJoints = pm.intField(self.numberOfJointsField, query = True, value = True) startPos = pm.xform(self.GetTranslationControl(joints[0]), query = True, worldSpace = True, translation = True) endPos = pm.xform(self.GetTranslationControl(joints[numJoints - 1]), query = True, worldSpace = True, translation = True) hookObj = self.FindHookObjectForLock() rotateOrder = pm.getAttr("%s.rotateOrder" %joints[0]) sao_local = pm.getAttr("%s:module_grp.sao_local" %self.moduleNamespace) sao_world = pm.getAttr("%s:module_grp.sao_world" %self.moduleNamespace) # Delete current spline module self.Delete() # Create new spline module with new joint count newInstance = Spline(self.userSpecifiedName, hookObj, newNumJoints, startPos, endPos) newInstance.Install() # Apply previous attribute values newJoints = newInstance.GetJoints() pm.setAttr("%s.rotateOrder" %newJoints[0], rotateOrder) pm.setAttr("%s:module_grp.sao_local" %newInstance.moduleNamespace, sao_local) pm.setAttr("%s:module_grp.sao_world" %newInstance.moduleNamespace, sao_world) self.blueprint_UI_instance.CreateScriptJob() pm.select("%s:module_transform" %newInstance.moduleNamespace, replace = True)
def transImgPlnDp(): #comfirmDialog for checking if ImgPln in the scene allTransNd = pm.ls(type='transform',fl=True) isImgPln = [] for trans in allTransNd: if trans == 'ImagePlane_Parent_Loc': isImgPln.append(trans) if len(isImgPln) == 0: cfmAnswer = pm.confirmDialog( title='Confirm', message='Create New Image Plane?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if cfmAnswer == 'Yes': createImgPln() elif len(isImgPln) >= 1: camDp = -pm.getAttr(curCam+'.translateZ') imgPlnScale = pm.getAttr(ImgPln[0]+'.s') if pm.getAttr(ImgPln[0]+'.translateZ') == (camDp)*0.01: pm.setAttr(ImgPln[0]+'.translateX',0) pm.setAttr(ImgPln[0]+'.translateY',0) pm.setAttr(ImgPln[0]+'.translateZ',(camDp)*0.1) pm.setAttr(ImgPln[0]+'.s',1,1,1) elif pm.getAttr(ImgPln[0]+'.translateZ') == (camDp)*0.1: pm.setAttr(ImgPln[0]+'.translateX',0) pm.setAttr(ImgPln[0]+'.translateY',0) pm.setAttr(ImgPln[0]+'.translateZ',(camDp)*0.01) pm.setAttr(ImgPln[0]+'.s',0.2,0.2,0.2) else: pm.setAttr(ImgPln[0]+'.translateX',0) pm.setAttr(ImgPln[0]+'.translateY',0) pm.setAttr(ImgPln[0]+'.translateZ',(camDp)*0.1) pm.setAttr(ImgPln[0]+'.s',1,1,1)
def dpaf_outputsFix(self, layer): """fix image output path if renderer is vray :param layer: maya renderLayer name :return outputs_Fixed: correct image output path """ outputs_Fixed = '' currentRenderer = pm.PyNode('defaultRenderGlobals').getAttr('currentRenderer') # get current maya image format setting tmp_OutFormatControl = pm.getAttr('defaultRenderGlobals.outFormatControl') if currentRenderer == 'vray' else '' imgPrefix_vray = pm.getAttr('vraySettings.fileNamePrefix') if currentRenderer == 'vray' else '' imgPrefix_maya = pm.getAttr('defaultRenderGlobals.imageFilePrefix') if currentRenderer == 'vray' else '' imageFormatStr = ('.' + ('png' if not pm.getAttr('vraySettings.imageFormatStr') else pm.getAttr('vraySettings.imageFormatStr'))) if currentRenderer == 'vray' else '' if currentRenderer == 'vray': # change current setting for fixing vray output path pm.setAttr('defaultRenderGlobals.outFormatControl', 1) pm.setAttr('defaultRenderGlobals.imageFilePrefix', imgPrefix_vray if imgPrefix_vray else '', type= 'string') if imgPrefix_vray else None # write output path outputs_Fixed = pm.renderSettings(layer= layer, fullPath= 1, firstImageName= 1, lastImageName= 1) outputs_Fixed[0] = os.path.normpath(outputs_Fixed[0]) + imageFormatStr outputs_Fixed[1] = os.path.normpath(outputs_Fixed[1]) + imageFormatStr outputs_Fixed = ','.join(outputs_Fixed) if currentRenderer == 'vray': # restore previous setting for good pm.setAttr('defaultRenderGlobals.imageFilePrefix', imgPrefix_maya if imgPrefix_maya else '', type= 'string') if imgPrefix_vray else None pm.setAttr('defaultRenderGlobals.outFormatControl', tmp_OutFormatControl) return outputs_Fixed
def writeRetimeFile(viz, pubShot): ''' Write the animated data on the currentTime attribute to a txt file. ''' tmpPath = None # Return None if the attribute is not keyed. if pm.keyframe('%s.currentTime'%viz, query=True, keyframeCount=True): # get framelist from pod podFile = str(pm.getAttr('%s.podFile'%viz)) ggcp = GtoGeometryCachePod.fromPodFile(podFile) ggcp.startFrame = pm.playbackOptions(q=True, animationStartTime=True) ggcp.endFrame = pm.playbackOptions(q=True, animationEndTime=True) frameList = ggcp.frameNumberList() # offset = float(pm.getAttr('%s.timeOffset'%viz)) # frameList = [frame + offset for frame in ggcp.frameNumberList()] # Get curve data animCurveData = list() for frame in frameList: value = pm.keyframe(viz, query=True, time=[frame], attribute='currentTime', eval=True) assert len(value) == 1, '%s keyframes found for time %s. One expected.' % (len(value), frame) animCurveData.append([frame, value[0]]) # Write it out to a temp file selCharName = str(pm.getAttr('%s.label'%viz)) if not tmpPath: name = '_'.join(['animLib', 'bd', pubShot, selCharName, 'retime.txt']) tmpPath = os.path.join(tempfile.gettempdir(), name) fh = open(tmpPath, 'w') for time, value in animCurveData: fh.write('%s %s\n' % (time, value)) fh.close() return tmpPath
def SetupModuleSpecificControls(self): currentlySelectedModuleInfo = pm.textScrollList(self.UIElements["animationModule_textScroll"], query = True, selectItem = True) currentlySelectedModuleNamespace = None if len(currentlySelectedModuleInfo) != 0: currentlySelectedModuleNamespace = currentlySelectedModuleInfo[0] if currentlySelectedModuleNamespace == self.previousAnimationModule and self.selectedBlueprintModule == self.previousBlueprintModule: return existingControls = pm.columnLayout(self.UIElements["moduleSpecificControlsColumn"], query = True, childArray = True) if existingControls != None: pm.deleteUI(existingControls) pm.button(self.UIElements["matchingButton"], edit = True, enable = False) pm.setParent(self.UIElements["moduleSpecificControlsColumn"]) moduleNameInfo = utils.FindAllModuleNames("/Modules/Animation") modules = moduleNameInfo[0] moduleNames = moduleNameInfo[1] if len(currentlySelectedModuleInfo) != 0: currentlySelectedModule = currentlySelectedModuleNamespace.rpartition("_")[0] if currentlySelectedModule in moduleNames: moduleWeightValue = pm.getAttr("%s:SETTINGS.%s_weight" %(self.selectedBlueprintModule, currentlySelectedModuleNamespace)) matchButtonEnable = moduleWeightValue > 0.0001 moduleIndex = moduleNames.index(currentlySelectedModule) module = modules[moduleIndex] pm.attrControlGrp(attribute = "%s:%s:module_grp.levelOfDetail" %(self.selectedBlueprintModule, currentlySelectedModuleNamespace), label = "Module LOD") mod = __import__("Animation.%s" %module, (), (), [module]) reload(mod) moduleClass = getattr(mod, mod.CLASS_NAME) moduleInst = moduleClass("%s:%s" %(self.selectedBlueprintModule, currentlySelectedModuleNamespace)) moduleInst.UI(self.UIElements["moduleSpecificControlsColumn"]) self.UIElements["moduleSpecificControls_preferenceFrame"] = pm.frameLayout(borderVisible = False, label = "preferences", collapsable = True, parent = self.UIElements["moduleSpecificControlsColumn"]) self.UIElements["moduleSpecificControls_preferenceColumn"] = pm.columnLayout(columnAttach = ["both", 5], adjustableColumn = True, parent = self.UIElements["moduleSpecificControls_preferenceFrame"]) pm.attrControlGrp(attribute = "%s:%s:module_grp.iconScale" %(self.selectedBlueprintModule, currentlySelectedModuleNamespace), label = "Icon Scale") value = pm.getAttr("%s:%s:module_grp.overrideColor" %(self.selectedBlueprintModule, currentlySelectedModuleNamespace)) + 1 self.UIElements["iconColor"] = pm.colorIndexSliderGrp(label = "Icon Color", maxValue = 32, value = value, changeCommand = partial(self.IconColor_callback, currentlySelectedModuleNamespace), parent = self.UIElements["moduleSpecificControls_preferenceColumn"]) moduleInst.UI_preferences(self.UIElements["moduleSpecificControls_preferenceColumn"]) pm.button(self.UIElements["matchingButton"], edit = True, enable = matchButtonEnable, command = moduleInst.Match) self.previousBlueprintModule = self.selectedBlueprintModule self.previousAnimationModule = currentlySelectedModuleNamespace
def create_jointChain( IdName = 'joint', inputCurve = pm.selected(), orientation = 'xyz' ): # get number of CVs on InputCurve numberOfCvs = pm.getAttr( inputCurve[0] + '.cp',s=1 ) # create joints on world space cv locations Jnts = [] for i in range(0, numberOfCvs): pm.select( clear = True ) currentCvPos = pm.pointPosition( inputCurve[0].cv[i], w=1 ) Jnt = pm.joint( name = '_'.join( ['bn', IdName, str( i+1 )] ) ) pm.xform( Jnt, t = currentCvPos ) Jnts.append( Jnt ) # create end joint pm.select( clear = True ) endJntPos = 0.1 * ( pm.getAttr( Jnts[len(Jnts)-1].translate ) - pm.getAttr( Jnts[len(Jnts)-2].translate ) ) + pm.getAttr( Jnts[len(Jnts)-1].translate ) endJnt = pm.joint( name = 'be_' + IdName, position = endJntPos, a = True ) Jnts.append( endJnt ) # set aim and orientation vectors, always yup aimDict = {} aimDict[orientation[0]] = 1 aimDict[orientation[1]] = 0 aimDict[orientation[2]] = 0 aimVec = ( aimDict['x'], aimDict['y'], aimDict['z'] ) orientDict = {} orientDict[orientation[0]] = 0 orientDict[orientation[1]] = 0 orientDict[orientation[2]] = 1 orientVec = ( orientDict['x'], orientDict['y'], orientDict['z'] ) # orient first joint JntAimConstrain = pm.aimConstraint( Jnts[1], Jnts[0], aimVector = aimVec, upVector = (0,1,0), worldUpType = "scene" ) pm.delete( JntAimConstrain ) Jnts[0].jointOrient.set( Jnts[0].rotate.get() ) Jnts[0].rotate.set( 0,0,0 ) # orient middle joints for i in range( 1, len( Jnts ) - 1 ): JntAimConstrain = pm.aimConstraint( Jnts[i+1], Jnts[i], aimVector = aimVec, upVector = orientVec, worldUpType = "objectrotation", worldUpVector = orientVec, worldUpObject = Jnts[i-1] ) pm.delete( JntAimConstrain ) Jnts[i].jointOrient.set( Jnts[i].rotate.get() ) Jnts[i].rotate.set( 0,0,0 ) # orient last joint Jnts[len( Jnts ) -1 ].jointOrient.set( Jnts[len( Jnts ) -2 ].jointOrient.get() ) # parent joints for i in range( 1, len( Jnts ) ): pm.parent( Jnts[i], Jnts[i-1], absolute = True) pm.select( Jnts[0] ) print('Successfully created and oriented joint-chain. Continuing...') return Jnts
def matchPos(src="", args=[], type=1, ws=True, silent=True): """ Function: takes a source and matches its position to the args Args = src=string/PyNode, args=list of strings/PyNodes, type=int, ws=boolean State: type=1: parentConstraint solution type=2: PyNode transform solution type=3: string transform solution type=4: xform -w solution ws=world space if true, object if false Returns: None Example Usage: matchPos(type=4,sel=True,ws=False) """ # store the seleciton as arguments if sel==True if args == []: sel = pm.ls(sl=True) if len(sel) <= 1: pm.error("Not enough objects selected numbskull") args = sel[1:] src = sel[0] if not silent: print "Positioning %s\nOn object %s" % (",".join(map(str, args)), src) # convert all the list to PyNodes if type==2 if type == 2: if isinstance(src, basestring): src = pm.PyNode(src) count = 0 for arg in args: if isinstance(arg, basestring): args[count] = pm.PyNode(arg) count += 1 # otherwise get on to the matching! for tgt in args: if type == 1: pc = pm.parentConstraint(src, tgt) pm.delete(pc) if type == 2: tgt.t.set(src.t.get()) tgt.r.set(src.r.get()) tgt.s.set(src.s.get()) if type == 3: pm.setAttr((tgt + ".t"), pm.getAttr(src + "t")) pm.setAttr((tgt + ".r"), pm.getAttr(src + "r")) pm.setAttr((tgt + ".s"), pm.getAttr(src + "s")) if type == 4: pm.xform( tgt, t=pm.xform(src, t=True, q=True, ws=ws), ro=pm.xform(src, ro=True, q=True, ws=ws), s=pm.xform(src, s=True, q=True, ws=ws), ) if type == 5: attrs = [] for attr in ["tx", "ty", "tz"]: if tgt.attr(attr).isLocked(): attrs.append(attr[1]) pm.delete(pm.pointConstraint(src, tgt, skip=attrs))
def create( self ): # # Create Kinect2 Joints # aimer = [] for kjot in self.k2map: tag = self.k2map[kjot][0] aimid = self.k2map[kjot][2] aim = None if aimid is None else self.k2map[aimid][0] aimv = (1,0,0) t = pm.xform( tag, q=True, ws=True, t=True ) pm.select( cl=True ) pm.joint( p=t, n=kjot ) if not aim is None: aimv = (-1,0,0) if pm.getAttr(aim+'.tx') < 0 else aimv aimer.append(pm.aimConstraint( aim, kjot, aim=aimv, wut='objectrotation', u=(0,1,0), wu=(0,1,0), wuo=tag )) pm.delete( aimer ) # # Make Joints Hierarchy # for kjot in self.k2map: parent = self.k2map[kjot][1] aimid = self.k2map[kjot][2] if not parent is None: pm.parent( kjot, self.k2map[kjot][1] ) if aimid is None: pm.setAttr( kjot+'.jointOrient', (0,0,0) ) # Freeze Transformations pm.makeIdentity( kjot, a=True, jo=False, t=False, r=True, s=False, n=0, pn=True ) # # Make Constraint # for kjot in self.k2map: tag = self.k2map[kjot][0] aimid = self.k2map[kjot][2] aim = None if aimid is None else self.k2map[aimid][0] aimv = (1,0,0) # Aim Constraint pm.pointConstraint( tag, kjot ) # Aim Constraint if not aim is None: aimv = (-1,0,0) if pm.getAttr(aim+'.tx') < 0 else aimv pm.aimConstraint( aim, kjot, aim=aimv, wut='objectrotation', u=(0,1,0), wu=(0,1,0), wuo=tag ) return
def update_velocity_grid_export(self, param_name): grp = "OpenVDBVelocityGrids" attr_value = pm.getAttr(param_name) pm.textFieldGrp(grp, edit=True, text="" if attr_value is None else attr_value, changeCommand=lambda val: pm.setAttr(param_name, val)) pm.scriptJob(parent=grp, replacePrevious=True, attributeChange=[param_name, lambda: pm.textFieldGrp(grp, edit=True, text=pm.getAttr(param_name))]) self.setup_velocity_grid_popup(grp, param_name)
def cbsStart(*args, **kwargs): base = kwargs.setdefault('base', pm.ls(sl=True)[0]) # (string) The base model for the character shape = kwargs.setdefault('shape') # (string) The shape node of the base model tweak = kwargs.setdefault('tweak') # (string) The tweak node of the base model that is being skinned skin = kwargs.setdefault('skin') # (string) The skinCluster node that is driving the base model #gather some info base, shape, tweak, skin = gatherInfo(base, shape, tweak, skin) verts = pm.polyEvaluate(base, v=True) #do a quick check to make sure this part hasn't been done before if base.hasAttr('baseTransform'): pm.error('You have already run the "Start" function on this model, so it is already ready to go.' + 'If corrections have already been made, click "Extract Shape to finish the process"') for i in pm.listHistory(base, lv=1): if i.type() == 'polySmoothFace': pm.error('The selected shape is connected to a smooth modifier. This hinders the ability to track edits. %s must be deleted.' % i) #turn off a couple things that might mess with things pm.symmetricModelling(e=True, symmetry= False) pm.softSelect(e=True, softSelectEnabled=False) for i in range(verts): x = pm.getAttr(('%s.vlist[0].vertex[%i].xVertex'%(tweak, i))) y = pm.getAttr(('%s.vlist[0].vertex[%i].yVertex'%(tweak, i))) z = pm.getAttr(('%s.vlist[0].vertex[%i].zVertex'%(tweak, i))) if not (x+y+z) == 0: pm.error('You have used the tweak node. No me gusta. If you really wanna clear it, run clearTweaks and try again. It will save what you have') #ok, let's get started, first instance the original mesh sculptTrans = pm.instance(base, n=('%s_corrective_sculpt'%base))[0] pm.reorderDeformers(skin, tweak, base) pm.setAttr('%s.v'%base, False) #Here, we'll make a duplicate of the base to look back on later if need be (for instance, using sculpt geometry tends to not register on tweak) baseRef = pm.duplicate(base, n='%s_editReference'%base)[0] pm.connectAttr(('%s.outMesh' %baseRef.getShapes()[1]), ('%s.inMesh' %baseRef.getShape())) #We'll also hook up the original so we can get it later pm.addAttr(sculptTrans, ln='baseTransform', at='message') pm.addAttr(sculptTrans, ln='baseReference', at='message') pm.connectAttr('%s.message'%base, '%s.baseTransform'%sculptTrans) pm.connectAttr('%s.message'%baseRef, '%s.baseReference'%sculptTrans) #now to keep things from changing between functions, we'll lock the three nodes involved in the #other script so our pesky little user won't delete or rename anything pm.lockNode(base, l=True) pm.lockNode(sculptTrans, l=True)
def checkFresnelUseIOR(self, nodeName): fullAttr = '%s.%s'%(nodeName, "Fresnel_use_IOR") fresIorValue = pm.getAttr(fullAttr) fullAttr = '%s.%s'%(nodeName, "specular_Fresnel") specFresValue = pm.getAttr(fullAttr) dim = (specFresValue is False) or (fresIorValue is True) pm.editorTemplate(dimControl=(nodeName, "Ksn", dim)) fullAttr = '%s.%s'%(nodeName, "Fresnel") refFresValue = pm.getAttr(fullAttr) dim = (refFresValue is False) or (fresIorValue is True) pm.editorTemplate(dimControl=(nodeName, "Krn", dim))
def update_channel(self, channel_name, param_name): grp = "OpenVDB%sChannelGrp" % channel_name attr_value = pm.getAttr(param_name) pm.textFieldGrp(grp, edit=True, text="" if attr_value is None else attr_value, changeCommand=lambda val: pm.setAttr(param_name, val)) pm.scriptJob(parent=grp, replacePrevious=True, attributeChange=[param_name, lambda : pm.textFieldGrp(grp, edit=True, text=pm.getAttr(param_name))]) self.clear_popups(grp) pm.popupMenu(parent=grp, postMenuCommand=lambda popup, popup_parent: AEvdb_visualizerTemplate.setup_popup_menu_elems(popup, popup_parent, param_name))
def face_mesh_query(): transforms = [] transforms.append(py.getAttr('Blend_Morph.translate')) transforms.append(py.getAttr('Blend_Morph.rotate')) transforms.append(py.getAttr('Blend_Morph.scale')) py.setAttr('master_locator_grp.translate', transforms[0], type="double3") py.setAttr('master_locator_grp.rotate', transforms[1], type="double3") py.setAttr('master_locator_grp.scale', transforms[2], type="double3") py.setAttr('master_offset_grp.translate', transforms[0], type="double3") py.setAttr('master_offset_grp.rotate', transforms[1], type="double3") py.setAttr('master_offset_grp.scale', transforms[2], type="double3") py.hide('Blend_Morph')
def attrTextFieldGrp(*args, **kwargs): """ There is a bug with attrControlGrp and string attributes where it ignores any attempt to edit the current attribute. So, we have to write our own replacement """ attribute = kwargs.pop('attribute', kwargs.pop('a', None)) assert attribute is not None, "You must passed an attribute" changeCommand = kwargs.pop('changeCommand', kwargs.pop('cc', None)) if changeCommand: def cc(newVal): pm.setAttr(attribute, newVal) changeCommand(newVal) else: cc = lambda newVal: pm.setAttr(attribute, newVal) if kwargs.pop('edit', kwargs.pop('e', False)): ctrl = args[0] pm.textFieldGrp(ctrl, edit=True, text=pm.getAttr(attribute), changeCommand=cc) pm.scriptJob(parent=ctrl, replacePrevious=True, attributeChange=[attribute, lambda: pm.textFieldGrp(ctrl, edit=True, text=pm.getAttr(attribute))]) elif kwargs.pop('query', kwargs.pop('q', False)): # query pass else: # create labelText = kwargs.pop('label', None) if not labelText: labelText = pm.mel.interToUI(attribute.split('.')[-1]) ctrl = None if len(args) > 0: ctrl = args[0] pm.textFieldGrp(ctrl, label=labelText, text=pm.getAttr(attribute), changeCommand=cc) else: ctrl = pm.textFieldGrp(label=labelText, text=pm.getAttr(attribute), changeCommand=cc) pm.scriptJob(parent=ctrl, attributeChange=[attribute, lambda: pm.textFieldGrp(ctrl, edit=True, text=pm.getAttr(attribute))]) return ctrl
def duplicate(self, * args): ''' # duplicates selected lights ''' selected = pm.ls(sl= True) for sel in selected: sel_shape = sel.getShape() # getting the shape node sel_type = pm.nodeType(sel_shape) # getting the node type xform = self.xform.getValue() if 'Light' not in sel_type: print '# wrong object type ', sel continue # creating a new light based on the recieved node type new_light = pm.shadingNode('%s' % (sel_type), asLight= True) new_light = pm.rename(new_light, '%s_copy' % (sel)) # renaming new_shape = new_light.getShape() # getting the shape # listing transform attrs input_attrs = pm.listAttr(sel) # listing shape attrs shape_attrs = pm.listAttr(sel_shape) if xform == 1: for attr in input_attrs: try: value = pm.getAttr('%s.%s' % (sel, attr)) pm.setAttr('%s.%s' % (new_light, attr), value) except: pass for attr in shape_attrs: try: value = pm.getAttr('%s.%s' % (sel_shape, attr)) pm.setAttr('%s.%s' % (new_shape, attr), value) except: pass pm.select(new_light) if self.override_intensity.getValue() == 1: #pm.setAttr('%s.intensity' % (new_light), self.int_slider.getValue()) new_light.intensity.set(self.int_slider.getValue()) if self.override_color.getValue() == 1: #pm.setAttr('%s.color' % (new_light), self.color_slider.getRgbValue()) new_light.color.set(self.color_slider.getRgbValue())
def _createRenderProxy( self, args ): mel.eval('setCurrentRenderer mentalRay') self.scene_name = mel.eval('file -q -sn -shn') for hi in args: if len(hi.split('|')) > 1 : hi=hi.split('|')[-1] #If the path doesn't exist for the file, create it. bipx_path = self._getBipxPath() if not os.path.exists(bipx_path): os.makedirs(bipx_path) #create the low geometry to take the proxy lo_proxy_name = hi+'_PROXY' lo = pm.polyPlane(w=1,h=1,sx=1,sy=1,ax=(0,1,0),cuv=2,ch=0,n=lo_proxy_name)[0] #Create the bipx if necessary bipx_name = hi+'_BINPROXY' if pm.objExists(bipx_name): bipx = pm.PyNode(bipx_name) else: bipx = pm.createNode('mip_binaryproxy', n=bipx_name) #turn the lo geometry shader on lo.miExportGeoShader.set(1) #connect the proxy to the lo's geo shader bipx.outValue.connect(lo.miGeoShader, f=True) #connect the hi to the proxy and set the write to 1 and set the file path hi.message.connect(bipx.geometry, f=True) bipx.write_geometry.set(1) bipx_filePath = bipx_path+hi+"_BINPROXY.mib" bipx.object_filename.set(bipx_filePath) #set the resolution width/height and store the originals to reset later res_wh = [pm.getAttr("defaultResolution.width"), pm.getAttr("defaultResolution.height")] pm.setAttr("defaultResolution.width", 5) pm.setAttr("defaultResolution.height", 5) #Perform a render, make the render globals really small square then reset after print ("Creating a file for object: %s" % (bipx_filePath)) mel.eval("renderWindowRender redoPreviousRender renderView;") try: with open(bipx_filePath): print 'File created Successfully.' except IOError: print 'Oh dear.' pm.setAttr("defaultResolution.width", res_wh[0]) pm.setAttr("defaultResolution.height", res_wh[1]) bipx.write_geometry.set(0) hi.message.disconnect(bipx.geometry)
def orient_joint(self, joint, aimAxis=[1, 0, 0], upAxis=[0, 0, 1], worldUpType="vector", worldUpVector=[0, 1, 0]): #joint should be pm.nt.Joint type if not isinstance(joint, pm.nt.Joint): raise TypeError("%s sholud be an instance of pm.nt.Joint Class" % joint) jointUnder = self.jointUnder(joint) if jointUnder is None: return 0 temporalGroup = DrawNode(Shape.transform, 'temporalGroup') pm.parent(jointUnder, temporalGroup.drawnNode) pm.setAttr(joint.jointOrient, (0, 0, 0)) if worldUpType == "object": aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis, upVector=upAxis, worldUpType=worldUpType, worldUpObject=worldUpVector) elif worldUpType == "vector": aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis, upVector=upAxis, worldUpType=worldUpType, worldUpVector=worldUpVector) pm.delete(aimConst) pm.parent(jointUnder, joint) pm.setAttr(joint.jointOrient, (pm.getAttr(joint.rotate))) pm.setAttr((joint.rotate), [0, 0, 0]) pm.delete(temporalGroup.drawnNode)
def repathTextures(cls, texList, newPath, *args, **kwargs): ''' repath the textures in a given list ''' if texList: for tex in texList: oldPath = pm.getAttr(tex+'.fileTextureName') fixedPath = path.repath(oldPath , newPath) pm.setAttr(tex+'.fileTextureName', fixedPath)
def set_attribute_order(node, attrs): """ Set the order of all user attributes on node. attrs should contain all user attributes. If any are missing from the list, they'll end up at the top. This can't be undone. """ # Sanity check the attribute list before making any changes. for attr in reversed(attrs): attr = node.attr(attr) with maya_helpers.restores() as restores: # Make sure undo is enabled. restores.append(maya_helpers.SetAndRestoreCmd(pm.undoInfo, key='state', value=True)) # Deleting an attribute and undoing the deletion pushes an attribute to the end of # the list. for attr in attrs: # For some reason, Maya won't delete a locked attribute. attr = node.attr(attr) locked = pm.getAttr(attr, lock=True) if locked: pm.setAttr(attr, lock=False) pm.deleteAttr(attr) pm.undo() if locked: pm.setAttr(attr, lock=True)
def jointConstraint(tf, jnt, name="jntconstriant"): """ constraint transform to joint preserve joint orients """ t_mat = pm.createNode("multMatrix", n=name + "Trans_MAT") r_mat = pm.createNode("multMatrix", n=name + "Rot_MAT") t_dmat = pm.createNode("decomposeMatrix", n=name + "Trans_DMAT") r_dmat = pm.createNode("decomposeMatrix", n=name + "Rot_DMAT") inv_mat = pm.createNode("inverseMatrix", n=name + "InvMat_TMP") rotateOrder = pm.getAttr(tf + '.rotateOrder') pm.setAttr(t_dmat + '.inputRotateOrder', rotateOrder) pm.setAttr(r_dmat + '.inputRotateOrder', rotateOrder) tf = pm.PyNode(tf) jnt = pm.PyNode(jnt) tf.worldMatrix[0] >> t_mat.matrixIn[0] jnt.parentInverseMatrix[0] >> t_mat.matrixIn[1] t_mat.matrixSum >> t_dmat.inputMatrix t_dmat.outputTranslate >> jnt.translate t_dmat.outputScale >> jnt.scale t_dmat.outputShear >> jnt.shear t_mat.matrixSum >> r_mat.matrixIn[0] t_mat.matrixSum >> inv_mat.inputMatrix r_mat.matrixIn[1].set(inv_mat.outputMatrix.get()) pm.delete(inv_mat) r_mat.matrixSum >> r_dmat.inputMatrix r_dmat.outputRotate >> jnt + ".rotate"
def repathTextures(cls, texList, newPath, *args, **kwargs): ''' repath the textures in a given list ''' if texList: for tex in texList: oldPath = pm.getAttr(tex + '.fileTextureName') fixedPath = path.repath(oldPath, newPath) pm.setAttr(tex + '.fileTextureName', fixedPath)
def open_file_browser(unused): old_path = pm.getAttr(fileAttribute) old_path = old_path.replace('\\', '/') starting_file = os.path.basename(old_path) # Find the absolute path to the current path, if any, and open the browser in the # same directory as the current path. Why don't all Maya file browsers do this? starting_directory = '' if old_path: attr = pm.ls(fileAttribute)[0] node_name = attr.nodeName() absolute_path = omr.MRenderUtil.exactFileTextureName( old_path, False, "", node_name) starting_directory = os.path.dirname(absolute_path) options = pm.mel.eval('fileBrowserActionSetup("image", 1)') files = pm.fileDialog2(caption='Open', okCaption='Open', fileMode=1, fileFilter=options[2], startingDirectory=starting_directory, selectFileFilter=starting_file) if not files: return path = files[0] path = path.replace('\\', '/') pm.setAttr(fileAttribute, path)
def get_layered_texture_attrs(self, node): blend_mode = { 0: 'None', 1: 'Over', 2: 'In', 3: 'Out', 4: 'Add', 5: 'Subtract', 6: 'Multiply', 7: 'Difference', 8: 'Lighten', 9: 'Darken', 10: 'Saturate', 11: 'Desaturate', 12: 'Illuminate' } output = [] inputs = node.inputs() for i in inputs: attr = self.get_layered_texture_input_index(node, i) new_attr = attr.split('.color')[0] mode = pm.getAttr('%s.blendMode' % (new_attr)) output.append("Layer '%s' Blend Mode: %s" % (i, blend_mode[mode])) return output
def getVisGroup(obj): ''' Returns ('name', int:level) if it's in a group, otherwise an empty tuple. ''' zero = core.dagObj.zero(obj, apply=False, make=False) if zero: obj = zero visCon = listConnections(obj.visibility.name(), p=True, s=True, d=False) if visCon: node = visCon[0].node() attr = visCon[0].longName() # This returns the long attr name, not the node at all, where .attrName() returns the short name. shape = get(create=False) level = 1 if nodeType(node) == 'condition' and attr == 'outColorR': #con = listConnections(node + '.firstTerm', p=True, s=True, d=False) con = node.firstTerm.listConnections(p=True, s=True, d=False) if con: level = int(getAttr(node + '.secondTerm')) #node = shortName(con[0].node()) attr = con[0].longName() # longName() returns the long attribute name, not the node (technically they are the same here). return attr, level # Verify the shape is sharedShape via uuid (as of 2017, pymel tosses an error) if mel.ls(node, uuid=True)[0] == mel.ls(shape, uuid=True)[0]: return attr, level return ()
def get_external_axis_names(robot_name, only_active=False): """ Gets all external axes assigned to the given robot :param robot_name: string, name of selected robot :param only_active: bool, if True, removes axes marked as "ignore" :return robots_external_axes: list, names of all external axes on robot """ target_ctrl_path = mimic_utils.get_target_ctrl_path(robot_name) # Find all attributes on the target_CTRL categorized as 'externalAxis' robot_external_axis_names = pm.listAttr(target_ctrl_path, category='externalAxis') # Remove parent attribute designation 'externalAxis_' from each axis name for i, axis_name in enumerate(robot_external_axis_names): robot_external_axis_names[i] = axis_name.replace('externalAxis_', '') # If only_active is True, remove axes marked as "Ignore" if only_active: active_external_axes = [x for x in robot_external_axis_names if not pm.getAttr(target_ctrl_path + '.' + x + '_ignore')] robot_external_axis_names = active_external_axes return robot_external_axis_names
def tagGuerillaAuto(*arg): selectionGuerilla_List = pm.ls(sl=1) asset = asset_core.string_to_asset(os.environ[defaults._asset_var_]) if selectionGuerilla_List: for mesh in selectionGuerilla_List: if pm.attributeQuery('GuerillaTags', node=mesh, exists=1) == 0: pm.addAttr(mesh, ln="GuerillaTags", dt="string") currentAttr = mesh.name() + '.GuerillaTags' currentTag = pm.getAttr(currentAttr) tags_list = [] if currentTag: tags_list = currentTag.split(',') if mesh.name() not in tags_list: tags_list.append(mesh.name()) if asset.category not in tags_list: tags_list.append(asset.category) if asset.name not in tags_list: tags_list.append(asset.name) if asset.variant not in tags_list: tags_list.append(asset.variant) name_variant = '{}_{}'.format(asset.name, asset.variant) if name_variant not in tags_list: tags_list.append(name_variant) attrs = (',').join(tags_list) pm.setAttr(mesh + '.GuerillaTags', attrs, type="string") else: pm.warning('Your selection is empty')
def recdisplay(arg): aucsel = cmds.ls(type="aiUtility") for i in range(0,len(aucsel)): aucHcolorn= aucsel[i]+".hardwareColor" aucHcolor = pm.getAttr(aucHcolorn) if aucHcolor !=(1,1,1): cmds.setAttr(aucHcolorn,0.5,0.5,0.5)
def migrate(self, weights, new_mesh=''): if not new_mesh: om.MGlobal.displayError("No target mesh found in selection") return # new blend shape name new_BS_node = self.targetNode + '_' + \ str(random.randint(4145, 1514545442)) self.new_blendshape_node = new_BS_node # create BS node pm.blendShape(new_mesh, n=new_BS_node, foc=True) for idx, item in enumerate(weights): newTarg = item # pm.blendShape(new_BS_node, edit=True, t=(new_mesh, idx, str(newTarg), 1.0)) if pm.attributeQuery('parent', node=newTarg, exists=True): downstreamNodes = pm.listConnections('{}.{}'.format( newTarg, 'parent'), d=True) for inBet in downstreamNodes: val = float('%.3f' % pm.getAttr(inBet + '.value')) pm.blendShape(new_BS_node, edit=True, t=(new_mesh, idx, inBet, float(val)))
def takeScreenshotForPoseBtn(filepath, filename, filesizeW, filesizeH): defaultRenderGlobalsNode = pm.PyNode('defaultRenderGlobals') #Get Current imageFormat from renderglobals currentImageFormat = pm.getAttr(defaultRenderGlobalsNode.name() + '.imageFormat') #Set new imageFormat to jpg defaultRenderGlobalsNode.setAttr('imageFormat', 8) #Create Playblast image #create playblast image path playblastImagePath = filepath + filename + '.jpg' pm.playblast(cf=playblastImagePath, fr=[pm.currentTime()], wh=(filesizeW, filesizeH), fmt='image', o=False, orn=False, v=False, p=100) #Reset imageFormat to old one defaultRenderGlobalsNode.setAttr('imageFormat', currentImageFormat)
def saveTextureList(self, *args, **kwargs): ''' write an xml file with a list of the scenes textures and timestamps ''' fileNodes = pm.ls(type='file') sceneName = path.getSceneName() xmlFileName = sceneName+'_textureList' doc = Document() textureList = doc.createElement('textureList') textureList.setAttribute('sceneName', sceneName) doc.appendChild(textureList) for node in fileNodes: fileTextureName = pm.getAttr(node+'.fileTextureName') if os.path.isfile(fileTextureName): time = os.path.getmtime(fileTextureName) textureNode = doc.createElement('textureNode') textureNode.setAttribute('nodeName', node) textureList.appendChild(textureNode) texturePath = doc.createElement('path') texturePath.appendChild(doc.createTextNode(fileTextureName) ) textureNode.appendChild(texturePath) textureTime = doc.createElement('time') textureTime.appendChild(doc.createTextNode(str(time) ) ) textureNode.appendChild(textureTime) f = open(self.settingsPath+xmlFileName+'.xml', 'w+') #f.write(doc.toprettyxml(indent=' ') ) #This is super slow !!!!! doc.writexml(f) f.close()
def setGeoGroupRender(self): ''' geo组的模型可渲染 ''' overName = [] geoName = self.getGeoGroup() if not geoName: return allMesh = pm.ls(type = 'mesh' , ni = True) meshs = [s for s in allMesh if geoName[0] in s.getAllParents()] attr = ['.castsShadows' , '.receiveShadows' , '.motionBlur' , '.smoothShading' , '.primaryVisibility' , '.visibleInReflections' , '.visibleInRefractions' , '.doubleSided', '.aiSelfShadows' , '.aiVisibleInDiffuse' , '.aiVisibleInGlossy'] for m in meshs: for atr in attr: try: value = pm.getAttr(m + atr) if value == 0: if m not in overName: overName.append(m) except: pass for s in overName: self.setRender(s , True , 0) return overName
def isLocked(node, attr): if not attr.startswith('.'): attr = '.' + attr for add in ('', 'X', 'Y', 'Z'): if pc.getAttr(node + attr + add, l=True): return True return False
def isKeyAble(name): keyable = 0 if (pm.getAttr(name,l = 1) == False) and (len(pm.listConnections(name,s = 1,d = 0)) == 0): keyable = 1 return keyable
def pasteAnimPlusRename(self, filename, locName, version): # imports cmds.file(filename + "\\" + locName + ".ma", i=True, type="mayaAscii", ignoreVersion=True, rpr="animExport", mergeNamespacesOnClash=False, pr=True) locAttrList = cmds.listAttr(locName, keyable=True) for locAttr in locAttrList: item = locAttr.split("___")[0] old = item.rpartition("_") new = old[0] + version + old[-1] objName = new attrName = locAttr.split("___")[1] if cmds.objExists(objName + "." + attrName): print (locName + "." + locAttr) connList = cmds.listConnections(locName + "." + locAttr, source=True, destination=False, skipConversionNodes=True) if self.isKeyable(objName + "." + attrName): if connList != None: if "animCurve" in cmds.nodeType(connList[0]): cmds.connectAttr((connList[0] + ".output"), (objName + "." + attrName)) else: value = pm.getAttr(locName + "." + locAttr) pm.setAttr((objName + "." + attrName), value) print (objName + "." + attrName) else: print (objName + "." + attrName + " has connections incoming or is locked! skipping....") else: print ("cant find " + objName + "." + attrName + " in the scene ! Skipping....") if cmds.objExists(locName): cmds.delete(locName) print "Success!"
def reloadTextures(cls, *args, **kwargs): ''' reloads all texture files in a scene ''' sel = pm.ls(typ='file') for tex in sel: path = pm.getAttr(tex+'.fileTextureName') if path != '': pm.setAttr(tex+'.fileTextureName',path)
def add_enum_parameters(self, enum, scene_object, **kwargs): name = kwargs.pop('name', 'spaceSwitch') if name in pm.listAttr(scene_object): if pm.getAttr(scene_object + "." + name, type=True) == 'enum': enums_in_object = self.get_control_enums(scene_object) for eachEnum in enum: if not eachEnum in enums_in_object: enums_in_object.append(eachEnum) pm.addAttr(scene_object + '.' + name, e=True, ln=name, en=":".join(enums_in_object)) index = 0 return_index_dictionary = {} for eachEnum in enums_in_object: return_index_dictionary[eachEnum] = index index += 1 return return_index_dictionary else: pm.addAttr(scene_object, at="enum", ln=name, k=1, en=":".join(enum)) return None
def reloadTextureList(cls, texList, *args, **kwargs): ''' reloads a list of texture nodes ''' for item in texList: path = pm.getAttr(item + '.fileTextureName') if os.path.exists(path): pm.setAttr(item + '.fileTextureName', path) pm.refresh()
def getAlpha(): target = py.ls(sl=1) py.select(target[0]) s = getShader() aa = py.getAttr(s + ".transparency") a = 255 * abs(1 - aa[0]) return a
def getCurrentTranslator(self, nodeName): """ get the current translator for this node, querying and setting the default if not yet set """ try : # asString allows for enum attributes as well transName = pm.getAttr(nodeName + ".aiTranslator", asString=True) except : transName = None translators = self.getTranslators() if not transName or transName not in translators: # set default transName = getDefaultTranslator(nodeName) if transName is None: if not translators: pm.warning("cannot find default translator for %s" % nodeName) return transName = translators[0] try : pm.setAttr(nodeName + ".aiTranslator", transName) except: pm.warning("cannot set default translator for %s" % nodeName) import traceback traceback.print_exc() return transName
def populateOutputs(self): self.publishAsComboBox.blockSignals(True) self.publishAsComboBox.clear() if not self.selVizNode: return origName = pm.getAttr('%s.originalName'%self.selVizNode) creature = bdNamingConventions.getCharacterFromFullname(origName) if creature in self.vampList: vampList = [NAMES_INFO[char]['fullname'] for char in self.vampList] vampList.sort() self.publishAsComboBox.addItems(vampList) elif creature in self.wolfList and 'young' in creature: wolfList = [NAMES_INFO[char]['fullname'] for char in self.wolfList if 'young' in char] wolfList.sort() self.publishAsComboBox.addItems(wolfList) elif creature in self.wolfList and 'young' not in creature: wolfList = [NAMES_INFO[char]['fullname'] for char in self.wolfList if 'young' not in char] wolfList.sort() self.publishAsComboBox.addItems(wolfList) else: pm.warning('Creature name %s not recognized' % creature) self.publishAsComboBox.blockSignals(False)
def __init__(self, parent, attr): self.base = super(MayaFloatSlider, self) self.base.__init__(parent) if not pmc.objExists(attr): msg = "Maya attribute \"{0}\" not found".format(attr) raise(NameError(msg)) self.mult = 100.0 self.attr = attr self.setValue(pmc.getAttr(attr)) # Find if maya object has min & max obj, a = attr.split(".") if pmc.attributeQuery(a, node=obj, minExists=True): sMin = pmc.attributeQuery(a, node=obj, min=True)[0] else: sMin = -10.0 if pmc.attributeQuery(a, node=obj, maxExists=True): sMax = pmc.attributeQuery(a, node=obj, max=True)[0] else: sMax = 10.0 self.setMinimum(sMin * self.mult) self.setMaximum(sMax * self.mult) self.valueChanged.connect(self.valueChangedConvert) self.floatValueChanged.connect(self.mayaAttrUpdate)
def is_scene_meshShown(self, assem): ''' ''' #cause is_scene check happens first, master must exists assem_children = pm.listRelatives(assem, c=True, pa=True) master = [ assem_c for assem_c in assem_children if str(assem_c).endswith('master') ][0] namespace = master.rsplit(':', 1)[0] hi_level = namespace + ':hi' if not pm.objExists(hi_level): return False # we only count on meshes in hi group trans = pm.listRelatives(hi_level, allDescendents=True, path=True, type='transform') for t in trans: if pm.getAttr(t + '.visibility'): meshes = pm.listRelatives( t, allDescendents=True, path=True, type=['mesh', 'subdiv', 'nurbsSurface']) if meshes: return True return False
def checkObjectNumerical(self): ''' geo组下模型和组的属性是否为默认值 ''' overName = [] geoName = self.getGeoGroup() if not geoName: return childrenList = geoName[0].getChildren(type = 'transform' , ad = True ) tranList = [c for c in childrenList if c.nodeType() == 'transform'] attrs = ['.tx' , '.ty' , '.tz' , '.rx' , '.ry' , '.rz' ,'.sx' , '.sy' , '.sz'] for t in tranList: for at in attrs: value = pm.getAttr(t + at) if at == '.sx' or at == '.sy' or at == '.sz': if value != 1: if t not in overName: overName.append(t) else: if value != 0: if t not in overName: overName.append(t) return overName
def reloadChangedTextures(self, *args, **kwargs): ''' ''' fileNodes = pm.ls(type='file') sceneName = path.getSceneName() xmlFileName = sceneName+'_textureList' if os.path.exists(self.settingsPath+xmlFileName+'.xml'): textureList = xml.dom.minidom.parse(self.settingsPath+xmlFileName+'.xml') for node in fileNodes: fileTextureName = pm.getAttr(node+'.fileTextureName') for nodeStored in textureList.getElementsByTagName('textureNode'): nodeNameStored = nodeStored.getAttribute('nodeName') if node == nodeNameStored: time = os.path.getmtime(fileTextureName) timeList = nodeStored.getElementsByTagName('time') timeNode = timeList[0] timeChild = timeNode.firstChild timeStored= timeChild.data if str(time) != timeStored: self.reloadTexture(node) self.saveTextureList() else: self.saveTextureList() self.reloadTextures()
def saveTextureList(self, *args, **kwargs): ''' write an xml file with a list of the scenes textures and timestamps ''' fileNodes = pm.ls(type='file') sceneName = lcPath.Path.getSceneName() xmlFileName = sceneName + '_textureList' doc = Document() textureList = doc.createElement('textureList') textureList.setAttribute('sceneName', sceneName) doc.appendChild(textureList) for node in fileNodes: fileTextureName = pm.getAttr(node + '.fileTextureName') if os.path.isfile(fileTextureName): time = os.path.getmtime(fileTextureName) textureNode = doc.createElement('textureNode') textureNode.setAttribute('nodeName', node) textureList.appendChild(textureNode) texturePath = doc.createElement('path') texturePath.appendChild(doc.createTextNode(fileTextureName)) textureNode.appendChild(texturePath) textureTime = doc.createElement('time') textureTime.appendChild(doc.createTextNode(str(time))) textureNode.appendChild(textureTime) f = open(self.settingsPath + xmlFileName + '.xml', 'w+') # f.write(doc.toprettyxml(indent=' ') ) #This is super slow !!!!! doc.writexml(f) f.close()
def reloadTextureList(cls, texList, *args, **kwargs): ''' reloads a list of texture nodes ''' for item in texList: path = pm.getAttr(item+'.fileTextureName') if os.path.exists(path): pm.setAttr(item+'.fileTextureName',path) pm.refresh()
def reloadChangedTextures(self, *args, **kwargs): ''' ''' fileNodes = pm.ls(type='file') sceneName = lcPath.Path.getSceneName() xmlFileName = sceneName + '_textureList' if os.path.exists(self.settingsPath + xmlFileName + '.xml'): textureList = xml.dom.minidom.parse(self.settingsPath + xmlFileName + '.xml') for node in fileNodes: fileTextureName = pm.getAttr(node + '.fileTextureName') for nodeStored in textureList.getElementsByTagName( 'textureNode'): nodeNameStored = nodeStored.getAttribute('nodeName') if node == nodeNameStored: time = os.path.getmtime(fileTextureName) timeList = nodeStored.getElementsByTagName('time') timeNode = timeList[0] timeChild = timeNode.firstChild timeStored = timeChild.data if str(time) != timeStored: self.reloadTexture(node) self.saveTextureList() else: self.saveTextureList() self.reloadTextures()
def create_assetData(self, assem_node): ''' create ad.AssetData instance, and add constrained attribute AssetData(namespace='', type='', name='', step='', transform=None) ''' assem_splits = assem_node.split(':') real_namespace = assem_splits[:-1] ar_prefix_ns = assem_splits[-1].replace('_AR', '') real_namespace.append(ar_prefix_ns) namespace = '.'.join(real_namespace) assem_def_path = pm.getAttr(assem_node + '.definition').replace( '\\', '/') def_path_tokens = assem_def_path.split('/') if 'asset' in def_path_tokens: i = def_path_tokens.index('asset') asset_type = def_path_tokens[i + 1] #read type from reference path asset_name = def_path_tokens[i + 2] asset_step = def_path_tokens[i + 3] else: asset_type = '-' asset_name = '-' asset_step = '-' return ad.AssetData(namespace, asset_type, asset_name, asset_step, assem_node)
def getTextureDimensions(self, *args, **kwargs): ''' returns the dimensions of the currently displayed texture in the UV Editor If there is no texture loaded returns a default [1,1] ''' textureDimensions = [1, 1] numImages = pm.textureWindow(self.uvTextureView[0], q=True, ni=True) if numImages > 0: if int(pm.about(version=True)) < 2014: currentTextureImage = pm.textureWindow(self.uvTextureView[0], q=True, imageNumber=True) imageList = pm.textureWindow(self.uvTextureView[0], q=True, imageNames=True) currentTextureString = imageList[currentTextureImage].split( '|') currentTextureNode = currentTextureString[ len(currentTextureString) - 1].strip() if pm.nodeType(currentTextureNode) == 'file': textureDimensions = pm.getAttr(currentTextureNode + '.outSize') else: textureDimensions = pm.textureWindow(self.uvTextureView[0], q=True, imageSize=True) return textureDimensions
def getAlpha(): target = py.ls(sl=1) py.select(target[0]) s = getShader() aa = py.getAttr(s + ".transparency") a = 255 * abs(1-aa[0]) return a
def buildRig(): ''' Makes the rig, saving shapes and removing the old rig if needed. ''' cards = util.selectedCards() mode = 'Use Rig Info Shapes' if not cards: confirmDialog(m='No cards to selected to operate on.') return for card in cards: if mode == 'Use Current Shapes': card.saveShapes() # If this being rebuilt, also restore the if it's in ik or fk switchers = [ controllerShape.getSwitcherPlug(x[0]) for x in card._outputs() ] prevValues = [(s, getAttr(s)) for s in switchers if s] card.removeRig() cardRigging.buildRig([card]) if mode != 'Use Rig Info Shapes': card.restoreShapes() # Restore ik/fk-ness for switch, value in prevValues: if objExists(switch): setAttr(switch, value) select(cards)
def checkShadeMode(self, nodeName): fullAttr = '%s.%s' % (nodeName, 'shade_mode') shadeModeValue = pm.getAttr(fullAttr) if shadeModeValue == 3: pm.editorTemplate(dimControl=(nodeName, 'aoDistance', False)) else: pm.editorTemplate(dimControl=(nodeName, 'aoDistance', True))
def deleteShotSculptNode(): global editState ssn = pm.optionMenu("selectedSSNode_menu", q=True, v=True) print ssn bshps = pm.getAttr(ssn + '.bshps') result = pm.confirmDialog(title='Delete Shot Sculpt Group', message='Are you sure you want to delete ' + ssn + "?", button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if result == 'Yes': ##exit editmode if enabled if editState: editSculptFrame() pm.textScrollList("SculptLayers_tsl", e=True, ra=True) pm.delete(ssn, bshps) pm.deleteUI(str(ssn)) existing_ssns = pm.optionMenu('selectedSSNode_menu', q=True, ils=True) print existing_ssns if len(existing_ssns) < 1: pm.menuItem("-- None --", p="selectedSSNode_menu") else: loadShotSculptNode()
def deleteShotSculptFrame(): if editState == True: editSculptFrame() ssn = pm.optionMenu("selectedSSNode_menu", q=True, v=True) bshps = pm.getAttr(ssn + '.bshps') frame = pm.textScrollList("SculptLayers_tsl", q=True, si=True) result = pm.confirmDialog(title='Delete Sculpt-Frame', message='Are you sure you want to delete ' + frame[0] + "?", button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if result == 'Yes': pm.deleteAttr(ssn + '.' + frame[0]) pm.textScrollList("SculptLayers_tsl", e=True, ri=str(frame[0])) for bshp in bshps: ##mel command: blendShapeDeleteTargetGroup + bshp + index index = getIndexByName(bshp, frame[0]) #remove the alias pm.aliasAttr(bshp + '.' + frame[0], remove=True) ##delete the target pm.removeMultiInstance(bshp + '.weight[' + str(index) + ']', b=True)
def keyFlash(obj=None, channel=None, fade=18): if obj == None: obj = pm.ls(sl=1)[0] if channel == None: channel = 'translateX' current = pm.currentTime(q=1) kf = [current - 1, current, current + 1, current + fade] value = pm.getAttr('%s.%s' % (obj, channel)) #see if already keys if pm.listConnections('%s.%s' % (obj, channel)) is not []: pm.cutKey(obj, at=channel, time=(kf[0], kf[-1])) pm.setKeyframe(obj, at=channel, v=0, t=[kf[0]], ott='stepnext') pm.setKeyframe(obj, at=channel, v=value, t=[kf[1]], ott='stepnext') pm.setKeyframe(obj, at=channel, v=value * 0.75, t=[kf[2]], ott='auto') pm.setKeyframe(obj, at=channel, v=0, t=[kf[3]], ott='auto') pm.keyTangent(obj, at=channel, a=1, outWeight=1, e=1, t=[kf[2]], outAngle=-10.253096)
def stretchyBack( ikHandleTorso, jntList ): pymelLogger.debug('Starting: stretchyBack()...') #Stretchy process # ArcLen to create curveInfo curveInfoNodeBack = pm.arclen( ikHandleTorso[2], ch=True ) # add attr to curveinfo Node (normalizedScale) # this will have a value coming from a multiply divide node that will be # dividing the current length by the initial length of the curve # this will be used later to scale the joints pm.addAttr(curveInfoNodeBack, longName='normalizedScale', attributeType='double') # get initial length of the curve iniLen = pm.getAttr( curveInfoNodeBack + '.arcLength' ) # create a node multiplydivide, operation set to division MDCurveBack = pm.shadingNode( 'multiplyDivide', asUtility=True ) pm.setAttr( MDCurveBack+'.operation', 2 ) # divide # Connect curve arcLength to input1X pm.connectAttr( curveInfoNodeBack + '.arcLength', MDCurveBack + '.input1X', force=True ) # Set input2X to initial length of the curve pm.setAttr(MDCurveBack+'.input2X', iniLen) # connect outpux x from multiplydivide to normalized scale of the curve info pm.connectAttr(MDCurveBack + '.outputX', curveInfoNodeBack + '.normalizedScale', force=True) returnList = [curveInfoNodeBack,MDCurveBack] pymelLogger.debug('End: stretchyBack()...') return returnList
def create_sphere_display_control_base(self, control, radius): new_sphere_transform, new_sphere_creator = pm.polySphere() self.display_spheres.append([new_sphere_transform, new_sphere_creator]) pfx = pm.createNode('pfxToon') transform_pfx = pm.ls('pfxToon1')[0] new_sphere_transform.setParent(self.rig_system.kinematics) self.name_conv.rename_name_in_format(transform_pfx, name='display') self.name_conv.rename_name_in_format(pfx, name='displaypfx') self.name_conv.rename_name_in_format(new_sphere_transform, name='displaySphere') self.name_conv.rename_name_in_format(new_sphere_creator, name='displaySphereCreation') new_sphere_transform.outMesh >> pfx.inputSurface[0].surface new_sphere_transform.worldMatrix >> pfx.inputSurface[0].inputWorldMatrix pfx.displayPercent.set(100) pfx.screenspaceWidth.set(True) pfx.distanceScaling.set(1) pfx.minPixelWidth.set(1) pfx.maxPixelWidth.set(10) pfx.profileColor.set(0.5, 0.0, 0.0) len(pm.getAttr(pfx.inputSurface, mi=True)) pfx.overrideEnabled.set(True) pfx.overrideDisplayType.set(2) pm.addAttr(control, ln='radius', at='float', k=True, hnv=True, min=0) pm.addAttr(control, ln='influenceDisplay', at='bool', k=True) control.radius >> new_sphere_creator.radius control.radius.set(radius) control.influenceDisplay.set(True) control.influenceDisplay >> transform_pfx.visibility pm.parentConstraint(control, new_sphere_transform)
def attributeChanged(self, nodeName, attr, *args): """ called when the translator attribute is changed """ transName = pm.getAttr(attr) pm.optionMenuGrp(self._optionMenu, edit=True, value=transName) self.updateChildren(nodeName, transName)
def showcurve(self) : length = 0.5 thickness = 0.1 dist = 1 # カーブ上の点を取得 resolution = 60 params = [i/resolution for i in range(resolution)] cv_list = curvetool.getCurvePoint(self.curve, params, "normal") # カメラ位置 cam = pm.PyNode(tools.getCamFromModelPanel()) cam_pos_temp = pm.getAttr(cam.translate) cam_pos = om2.MPoint(cam_pos_temp[0],cam_pos_temp[1],cam_pos_temp[2]) # カメラ位置から距離dist,方向各CVとなる点を選ぶ points = [] for cvp in cv_list : dl = dist / (cvp - cam_pos).length() points.append( dl*cvp + (1-dl)*cam_pos ) # カーブの進行方向,カメラ方向と垂直な方向に上下に目張り # シェーダをセット print "set shader" global shadingEngine #pm.sets(shadingEngine, e = 1, forceElement = plane) print "fin"