def assignShader2(): shaderInfoNode = pm.PyNode('shaderInfoNode') numAttr = shaderInfoNode.shaderInfos.numChildren() message = '' for i in range(numAttr): shaderInfos = json.loads( shaderInfoNode.attr('shaderInfos{}'.format(i)).get()) try: pm.select(shaderInfos.get('geometry')) surfaceShader = pm.PyNode(shaderInfos.get('surfaceShader')) pm.hyperShade(assign=surfaceShader) pm.select(cl=True) try: if shaderInfos.get('displacement'): displacement = pm.PyNode(shaderInfos.get('displacement')) sg = surfaceShader.outColor.outputs()[0] displacement.displacement.connect(sg.displacementShader) except: message += (str(shaderInfos.get('displacement')) + '-->' + sg.name() + '\n') except: message += (str(shaderInfos.get('surfaceShader')) + '-->' + str(shaderInfos.get('geometry')) + '\n') shaderInfoNode.unlock() pm.delete(shaderInfoNode) return message
def create_locator(name): pm.select(None) global THU_MFT_LOCATOR_MATERIAL_NAME, THU_MFT_LOCATOR_ATTR try: material = pm.PyNode(THU_MFT_LOCATOR_MATERIAL_NAME) except: material = pm.createSurfaceShader( 'lambert', name=THU_MFT_LOCATOR_MATERIAL_NAME)[0] material.color.set((1, 0, 0)) material.transparency.set((0.8, 0.8, 0.8)) loc_name = '%s_%s' % (name, THU_MFT_LOCATOR_ATTR) try: locator_trans = pm.PyNode(loc_name) except: locator_trans = pm.polyPlane(name=loc_name, sw=1, sh=1)[0] pm.sets(material.shadingGroups()[0], edit=True, forceElement=locator_trans) if (not locator_trans.hasAttr(THU_MFT_LOCATOR_ATTR)): locator_trans.addAttr(THU_MFT_LOCATOR_ATTR, dt='string') locator_trans.setAttr(THU_MFT_LOCATOR_ATTR, name) return locator_trans
def displayConnect(self, obj): # Create curve for display, between selected objects # Return [curve, locator1, locator2] if len(obj) == 0: obj = pm.ls(transforms=1, sl=1) if len(obj) < 2: pm.error(u"KH_curve_Connect : 선택된 오브젝트가 없습니다.") pointA = obj[0] pointB = obj[1] curve = pm.curve(p=[(0, 0, 0), (0, 0, 0)], k=[0, 1], d=1) pointCurveConstraint1 = pm.pointCurveConstraint(curve + ".ep[0]", ch=True) pointCurveConstraint2 = pm.pointCurveConstraint(curve + ".ep[1]", ch=True) pointCostraint1 = pm.pointConstraint(pointA, pointCurveConstraint1[0]) pointCostraint2 = pm.pointConstraint(pointB, pointCurveConstraint2[0]) locShape1 = pm.listRelatives(pointCurveConstraint1[0], s=1) locShape2 = pm.listRelatives(pointCurveConstraint2[0], s=1) pm.setAttr(locShape1[0] + ".visibility", 0) pm.setAttr(locShape2[0] + ".visibility", 0) return [ curve, pm.PyNode(pointCurveConstraint1[0]), pm.PyNode(pointCurveConstraint2[0]), pointCostraint1, pointCostraint2 ]
def __exit__(self): if self.tmpObjectShape.name() == pm.PyNode( self.tmpObjectShape.name()).name(): pm.delete(tmpObjectShape) if self.tmpObject.name() == pm.PyNode(self.tmpObject.name()).name(): children = self.tmpObject.getChildren() if len(children) == 0: pm.delete(tmpObjectShape)
def create_joint(self, **kwargs): crv = kwargs.get("crv_node", "") if isinstance(crv, list): crv = pm.PyNode(crv[0]) crv = pm.PyNode(crv) shp = crv.getShape() pm.select(clear=True) ctr = pm.joint() pm.parent(shp, ctr, relative=True, shape=True) pm.delete(crv) return ctr
def importYeti(path): msg = '' try: yetiInfo = getYetiInfo() if yetiInfo: for yetiNode, shader in yetiInfo.items(): if pm.objExists(yetiNode): pm.delete(yetiNode) if pm.objExists(shader): pm.delete(shader) if pm.objExists('yetiInfoNode'): yetiInfoNode = pm.PyNode('yetiInfoNode') yetiInfoNode.unlock() pm.delete(yetiInfoNode) cmds.file(path, pr=1, ignoreVersion=1, i=1, type="mayaBinary", mergeNamespacesOnClash=False, options="v=0;") #pm.importFile(path) if not pm.objExists('yetiInfoNode'): msg += u'"yetiInfoNode"가 존재 하지 않습니다.' except: return msg if not pm.objExists('time1'): timeNode = pm.createNode('time', n='time1') timeNode = pm.PyNode('time1') yetiInfoNode = pm.PyNode('yetiInfoNode') yetiInfo = json.loads(yetiInfoNode.yetiInfo.get()) for yetiNodeName, shaderName in yetiInfo.items(): try: yetiNode = pm.createNode('pgYetiMaya', n=yetiNodeName + 'Shape') yetiParent = yetiNode.getParent() yetiParent.rename(yetiNodeName) yetiNode.renderDensity.set(1) yetiNode.aiOpaque.set(0) timeNode.outTime.connect(yetiNode.currentTime) pm.select(yetiParent) surfaceShader = pm.PyNode(shaderName) pm.hyperShade(assign=surfaceShader) except: msg += u'{}노드와 {}쉐이더를 어싸인 하는데 실패 했습니다'.format( yetiNodeName, shaderName) return msg
def assignShader(): """씬안에서 shaderInfoNode 노드를 검색 한다.\n shaderInfoNode 노드에 shaderInfos# 어트리뷰트를 검색한다.\n shaderInfos# 어트리뷰트의 값을 json 으로 가져 온다.\n 어트리뷰트의 geometry, surfaceShader, displacement 키 값을 가져 온다.\n geometry에 surfaceShader, displacement 적용 한다.\n shaderInfoNode 삭제 한다. .. warning:: 씬안에 'shaderInfoNode' 노드가 없을 때 ``shaderInfoNode not exist!`` 예외 발생 """ try: shaderInfoNode = pm.PyNode('shaderInfoNode') except: print '"shaderInfoNode" not exist!' numAttr = shaderInfoNode.shaderInfos.numChildren() message = '' for i in range(numAttr): shaderInfos = json.loads( shaderInfoNode.attr('shaderInfos{}'.format(i)).get()) geos = [] for geo in shaderInfos.get('geometry'): if pm.objExists(geo): geos.append(geo) try: pm.select(geos) surfaceShader = pm.PyNode(shaderInfos.get('surfaceShader')) pm.hyperShade(assign=surfaceShader) pm.select(cl=True) try: if shaderInfos.get('displacement'): displacement = pm.PyNode(shaderInfos.get('displacement')) sg = surfaceShader.outColor.outputs()[0] displacement.displacement.connect(sg.displacementShader) except: message += (str(shaderInfos.get('displacement')) + '-->' + sg.name() + '\n') except: message += (str(shaderInfos.get('surfaceShader')) + '-->' + str(geos) + '\n') shaderInfoNode.unlock() pm.delete(shaderInfoNode) if message: print 'Failed list:\n' print message
def fixCamsClipAndPos(self): ## Camera Python script to fix clipping and default positioning ## We can get maya objects by name persp = pm.PyNode( 'persp' ) perspShape = pm.PyNode( 'perspShape' ) ## We can set attributes like this perspShape.nearClipPlane.set( 1.0 ) perspShape.farClipPlane.set( 99999 ) top = pm.PyNode( 'top' ) topShape = pm.PyNode( 'topShape' ) ## We can set attributes like this top.translateY.set( 44444 ) topShape.nearClipPlane.set( 1.0 ) topShape.farClipPlane.set( 99999 ) front = pm.PyNode( 'front' ) frontShape = pm.PyNode( 'frontShape' ) ## We can set attributes like this front.translateZ.set( 44444 ) frontShape.nearClipPlane.set( 1.0 ) frontShape.farClipPlane.set( 99999 ) side = pm.PyNode( 'side' ) sideShape = pm.PyNode( 'sideShape' ) ## We can set attributes like this side.translateX.set( 44444 ) sideShape.nearClipPlane.set( 1.0 ) sideShape.farClipPlane.set( 99999 )
def ConnectToAttr(src, trgt, attr): moveUVs = src.getShape().history(type='polyMoveUV') try: attr = pm.PyNode(trgt).attr(attr).getChildren() except: attr = [pm.PyNode(trgt).attr(attr)] if (len(moveUVs) > len(attr)): pm.warning( 'There are more polyMoveUV nodes that attrs to connect to %s:%s' % (len(moveUVs), len(attr))) else: for i, moveUV in enumerate(moveUVs): moveUV.translateV >> attr[i]
def saveRenderGlobal(): rgArnold = pm.PyNode('defaultArnoldDriver') rgArnoldRO = pm.PyNode('defaultArnoldRenderOptions') rgCommon = pm.PyNode('defaultRenderGlobals') rgRes = pm.PyNode('defaultResolution') # get renderInfo = {} for attr in rgArnold.listAttr(): try: renderInfo[attr.name()] = cmds.getAttr(attr.name()) except: pass for attr in rgCommon.listAttr(): try: renderInfo[attr.name()] = cmds.getAttr(attr.name()) except: pass for attr in rgRes.listAttr(): try: renderInfo[attr.name()] = cmds.getAttr(attr.name()) except: pass for attr in rgArnoldRO.listAttr(): try: renderInfo[attr.name()] = cmds.getAttr(attr.name()) except: pass # add data if pm.objExists('renderInfoNode'): lightInfoNode = pm.PyNode('renderInfoNode') lightInfoNode.unlock() pm.delete(lightInfoNode) lightInfoNode = pm.createNode('network', n='renderInfoNode') lightInfoNode.addAttr('renderInfo', dt='string') jsonHandl = json.dumps(renderInfo) lightInfoNode.attr('renderInfo').set(jsonHandl) lightInfoNode.attr('renderInfo').lock() print u'렌더 셋팅을 성공 적으로 저장 했습니다.'
def bind_card(source_mesh, target_mesh, combine=True): hasskin = True try: source_skin_cluster = pm.PyNode( pm.mel.eval('findRelatedSkinCluster %s' % (source_mesh))) joints = source_skin_cluster.getWeightedInfluence() except: hasskin = False if (combine): p = target_mesh.getParent() dup_source_mesh = source_mesh.duplicate()[0] dup_target_mesh = target_mesh.duplicate()[0] bind_mesh = pm.polyUnite(dup_source_mesh, dup_target_mesh)[0] bind_mesh.rename(target_mesh.name()) pm.delete(bind_mesh, ch=True) try: pm.delete(dup_source_mesh) except: pass else: bind_mesh = target_mesh if hasskin: target_skin_cluster = pm.skinCluster(bind_mesh, joints) pm.copySkinWeights(source_mesh, bind_mesh, ia='oneToOne', sa='closestPoint') pm.select(bind_mesh) th_skinClusterMerge.reduce_influences() pm.select(None)
def create_curves_from_mesh(mesh): global THU_MFT_ANGLE_TOLERANCE try: edges = mesh.edges except: pm.error('Could not get edges from %s' % (mesh)) edge_curve_group_name = mesh.name().split(':')[-1] + '_edgeCurve_GRP' try: edge_curve_group = pm.PyNode(edge_curve_group_name) except: edge_curve_group = pm.group(name=edge_curve_group_name, world=True, empty=True) converted_edges = [] for c, edge in enumerate(edges): if (edge not in converted_edges): print 'Processing edge %s of %s' % (c, len(edges)) merged_curve, edgeloop = __create_curve_from_edge(edge) pm.select(None) converted_edges.extend(edgeloop) # print merged_curve if (merged_curve): merged_curve.setParent(edge_curve_group) return edge_curve_group
def merge_cards(start, end, suit): cards = [] # suits = [ 'Hearts', 'Diamonds', 'Clubs', 'Spades' ] ranks = range(start, end) total_cards = len(ranks) i = 0 # for suit in suits : try: suit_group = pm.PyNode('%s_cards_GRP' % (suit)) except: suit_group = pm.group(name='%s_cards_GRP' % (suit), empty=True, world=True) for rank in ranks: print 'Processing card %s of %s' % (i, total_cards) # print rank, suit # print get_card_sprites( rank, suit ) # return card_sprites = pm.duplicate(get_card_sprites(rank, suit)) for card_sprite in card_sprites: card_sprite.setParent(None) card = pm.polyUnite(card_sprites, mergeUVSets=1, ch=True)[0] pm.delete(card, ch=True) for cs in card_sprites: try: pm.delete(cs) except: pass card.rename('%s_%s_G' % (suit, rank)) card.setParent(suit_group) cards.append(card) # pm.flushUndo() i += 1 return cards
def disp_uv_tile_val(self, sh, Utile, Vtile): tex = pm.PyNode(sh + "_2dTex") if Utile: Utile.setText(tex.repeatU.get()) if Vtile: Vtile.setText(tex.repeatV.get()) return None
def exportYeti(path): yeitInfo = getYetiInfo() if pm.objExists('yetiInfoNode'): yetiInfoNode = pm.PyNode('yetiInfoNode') yetiInfoNode.unlock() pm.delete(yetiInfoNode) attrName = 'yetiInfo' yetiInfoNode = pm.createNode('network', n='yetiInfoNode') yetiInfoNode.addAttr(attrName, dt='string') jsonHandl = json.dumps(yeitInfo) yetiInfoNode.attr(attrName).set(jsonHandl) yetiInfoNode.attr(attrName).lock() yetiInfoNode.lock() exportList = [yetiInfoNode] for _, shader in yeitInfo.items(): exportList.append(shader) pm.select(exportList) try: pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1) print 'Success Export Shader' except: print exportList print path finally: yetiInfoNode.unlock() pm.delete(yetiInfoNode)
def tile_uv_val(self, sh, U, V, Uval, Vval, inc, uText, vText): tex = pm.PyNode(sh + "_2dTex") if not pm.objExists(tex): pm.displayError("texture does not exist") return None if U: if Uval: u_val = float(Uval.getText()) tex.repeatU.set(u_val) else: u_val = tex.repeatU.get() if inc: tex.repeatU.set(u_val + 1) else: if (u_val - 1) > 0: tex.repeatU.set(u_val - 1) if V: if Vval: v_val = float(Vval.getText()) tex.repeatV.set(v_val) else: v_val = tex.repeatV.get() if inc: tex.repeatV.set(v_val + 1) else: if (v_val - 1) > 0: tex.repeatV.set(v_val - 1) if uText or vText: self.disp_uv_tile_val(sh, uText, vText) return None
def getCameras(): camShapes = pm.ls(type='camera') defalutCams = [] usedCams = [] itemsInfo = [] for dc in ['persp', 'top', 'front', 'side', 'back', 'left', 'bottom']: if pm.objExists(dc): defalutCams.append(pm.PyNode(dc)) for shape in camShapes: usedCams.append(shape.getParent()) validCams = list(set(usedCams) - set(defalutCams)) for node in validCams: itemsInfo.append({ 'namespace': '', 'rootNode': node.name(), 'abcAsset': '', 'abcPath': '', 'label': node.name(), 'nodeType': 'cam' }) return itemsInfo
def joints_along_curve(**kwargs): number_of_joints = kwargs.get("number_of_joints", 2) bind_curve = kwargs.get("bind_curve_to_joint", False) curve = kwargs.get("curve", None) if not isinstance(curve, pm.PyNode): curve = pm.PyNode(bind_curve) crv_len = curve.length() parts = number_of_joints - 1 div = float(crv_len) / float(parts) len_lst = [0] inc = 0 for i in range(1, parts + 1): inc += div len_lst.append(inc) joint_lst = [] for val in len_lst: pm.select(clear=True) param = curve.findParamFromLength(val) point = curve.getPointAtParam(param) jnt = pm.joint(position=point, radius=3) joint_lst.append(jnt) if bind_curve: pm.skinCluster(joint_lst, curve) return joint_lst
def network(self): if self.message.connections(): for obj in self.message.connections(): if obj.hasAttr('_class'): return obj elif self.hasAttr('Network'): return pymel.PyNode(self.Network.get())
def limb_grp(self): # Using mel to speed up the code for obj in cmds.ls(type='transform'): if cmds.attributeQuery('Utility', node=obj, exists=True) and\ cmds.getAttr('{}.Utility'.format(obj)) == 'LimbGrp' and\ cmds.attributeQuery('Network', node=obj, exists=True) and\ cmds.getAttr('{}.Network'.format(obj)) == self.network.name(): return pymel.PyNode(obj)
def assign_shader(self, sh, Utile, Vtile): self.sel = pm.ls(selection=True) if not pm.objExists(sh): self.create_shader(sh) pm.select(self.sel) pm.hyperShade(assign=pm.PyNode(sh)) self.disp_uv_tile_val(sh, Utile, Vtile) return None
def getAllCtrls(self): # todo: Add support for multiple rigs in a scene. nodes = [] for obj in cmds.ls(type='transform'): if cmds.attributeQuery('Type', node=obj, exists=True) and cmds.getAttr( '{}.Type'.format(obj)) == 'CTRL': nodes.append(pymel.PyNode(obj)) return nodes
def __group(name, parent): try: grp = pm.PyNode('%s|%s' % (parent, name)) # if( len(grp.getChildren(type=pm.Shape)) > 0 ) : # return None # else : # return grp except: grp = pm.group(name=name, parent=parent, empty=True) return grp
def deleteShader(mod): try: pm.select(mod) lambert = pm.PyNode('lambert1') pm.hyperShade(assign=lambert) pm.select(cl=True) pm.mel.eval('MLdeleteUnused;') return True except: return False
def refreshArsenalPassMember(self, myRenderLayer = None, progressBarUpdate = None): if myRenderLayer.name() != 'defaultRenderLayer': if pm.getAttr(myRenderLayer.name() + '.global') == 0: myMemberRenderLayer = myRenderLayer.listMembers(fullNames=True) if myMemberRenderLayer is None: return myMemberRenderLayer = list(set(myMemberRenderLayer)) myMemberArsenalPass = pm.PyNode(myRenderLayer.name() + '_arsenalPass.passMembers').inputs(shapes=True) difference = list(set(myMemberRenderLayer).symmetric_difference(set(myMemberArsenalPass))) if difference: for (i, myMember,) in enumerate(difference): if not pm.PyNode(myMember + '.message').isConnectedTo(myRenderLayer.name() + '_arsenalPass.passMembers', checkOtherArray=True): if progressBarUpdate is not None: progressBarUpdate(numStep=len(difference), value=i, text='Pass ' + myRenderLayer.name() + ' step 1 : connect passMembers %v of %m ...') pm.connectAttr(myMember + '.message', myRenderLayer.name() + '_arsenalPass.passMembers', force=True, nextAvailable=True) else: if progressBarUpdate is not None: progressBarUpdate(numStep=len(difference), value=i, text='Pass ' + myRenderLayer.name() + ' step 1 : disconnect passMembers %v of %m ...') pm.PyNode(myMember + '.message').disconnect(destination=myRenderLayer.name() + '_arsenalPass.passMembers', nextAvailable=True)
def get_attr_name(self): # Return attributes of type enum from selected controller self.ctr = self.ctr[0] attrs = pm.listAttr(self.ctr, keyable=True) enum_attr_list = [] for at in attrs: at_typ = pm.PyNode(str(self.ctr) + "." + at).type() if at_typ == "enum": enum_attr_list.append(at) return enum_attr_list
def get_path_name(self): path_name = self.curve_name.getText() if not path_name: return self.INVALID_INPUT_FAIL if not pm.objExists(path_name): return self.NO_OBJECT_FAIL shape_node = pm.PyNode(path_name).getShape() if not isinstance(shape_node, pm.NurbsCurve): return self.DATA_TYPE_FAIL return self.curve_name.getText()
def getLimbCtrls(self): nodes = [] for obj in cmds.ls(type='transform'): if cmds.attributeQuery('Network', node=obj, exists=True) and\ cmds.getAttr('{}.Network'.format(obj)) == self.network.name() and \ cmds.attributeQuery('Type', node=obj, exists=True) and \ cmds.getAttr('{}.Type'.format(obj)) == 'CTRL': nodes.append(pymel.PyNode(obj)) return nodes
def getCtrlRig(self): """Return all control rig nodes, ignore skinning joints""" nodes = [] for obj in cmds.ls(type='transform'): if cmds.attributeQuery('Network', node=obj, exists=True) and\ cmds.getAttr('{}.Network'.format(obj)) == self.network.name() and obj not in self.jnts: nodes.append(pymel.PyNode(obj)) return nodes
def set_color(self, **kwargs): obj = kwargs.get("obj", None) if not obj: return None if isinstance(obj, list): obj = obj[0] obj = pm.PyNode(obj) sh = obj.getShape() sh.overrideEnabled.set(1) sh.overrideColor.set(random.choice(self.color_list)) return None