def getSgWobbleCurve( curve ): import sgBFunction_dag wobbles = sgBFunction_dag.getNodeFromHistory( curve, 'sgWobbleCurve2' ) if not wobbles: follicles = sgBFunction_dag.getNodeFromHistory( curve, 'follicle' ) wobbles = sgBFunction_dag.getNodeFromHistory( follicles[0], 'sgWobbleCurve2' ) return wobbles[0]
def selectFollicles( targetMesh ): import sgBFunction_dag skinNode = sgBFunction_dag.getNodeFromHistory( targetMesh, 'skinCluster' )[0] topJnt = cmds.listConnections( skinNode+'.matrix[0]' )[0] dcmp = cmds.listConnections( topJnt, s=1, d=0, type='decomposeMatrix' )[0] topJntOrig = cmds.listConnections( dcmp, s=1, d=0 )[0] handle = cmds.listConnections( topJntOrig, d=1, s=0, type='ikHandle' )[0] crv = cmds.listConnections( handle+'.inCurve' )[0] cmds.select( sgBFunction_dag.getNodeFromHistory( crv, 'follicle' ) )
def setWobbleCurveRandom(wobbleCurves, randOffset=[0.0, 0.5], randLength=[0.2, 0.25], randRotate=[0, 0]): import random import sgBFunction_dag for curve in wobbleCurves: wobbleNode = sgBFunction_dag.getNodeFromHistory( curve, 'sgWobbleCurve2') if not wobbleNode: continue mmdc = cmds.listConnections(wobbleNode[0] + '.aimMatrix') if not mmdc: continue aimMatrixObj = cmds.listConnections(mmdc[0] + '.i[0]') if not aimMatrixObj: continue randomValueOffset = random.uniform(randOffset[0], randOffset[1]) randomValueLength = random.uniform(randLength[0], randLength[1]) randomValueRotate = random.uniform(randRotate[0], randRotate[1]) cmds.setAttr(curve + '.offset', randomValueOffset) cmds.setAttr(curve + '.waveLength', randomValueLength) cmds.setAttr(aimMatrixObj[0] + '.rotateY', randomValueRotate)
def getInfluenceAndWeightList( mesh, vertices = [] ): skinClusters = sgBFunction_dag.getNodeFromHistory( mesh, 'skinCluster' ) if not skinClusters: return None skinCluster = skinClusters[0] fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) ) plugWeightList = fnSkinCluster.findPlug( 'weightList' ) if not vertices: vertices = [ i for i in range( plugWeightList.numElements() ) ] influenceAndWeightList = [ [] for i in range( len( vertices ) ) ] phygicalMap = [ 0 for i in range( plugWeightList.numElements() ) ] for i in range( len( vertices ) ): logicalIndex = vertices[i] plugWeights = plugWeightList[ logicalIndex ].child( 0 ) influenceNums = [] values = [] for j in range( plugWeights.numElements() ): influenceNum = plugWeights[j].logicalIndex() value = plugWeights[j].asFloat() influenceNums.append( influenceNum ) values.append( value ) influenceAndWeightList[i] = [ influenceNums, values ] phygicalMap[ logicalIndex ] = i return influenceAndWeightList, phygicalMap
def getInfluenceAndWeightList(mesh, vertices=[]): skinClusters = sgBFunction_dag.getNodeFromHistory(mesh, 'skinCluster') if not skinClusters: return None skinCluster = skinClusters[0] fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject(skinCluster)) plugWeightList = fnSkinCluster.findPlug('weightList') if not vertices: vertices = [i for i in range(plugWeightList.numElements())] influenceAndWeightList = [[] for i in range(len(vertices))] phygicalMap = [0 for i in range(plugWeightList.numElements())] for i in range(len(vertices)): logicalIndex = vertices[i] plugWeights = plugWeightList[logicalIndex].child(0) influenceNums = [] values = [] for j in range(plugWeights.numElements()): influenceNum = plugWeights[j].logicalIndex() value = plugWeights[j].asFloat() influenceNums.append(influenceNum) values.append(value) influenceAndWeightList[i] = [influenceNums, values] phygicalMap[logicalIndex] = i return influenceAndWeightList, phygicalMap
def setKeyCurve(keyCurve, targetCurve, objBaseMatrix=None): import sgBFunction_dag import sgBFunction_base sgBFunction_base.autoLoadPlugin('sgHair') nodes = sgBFunction_dag.getNodeFromHistory(targetCurve, 'sgHair_keyCurve') if not nodes: node = cmds.deformer(targetCurve, type='sgHair_keyCurve')[0] cmds.connectAttr('time1.outTime', node + '.time') if objBaseMatrix: mm = cmds.createNode('multMatrix') cmds.connectAttr(objBaseMatrix + '.wm', mm + '.i[0]') cmds.connectAttr(targetCurve + '.wim', mm + '.i[1]') cmds.connectAttr(mm + '.o', node + '.baseLocalMatrix') else: node = nodes[0] fnNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(node)) cuTime = cmds.currentTime(q=1) plugKeys = fnNode.findPlug('keys') targetIndex = 0 for i in range(plugKeys.numElements()): plugKey = plugKeys[i] plugFrame = plugKey.child(0) timeValue = plugFrame.asMTime().value() if cuTime == timeValue: targetIndex = plugKey.logicalIndex() break if plugKey.logicalIndex() >= targetIndex: targetIndex = plugKey.logicalIndex() + 1 if objBaseMatrix: import sgBFunction_convert mtxObj = cmds.getAttr(objBaseMatrix + '.wm') mtxInvCurve = cmds.getAttr(keyCurve + '.wim') mMtxObj = sgBFunction_convert.convertMatrixToMMatrix(mtxObj) mMtxInvCurve = sgBFunction_convert.convertMatrixToMMatrix(mtxInvCurve) mMtxLocal = mMtxObj * mMtxInvCurve mtxLocal = sgBFunction_convert.convertMMatrixToMatrix(mMtxLocal) cmds.setAttr(node + '.keys[%d].baseMatrix' % targetIndex, mtxLocal, type='matrix') cmds.setAttr(node + '.keys[%d].keyframe' % targetIndex, cuTime) keyCurveShape = sgBFunction_dag.getShape(keyCurve) if not cmds.isConnected(keyCurveShape + '.local', node + '.keys[%d].inputCurve' % targetIndex): cmds.connectAttr(keyCurveShape + '.local', node + '.keys[%d].inputCurve' % targetIndex, f=1) '''
def selectOutJoint( targetMesh ): import sgBFunction_dag skinNode = sgBFunction_dag.getNodeFromHistory( targetMesh, 'skinCluster' )[0] topJnt = cmds.listConnections( skinNode+'.matrix[0]' )[0] cmds.select( topJnt )
def selectOrigJoint( targetMesh ): import sgBFunction_dag skinNode = sgBFunction_dag.getNodeFromHistory( targetMesh, 'skinCluster' )[0] topJnt = cmds.listConnections( skinNode+'.matrix[0]' )[0] dcmp = cmds.listConnections( topJnt, s=1, d=0, type='decomposeMatrix' )[0] topJntOrig = cmds.listConnections( dcmp, s=1, d=0 )[0] handle = cmds.listConnections( topJntOrig, d=1, s=0, type='ikHandle' )[0] crv = cmds.listConnections( handle+'.inCurve' )[0] follicle = sgBFunction_dag.getNodeFromHistory( crv, 'follicle' )[0] curves = sgBFunction_dag.getNodeFromHistory( follicle, 'nurbsCurve' ) mmdc = cmds.listConnections( curves[-1]+'.controlPoints[0]' )[0] jnt = cmds.listConnections( mmdc+'.i[0]' )[0] cmds.select( jnt )
def setKeyCurve( keyCurve, targetCurve, objBaseMatrix = None ): import sgBFunction_dag import sgBFunction_base sgBFunction_base.autoLoadPlugin( 'sgHair' ) nodes = sgBFunction_dag.getNodeFromHistory( targetCurve, 'sgHair_keyCurve' ) if not nodes: node = cmds.deformer( targetCurve, type= 'sgHair_keyCurve' )[0] cmds.connectAttr( 'time1.outTime', node+'.time' ) if objBaseMatrix: mm = cmds.createNode( 'multMatrix' ) cmds.connectAttr( objBaseMatrix+'.wm', mm+'.i[0]' ) cmds.connectAttr( targetCurve+'.wim', mm+'.i[1]' ) cmds.connectAttr( mm+'.o', node+'.baseLocalMatrix' ) else: node = nodes[0] fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( node ) ) cuTime = cmds.currentTime( q=1 ) plugKeys = fnNode.findPlug( 'keys' ) targetIndex = 0 for i in range( plugKeys.numElements() ): plugKey = plugKeys[i] plugFrame = plugKey.child( 0 ) timeValue = plugFrame.asMTime().value() if cuTime == timeValue: targetIndex = plugKey.logicalIndex() break if plugKey.logicalIndex() >= targetIndex: targetIndex = plugKey.logicalIndex() + 1 if objBaseMatrix: import sgBFunction_convert mtxObj = cmds.getAttr( objBaseMatrix+'.wm' ) mtxInvCurve = cmds.getAttr( keyCurve+'.wim' ) mMtxObj = sgBFunction_convert.convertMatrixToMMatrix( mtxObj ) mMtxInvCurve = sgBFunction_convert.convertMatrixToMMatrix( mtxInvCurve ) mMtxLocal = mMtxObj * mMtxInvCurve mtxLocal = sgBFunction_convert.convertMMatrixToMatrix( mMtxLocal ) cmds.setAttr( node+'.keys[%d].baseMatrix' % targetIndex, mtxLocal, type='matrix' ) cmds.setAttr( node+'.keys[%d].keyframe' % targetIndex, cuTime ) keyCurveShape = sgBFunction_dag.getShape( keyCurve ) if not cmds.isConnected( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex ): cmds.connectAttr( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex, f=1 ) '''
def replaceObject( source, target ): import sgRigDag import sgRigSkinCluster import sgBFunction_dag skinClusters = sgBFunction_dag.getNodeFromHistory( target, 'skinCluster' ) if skinClusters: sgRigSkinCluster.replaceObjectSkined( source, target ) else: sgRigDag.replaceObject( source, target )
def replaceObject(source, target): import sgRigDag import sgRigSkinCluster import sgBFunction_dag skinClusters = sgBFunction_dag.getNodeFromHistory(target, 'skinCluster') if skinClusters: sgRigSkinCluster.replaceObjectSkined(source, target) else: sgRigDag.replaceObject(source, target)
def separateMeshBySkinWeight(meshObj): import sgBFunction_connection skinClusters = sgBFunction_dag.getNodeFromHistory(meshObj, 'skinCluster') meshShape = sgBFunction_dag.getShape(meshObj) if not skinClusters: return [] skinCluster = skinClusters[0] fnMesh = om.MFnMesh(sgBFunction_dag.getMDagPath(meshShape)) jntsPerVertices = JointsPerVertices(skinCluster) polygonsPerJointArray = [ PolygonsPerJoint(meshShape) for i in range(len(jntsPerVertices.existConnectJoints)) ] vtxCountsPerPolygon = om.MIntArray() vtxIndices = om.MIntArray() fnMesh.getVertices(vtxCountsPerPolygon, vtxIndices) try: vtxIndexPerPolygon = 0 for i in range(fnMesh.numPolygons()): vtxCountPerPolygon = vtxCountsPerPolygon[i] for j in range(vtxCountPerPolygon): vtxIndex = vtxIndices[vtxIndexPerPolygon + j] jointIndex = jntsPerVertices.getJointIndex(vtxIndex) physicalIndex = jntsPerVertices.jointLogicalIndexMap[ jointIndex] polygonsPerJointArray[physicalIndex].check(i) vtxIndexPerPolygon += vtxCountPerPolygon except: print "errorMesh : ", meshObj return [] meshs = [] for i in range(len(polygonsPerJointArray)): targetJoint = om.MFnDagNode( jntsPerVertices.existConnectJoints[i]).fullPathName() mesh = polygonsPerJointArray[i].buildMesh() mesh = cmds.rename(mesh, targetJoint.split('|')[-1] + '_mesh') cmds.sets(mesh, e=1, forceElement='initialShadingGroup') meshs.append(mesh) sgBFunction_connection.bindConnect(mesh, targetJoint) return meshs
def setBindPreMatrix( joint, bindPreObj, targetMesh ): skinNodes = sgBFunction_dag.getNodeFromHistory( targetMesh, 'skinCluster' ) if not skinNodes: return None cons = cmds.listConnections( joint+'.wm', type='skinCluster', p=1, c=1 ) for con in cons[1::2]: skinCluster = con.split( '.' )[0] if skinCluster != skinNodes[0]: continue index = int( con.split( '[' )[-1].replace( ']', '' ) ) if not cmds.isConnected( bindPreObj+'.wim', skinCluster+'.bindPreMatrix[%d]' % index ): cmds.connectAttr( bindPreObj+'.wim', skinCluster+'.bindPreMatrix[%d]' % index, f=1 )
def copySkinWeightFromSelection(): import sgBFunction_dag import sgBFunction_skinCluster sels = cmds.ls( sl=1 ) source = '' target = '' for sel in sels: skinNodes = sgBFunction_dag.getNodeFromHistory( sel, 'skinCluster' ) if skinNodes: source = sel else: target = sel if not source or not target: return None sgBFunction_skinCluster.autoCopyWeight( source, target ) return source, target
def importCacheData( folderPath ): import os for root, dirs, names in os.walk( folderPath ): for name in names: filePath = root + '/' + name if filePath[-4:].lower() != '.xml': continue meshName = name.split( '.' )[0] if not cmds.objExists( meshName ): cmds.warning( "%s is not exists" % meshName ) continue if sgBFunction_dag.getNodeFromHistory( meshName, 'cacheFile' ): continue sgBFunction_fileAndPath.importCache( meshName, filePath )
def setBindPreMatrix(joint, bindPreObj, targetMesh): skinNodes = sgBFunction_dag.getNodeFromHistory(targetMesh, 'skinCluster') if not skinNodes: return None cons = cmds.listConnections(joint + '.wm', type='skinCluster', p=1, c=1) for con in cons[1::2]: skinCluster = con.split('.')[0] if skinCluster != skinNodes[0]: continue index = int(con.split('[')[-1].replace(']', '')) if not cmds.isConnected(bindPreObj + '.wim', skinCluster + '.bindPreMatrix[%d]' % index): cmds.connectAttr(bindPreObj + '.wim', skinCluster + '.bindPreMatrix[%d]' % index, f=1)
def separateMeshBySkinWeight( meshObj ): import sgBFunction_connection skinClusters = sgBFunction_dag.getNodeFromHistory( meshObj, 'skinCluster' ) meshShape = sgBFunction_dag.getShape( meshObj ) if not skinClusters: return [] skinCluster = skinClusters[0] fnMesh = om.MFnMesh( sgBFunction_dag.getMDagPath( meshShape ) ) jntsPerVertices = JointsPerVertices( skinCluster ) polygonsPerJointArray = [ PolygonsPerJoint( meshShape ) for i in range( len( jntsPerVertices.existConnectJoints ) ) ] vtxCountsPerPolygon = om.MIntArray() vtxIndices = om.MIntArray() fnMesh.getVertices( vtxCountsPerPolygon, vtxIndices ) try: vtxIndexPerPolygon = 0 for i in range( fnMesh.numPolygons() ): vtxCountPerPolygon = vtxCountsPerPolygon[i] for j in range( vtxCountPerPolygon ): vtxIndex = vtxIndices[ vtxIndexPerPolygon + j ] jointIndex = jntsPerVertices.getJointIndex( vtxIndex ) physicalIndex = jntsPerVertices.jointLogicalIndexMap[ jointIndex ] polygonsPerJointArray[ physicalIndex ].check( i ) vtxIndexPerPolygon += vtxCountPerPolygon except: print "errorMesh : ", meshObj return [] meshs = [] for i in range( len( polygonsPerJointArray ) ): targetJoint = om.MFnDagNode( jntsPerVertices.existConnectJoints[i] ).fullPathName() mesh = polygonsPerJointArray[i].buildMesh() mesh = cmds.rename( mesh, targetJoint.split( '|' )[-1] + '_mesh' ) cmds.sets( mesh, e=1, forceElement='initialShadingGroup' ) meshs.append( mesh ) sgBFunction_connection.bindConnect( mesh, targetJoint ) return meshs
def importCacheData(folderPath): import os for root, dirs, names in os.walk(folderPath): for name in names: filePath = root + '/' + name if filePath[-4:].lower() != '.xml': continue meshName = name.split('.')[0] if not cmds.objExists(meshName): cmds.warning("%s is not exists" % meshName) continue if sgBFunction_dag.getNodeFromHistory(meshName, 'cacheFile'): continue sgBFunction_fileAndPath.importCache(meshName, filePath)
def setWobbleCurveRotateRandom( wobbleCurves, randMin, randMax ): import random import sgBFunction_convert import sgBFunction_dag wobbleCurves = sgBFunction_convert.singleToList( wobbleCurves ) for curve in wobbleCurves: wobbleNode = sgBFunction_dag.getNodeFromHistory( curve, 'sgWobbleCurve2' ) if not wobbleNode: continue mmdc = cmds.listConnections( wobbleNode[0]+'.aimMatrix' ) if not mmdc: continue aimMatrixObj = cmds.listConnections( mmdc[0]+'.i[0]' ) if not aimMatrixObj: continue randomValueRotate = random.uniform( randMin, randMax ) cmds.setAttr( aimMatrixObj[0]+'.rotateY', randomValueRotate )
def setWobbleCurveRotateRandom(wobbleCurves, randMin, randMax): import random import sgBFunction_convert import sgBFunction_dag wobbleCurves = sgBFunction_convert.singleToList(wobbleCurves) for curve in wobbleCurves: wobbleNode = sgBFunction_dag.getNodeFromHistory( curve, 'sgWobbleCurve2') if not wobbleNode: continue mmdc = cmds.listConnections(wobbleNode[0] + '.aimMatrix') if not mmdc: continue aimMatrixObj = cmds.listConnections(mmdc[0] + '.i[0]') if not aimMatrixObj: continue randomValueRotate = random.uniform(randMin, randMax) cmds.setAttr(aimMatrixObj[0] + '.rotateY', randomValueRotate)
def setWobbleCurveRandom( wobbleCurves, randOffset=[0.0, 0.5], randLength= [0.2, 0.25], randRotate= [0, 0] ): import random import sgBFunction_dag for curve in wobbleCurves: wobbleNode = sgBFunction_dag.getNodeFromHistory( curve, 'sgWobbleCurve2' ) if not wobbleNode: continue mmdc = cmds.listConnections( wobbleNode[0]+'.aimMatrix' ) if not mmdc: continue aimMatrixObj = cmds.listConnections( mmdc[0]+'.i[0]' ) if not aimMatrixObj: continue randomValueOffset = random.uniform( randOffset[0], randOffset[1] ) randomValueLength = random.uniform( randLength[0], randLength[1] ) randomValueRotate = random.uniform( randRotate[0], randRotate[1] ) cmds.setAttr( curve+'.offset', randomValueOffset ) cmds.setAttr( curve+'.waveLength', randomValueLength ) cmds.setAttr( aimMatrixObj[0]+'.rotateY', randomValueRotate )
def weightHammerCurve( targets ): import maya.OpenMaya as om import sgBFunction_dag import sgCFnc_dag import sgModelDg def getWeights( plug ): childPlug = plug.child(0) numElements = childPlug.numElements() indicesAndValues = [] for i in range( numElements ): logicalIndex = childPlug[i].logicalIndex() value = childPlug[i].asFloat() indicesAndValues.append( [ logicalIndex, value ] ) return indicesAndValues def getMixWeights( first, second, rate ): invRate = 1.0-rate print first print second firstMaxIndex = first[-1][0] secondMaxIndex = second[-1][0] maxIndex = firstMaxIndex+1 if firstMaxIndex < secondMaxIndex: maxIndex = secondMaxIndex+1 firstLogicalMap = [ False for i in range( maxIndex ) ] secondLogicalMap = [ False for i in range( maxIndex ) ] for index, value in first: firstLogicalMap[ index ] = True for index, value in second: secondLogicalMap[ index ] = True returnTargets = [] for index, value in first: returnTargets.append( [index, invRate * value] ) for index, value in second: if firstLogicalMap[ index ]: for i in range( len( returnTargets ) ): wIndex = returnTargets[i][0] if wIndex == index: returnTargets[i][1] += rate * value break else: returnTargets.append( [index, rate * value] ) return returnTargets def clearArray( targetPlug ): plugChild = targetPlug.child( 0 ) targetInstances = [] for i in range( plugChild.numElements() ): targetInstances.append( plugChild[i].name() ) targetInstances.reverse() for i in range( len( targetInstances ) ): cmds.removeMultiInstance( targetInstances[i] ) node = targets[0].split( '.' )[0] skinClusterNodes = sgBFunction_dag.getNodeFromHistory( node, 'skinCluster' ) if not skinClusterNodes: return None fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinClusterNodes[0] ) ) plugWeightList = fnSkinCluster.findPlug( 'weightList' ) cmds.select( targets ) for dagPath, uArr, vArr, wArr in sgCFnc_dag.getMDagPathAndComponent(): fnCurve = om.MFnNurbsCurve( dagPath ) startNum = 0 lastNum = fnCurve.numCVs()-1 if uArr[-1] == lastNum: pass elif uArr[0] == startNum: pass elif uArr[0] == startNum and uArr[-1] == lastNum: pass else: weightStart = getWeights( plugWeightList[ uArr[0]-1 ] ) weightEnd = getWeights( plugWeightList[ uArr[-1]+1 ] ) length = uArr.length() for i in range( uArr.length() ): clearArray( plugWeightList[ uArr[i] ] ) plugWeightListEmelent = plugWeightList.elementByLogicalIndex( uArr[i] ) rate = float( i+1 ) / (length+2) weights = getMixWeights( weightStart, weightEnd, rate ) for index, value in weights: targetPlug = plugWeightListEmelent.child(0).elementByLogicalIndex( index ) cmds.setAttr( targetPlug.name(), value ) cmds.skinPercent( skinClusterNodes[0], normalize=1 )
def createCurveFromSelVertices_mirror(targetCurve): import sgBFunction_dag def getMeshAndIndices(targetCurve): curveShape = sgBFunction_dag.getShape(targetCurve) inputNode = curveShape crvToPointNode = None mtxFromVtxNode = None num = 0 while True: num += 1 if num >= 100: break cons = cmds.listConnections(inputNode, s=1, d=0, p=1, c=1) if not cons: return None outputCon = cons[1] node = outputCon.split('.')[0] targetNodeType = cmds.nodeType(node) if targetNodeType == 'sgCurveFromPoints': crvToPointNode = node inputNode = node continue if targetNodeType == 'sgMatrixFromVertices': mtxFromVtxNode = node break inputNode = node mesh = cmds.listConnections(mtxFromVtxNode + '.inputMesh', s=1, d=0)[0] print "crvToPointNode : ", crvToPointNode fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject(crvToPointNode)) plugInputs = fnNode.findPlug('input') indices = [] for i in range(plugInputs.numElements()): connections = om.MPlugArray() plugInputPoint = plugInputs[i].child(1) plugInputPoint.connectedTo(connections, True, False) indices.append(connections[0].logicalIndex()) return mesh, indices def createCurve(mesh, indices): vtsToCrv = cmds.createNode('sgMatrixFromVertices') pointToCrv = cmds.createNode('sgCurveFromPoints') crv = cmds.createNode('nurbsCurve') cmds.connectAttr(pointToCrv + '.outputCurve', crv + '.create') cmds.connectAttr(mesh + '.outMesh', vtsToCrv + '.inputMesh') cmds.connectAttr(mesh + '.wm', vtsToCrv + '.inputMeshMatrix') for i in range(len(indices)): cmds.setAttr(vtsToCrv + '.verticeId[%d]' % indices[i], indices[i]) cmds.connectAttr(vtsToCrv + '.outputTranslate[%d]' % indices[i], pointToCrv + '.input[%d].inputPoint' % i) return crv, pointToCrv mesh, indices = getMeshAndIndices(targetCurve) mesh = sgBFunction_dag.getShape(mesh) dagPathMesh = sgBFunction_dag.getMDagPath(mesh) intersector = om.MMeshIntersector() intersector.create(dagPathMesh.node()) meshMtx = dagPathMesh.inclusiveMatrix() meshMtxInv = dagPathMesh.inclusiveMatrixInverse() fnMesh = om.MFnMesh(dagPathMesh) pArr = om.MPointArray() fnMesh.getPoints(pArr) targetIndices = [] pointOnMesh = om.MPointOnMesh() for index in indices: worldPoint = pArr[index] * meshMtx mirrorPoint = om.MPoint(-worldPoint.x, worldPoint.y, worldPoint.z) * meshMtxInv intersector.getClosestPoint(mirrorPoint, pointOnMesh) fIndex = pointOnMesh.faceIndex() vtxIndices = om.MIntArray() fnMesh.getPolygonVertices(fIndex, vtxIndices) closeDist = 1000000.0 closeIndex = vtxIndices[0] for vtxIndex in vtxIndices: point = pArr[vtxIndex] dist = point.distanceTo(mirrorPoint) if dist < closeDist: closeDist = dist closeIndex = vtxIndex targetIndices.append(closeIndex) node = sgBFunction_dag.getNodeFromHistory(targetCurve, 'sgCurveFromPoints')[0] createType = cmds.getAttr(node + '.createType') degrees = cmds.getAttr(node + '.degrees') createdCrv, createdNode = createCurve(mesh, targetIndices) cmds.setAttr(createdNode + '.createType', createType) cmds.setAttr(createdNode + '.degrees', degrees)
def createCurveFromSelVertices_mirror( targetCurve ): import sgBFunction_dag def getMeshAndIndices( targetCurve ): curveShape = sgBFunction_dag.getShape( targetCurve ) inputNode = curveShape crvToPointNode = None mtxFromVtxNode = None num = 0 while True: num += 1 if num >= 100: break cons = cmds.listConnections( inputNode, s=1, d=0, p=1, c=1 ) if not cons: return None outputCon = cons[1] node = outputCon.split( '.' )[0] targetNodeType = cmds.nodeType( node ) if targetNodeType == 'sgCurveFromPoints': crvToPointNode = node inputNode = node continue if targetNodeType == 'sgMatrixFromVertices': mtxFromVtxNode = node break inputNode = node mesh = cmds.listConnections( mtxFromVtxNode+'.inputMesh', s=1, d=0 )[0] print "crvToPointNode : ", crvToPointNode fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( crvToPointNode ) ) plugInputs = fnNode.findPlug( 'input' ) indices = [] for i in range( plugInputs.numElements() ): connections = om.MPlugArray() plugInputPoint = plugInputs[i].child( 1 ) plugInputPoint.connectedTo( connections, True, False ) indices.append( connections[0].logicalIndex() ) return mesh, indices def createCurve( mesh, indices ): vtsToCrv = cmds.createNode( 'sgMatrixFromVertices' ) pointToCrv = cmds.createNode( 'sgCurveFromPoints' ) crv = cmds.createNode( 'nurbsCurve' ) cmds.connectAttr( pointToCrv+'.outputCurve', crv+'.create' ) cmds.connectAttr( mesh+'.outMesh', vtsToCrv+'.inputMesh' ) cmds.connectAttr( mesh+'.wm', vtsToCrv+'.inputMeshMatrix' ) for i in range( len( indices ) ): cmds.setAttr( vtsToCrv+'.verticeId[%d]' % indices[i], indices[i] ) cmds.connectAttr( vtsToCrv+'.outputTranslate[%d]' % indices[i], pointToCrv+'.input[%d].inputPoint' % i ) return crv, pointToCrv mesh, indices = getMeshAndIndices( targetCurve ) mesh = sgBFunction_dag.getShape( mesh ) dagPathMesh = sgBFunction_dag.getMDagPath( mesh ) intersector = om.MMeshIntersector() intersector.create( dagPathMesh.node() ) meshMtx = dagPathMesh.inclusiveMatrix() meshMtxInv = dagPathMesh.inclusiveMatrixInverse() fnMesh = om.MFnMesh( dagPathMesh ) pArr = om.MPointArray() fnMesh.getPoints( pArr ) targetIndices = [] pointOnMesh = om.MPointOnMesh() for index in indices: worldPoint = pArr[ index ] * meshMtx mirrorPoint = om.MPoint( -worldPoint.x, worldPoint.y, worldPoint.z )*meshMtxInv intersector.getClosestPoint( mirrorPoint, pointOnMesh ) fIndex = pointOnMesh.faceIndex() vtxIndices = om.MIntArray() fnMesh.getPolygonVertices( fIndex, vtxIndices ) closeDist = 1000000.0 closeIndex = vtxIndices[0] for vtxIndex in vtxIndices: point = pArr[ vtxIndex ] dist = point.distanceTo( mirrorPoint ) if dist < closeDist: closeDist = dist closeIndex = vtxIndex targetIndices.append( closeIndex ) node = sgBFunction_dag.getNodeFromHistory( targetCurve, 'sgCurveFromPoints' )[0] createType = cmds.getAttr( node + '.createType' ) degrees = cmds.getAttr( node+'.degrees' ) createdCrv, createdNode = createCurve( mesh, targetIndices ) cmds.setAttr( createdNode + '.createType', createType ) cmds.setAttr( createdNode + '.degrees', degrees )
def setWeightInnerPointsToTargetJoint( baseMesh, baseJoint, targetMeshs ): import sgBFunction_dag baseMeshShape = sgBFunction_dag.getShape( baseMesh ) dagPathBaseMesh = sgBFunction_dag.getMDagPath( baseMeshShape ) mtxBaseMesh = dagPathBaseMesh.inclusiveMatrix() headIntersector = om.MMeshIntersector() headIntersector.create( dagPathBaseMesh.node() ) targetMeshs = cmds.ls( sl=1 ) for targetMesh in targetMeshs: skinNodes = sgBFunction_dag.getNodeFromHistory( targetMesh ,'skinCluster') if not skinNodes: continue skinNode = skinNodes[0] fnSkinNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinNode ) ) joints = cmds.listConnections( skinNode+'.matrix', s=1, d=0 ) if not baseJoint in joints: continue indexInfluence = joints.index( baseJoint ) plugWeightList = fnSkinNode.findPlug( 'weightList' ) targetMeshShape = sgBFunction_dag.getShape( targetMesh ) dagPathTargetMesh = sgBFunction_dag.getMDagPath( targetMeshShape ) fnTargetMesh = om.MFnMesh( dagPathTargetMesh ) mtxTarget = dagPathTargetMesh.inclusiveMatrix() mtxToBase = mtxTarget * mtxBaseMesh.inverse() numVertices = fnTargetMesh.numVertices() pointsTarget = om.MPointArray() fnTargetMesh.getPoints( pointsTarget ) pointOnMesh = om.MPointOnMesh() targetVertices = [] for i in range( numVertices ): pointLocal = pointsTarget[i] * mtxToBase headIntersector.getClosestPoint( pointLocal, pointOnMesh ) point = pointOnMesh.getPoint() normal = om.MVector( pointOnMesh.getNormal() ) vDir = om.MVector( pointLocal ) - om.MVector( point ) if vDir * normal > 0: continue plugWeights = plugWeightList[i].child( 0 ) for j in range( plugWeights.numElements() ): cmds.setAttr( plugWeights.name() + "[%d]" % j, 0 ) cmds.setAttr( plugWeights.name() + "[%d]" % indexInfluence, 1 ) targetVertices.append( targetMesh+'.vtx[%d]' % i ) cmds.select( targetVertices )
def createRivetBasedOnSkinWeights( selectedObjs ): import sgBFunction_convert import sgBFunction_mesh import sgBFunction_dag import sgBFunction_skinCluster import maya.OpenMaya as om def getJointMultMatrix( jnt, mtxBindPre ): cons = cmds.listConnections( jnt+'.wm', type='multMatrix' ) if cons: for con in cons: if cmds.attributeQuery( 'skinWeightInfluenceMatrix', node=con, ex=1 ): if mtxBindPre == cmds.getAttr( con+'.i[0]' ): return con mmtxNode = cmds.createNode( 'multMatrix' ) cmds.setAttr( mmtxNode+'.i[0]', mtxBindPre, type='matrix' ) cmds.connectAttr( jnt+'.wm', mmtxNode+'.i[1]' ) cmds.addAttr( mmtxNode, ln='skinWeightInfluenceMatrix', at='message' ) return mmtxNode mesh, vtxIndices = sgBFunction_mesh.getMeshAndIndicesPoints( selectedObjs ) skinClusterNode = sgBFunction_dag.getNodeFromHistory( mesh, 'skinCluster' ) if not skinClusterNode: return None skinClusterNode = skinClusterNode[0] influenceAndWeightList, phygicalMap = sgBFunction_skinCluster.getInfluenceAndWeightList( mesh, vtxIndices ) meshMatrix = sgBFunction_dag.getMDagPath( mesh ).inclusiveMatrix() meshPoints = sgBFunction_mesh.getLocalPoints( mesh ) plugMatrix = sgBFunction_skinCluster.getPlugMatrix( mesh ) plugBindPre = sgBFunction_skinCluster.getPlugBindPre( mesh ) BB = om.MBoundingBox() wtAddMtx = cmds.createNode( 'wtAddMatrix' ) mtxPlugIndidcesAndWeights = {} allWeights = 0.0 for i in vtxIndices: influenceList, weights = influenceAndWeightList[ phygicalMap[i] ] for j in range( len( influenceList ) ): mtxPlugIndex = influenceList[j] if mtxPlugIndex in mtxPlugIndidcesAndWeights.keys(): mtxPlugIndidcesAndWeights[mtxPlugIndex] += weights[j] else: mtxPlugIndidcesAndWeights.update( {mtxPlugIndex:weights[j]} ) allWeights += weights[j] BB.expand( meshPoints[i] ) worldPoint = BB.center()*meshMatrix items = mtxPlugIndidcesAndWeights.items() for i in range( len( items ) ): influence, weight = items[i] plugMatrixElement = plugMatrix.elementByLogicalIndex( influence ) plugBindPreElement = plugBindPre.elementByLogicalIndex( influence ) jnt = cmds.listConnections( plugMatrixElement.name(), s=1, d=0, type='joint' )[0] mtxBindPre = cmds.getAttr( plugBindPreElement.name() ) mmtxNode = getJointMultMatrix( jnt, mtxBindPre ) cmds.connectAttr( mmtxNode+'.o', wtAddMtx+'.i[%d].m' % i ) cmds.setAttr( wtAddMtx+'.i[%d].w' % i, weight/allWeights ) origObj = cmds.createNode( 'transform', n='OrigObject' ) destObj = cmds.createNode( 'transform', n='destObject' ) cmds.setAttr( destObj+'.dh' , 1 ) cmds.setAttr( destObj+'.dla', 1 ) mmNode = cmds.createNode( 'multMatrix' ) dcmp = cmds.createNode( 'decomposeMatrix' ) mtxWtAdd = cmds.getAttr( wtAddMtx+'.o' ) cmds.connectAttr( origObj+'.wm', mmNode+'.i[0]' ) cmds.connectAttr( wtAddMtx+'.o', mmNode+'.i[1]' ) cmds.connectAttr( destObj+'.pim', mmNode+'.i[2]' ) cmds.connectAttr( mmNode+'.o', dcmp+'.imat' ) cmds.connectAttr( dcmp+'.ot', destObj+'.t' ) cmds.connectAttr( dcmp+'.or', destObj+'.r' ) mmtxWtAdd = sgBFunction_convert.convertMatrixToMMatrix( mtxWtAdd ) worldPoint *= mmtxWtAdd.inverse() cmds.setAttr( origObj+'.t', worldPoint.x, worldPoint.y, worldPoint.z )
def setWeightInnerPointsToTargetJoint(baseMesh, baseJoint, targetMeshs): import sgBFunction_dag baseMeshShape = sgBFunction_dag.getShape(baseMesh) dagPathBaseMesh = sgBFunction_dag.getMDagPath(baseMeshShape) mtxBaseMesh = dagPathBaseMesh.inclusiveMatrix() headIntersector = om.MMeshIntersector() headIntersector.create(dagPathBaseMesh.node()) targetMeshs = cmds.ls(sl=1) for targetMesh in targetMeshs: skinNodes = sgBFunction_dag.getNodeFromHistory(targetMesh, 'skinCluster') if not skinNodes: continue skinNode = skinNodes[0] fnSkinNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(skinNode)) joints = cmds.listConnections(skinNode + '.matrix', s=1, d=0) if not baseJoint in joints: continue indexInfluence = joints.index(baseJoint) plugWeightList = fnSkinNode.findPlug('weightList') targetMeshShape = sgBFunction_dag.getShape(targetMesh) dagPathTargetMesh = sgBFunction_dag.getMDagPath(targetMeshShape) fnTargetMesh = om.MFnMesh(dagPathTargetMesh) mtxTarget = dagPathTargetMesh.inclusiveMatrix() mtxToBase = mtxTarget * mtxBaseMesh.inverse() numVertices = fnTargetMesh.numVertices() pointsTarget = om.MPointArray() fnTargetMesh.getPoints(pointsTarget) pointOnMesh = om.MPointOnMesh() targetVertices = [] for i in range(numVertices): pointLocal = pointsTarget[i] * mtxToBase headIntersector.getClosestPoint(pointLocal, pointOnMesh) point = pointOnMesh.getPoint() normal = om.MVector(pointOnMesh.getNormal()) vDir = om.MVector(pointLocal) - om.MVector(point) if vDir * normal > 0: continue plugWeights = plugWeightList[i].child(0) for j in range(plugWeights.numElements()): cmds.setAttr(plugWeights.name() + "[%d]" % j, 0) cmds.setAttr(plugWeights.name() + "[%d]" % indexInfluence, 1) targetVertices.append(targetMesh + '.vtx[%d]' % i) cmds.select(targetVertices)
def weightHammerCurve(targets): import maya.OpenMaya as om import sgBFunction_dag import sgCFnc_dag import sgModelDg def getWeights(plug): childPlug = plug.child(0) numElements = childPlug.numElements() indicesAndValues = [] for i in range(numElements): logicalIndex = childPlug[i].logicalIndex() value = childPlug[i].asFloat() indicesAndValues.append([logicalIndex, value]) return indicesAndValues def getMixWeights(first, second, rate): invRate = 1.0 - rate print first print second firstMaxIndex = first[-1][0] secondMaxIndex = second[-1][0] maxIndex = firstMaxIndex + 1 if firstMaxIndex < secondMaxIndex: maxIndex = secondMaxIndex + 1 firstLogicalMap = [False for i in range(maxIndex)] secondLogicalMap = [False for i in range(maxIndex)] for index, value in first: firstLogicalMap[index] = True for index, value in second: secondLogicalMap[index] = True returnTargets = [] for index, value in first: returnTargets.append([index, invRate * value]) for index, value in second: if firstLogicalMap[index]: for i in range(len(returnTargets)): wIndex = returnTargets[i][0] if wIndex == index: returnTargets[i][1] += rate * value break else: returnTargets.append([index, rate * value]) return returnTargets def clearArray(targetPlug): plugChild = targetPlug.child(0) targetInstances = [] for i in range(plugChild.numElements()): targetInstances.append(plugChild[i].name()) targetInstances.reverse() for i in range(len(targetInstances)): cmds.removeMultiInstance(targetInstances[i]) node = targets[0].split('.')[0] skinClusterNodes = sgBFunction_dag.getNodeFromHistory(node, 'skinCluster') if not skinClusterNodes: return None fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject(skinClusterNodes[0])) plugWeightList = fnSkinCluster.findPlug('weightList') cmds.select(targets) for dagPath, uArr, vArr, wArr in sgCFnc_dag.getMDagPathAndComponent(): fnCurve = om.MFnNurbsCurve(dagPath) startNum = 0 lastNum = fnCurve.numCVs() - 1 if uArr[-1] == lastNum: pass elif uArr[0] == startNum: pass elif uArr[0] == startNum and uArr[-1] == lastNum: pass else: weightStart = getWeights(plugWeightList[uArr[0] - 1]) weightEnd = getWeights(plugWeightList[uArr[-1] + 1]) length = uArr.length() for i in range(uArr.length()): clearArray(plugWeightList[uArr[i]]) plugWeightListEmelent = plugWeightList.elementByLogicalIndex( uArr[i]) rate = float(i + 1) / (length + 2) weights = getMixWeights(weightStart, weightEnd, rate) for index, value in weights: targetPlug = plugWeightListEmelent.child( 0).elementByLogicalIndex(index) cmds.setAttr(targetPlug.name(), value) cmds.skinPercent(skinClusterNodes[0], normalize=1)
def getSkinClusterFromMesh( mesh ): return sgBFunction_dag.getNodeFromHistory( mesh, 'skinCluster' )
def combineSkinCluster(skinedObjs): import sgBFunction_dag numVertices = None for skinedObj in skinedObjs: objShape = sgBFunction_dag.getShape(skinedObj) fnMesh = om.MFnMesh(sgBFunction_dag.getMDagPath(objShape)) if not numVertices: numVertices = fnMesh.numVertices() else: if numVertices != fnMesh.numVertices(): cmds.error("Selected meshs not same objects") skinJoints = [] weightList = [[] for i in range(numVertices)] for skinedObj in skinedObjs: skinCluster = sgBFunction_dag.getNodeFromHistory( skinedObj, 'skinCluster') if not skinCluster: continue skinCluster = skinCluster[0] fnNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(skinCluster)) plugMatrix = fnNode.findPlug('matrix') plugMatrixMaxLogicalIndex = 0 for i in range(plugMatrix.numElements()): logicalIndex = plugMatrix[i].logicalIndex() if logicalIndex > plugMatrixMaxLogicalIndex: plugMatrixMaxLogicalIndex = logicalIndex connections = om.MPlugArray() skinedJointIndices = [] origSkinedJointIndicesMap = [ -1 for i in range(plugMatrixMaxLogicalIndex + 1) ] for i in range(plugMatrix.numElements()): plugMatrix[i].connectedTo(connections, True, False) if not connections.length(): continue skinJointName = om.MFnDagNode(connections[0].node()).fullPathName() if not skinJointName in skinJoints: skinJoints.append(skinJointName) jntIndex = skinJoints.index(skinJointName) origSkinedJointIndicesMap[plugMatrix[i].logicalIndex()] = jntIndex skinedJointIndices.append(jntIndex) plugWeightList = fnNode.findPlug('weightList') for i in range(plugWeightList.numElements()): plugWeights = plugWeightList[i].child(0) for j in range(plugWeights.numElements()): logicalIndex = plugWeights[j].logicalIndex() weightValue = plugWeights[j].asFloat() jntIndex = origSkinedJointIndicesMap[logicalIndex] weightList[i].append([jntIndex, weightValue]) newMesh = cmds.createNode('mesh') srcShape = sgBFunction_dag.getShape(skinedObjs[0]) newMeshObj = sgBFunction_dag.getParent(newMesh) cmds.connectAttr(srcShape + '.outMesh', newMesh + '.inMesh') cmds.refresh() cmds.disconnectAttr(srcShape + '.outMesh', newMesh + '.inMesh') node = cmds.deformer(newMeshObj, type='skinCluster')[0] for i in range(len(skinJoints)): cmds.connectAttr(skinJoints[i] + '.wm', node + '.matrix[%d]' % i) bindPreMatrix = cmds.getAttr(skinJoints[i] + '.wim') cmds.setAttr(node + '.bindPreMatrix[%d]' % i, bindPreMatrix, type='matrix') for i in range(len(weightList)): for logicalIndex, value in weightList[i]: cmds.setAttr( node + '.weightList[%d].weights[%d]' % (i, logicalIndex), value) cmds.skinPercent(node, normalize=True)
def getSkinClusterFromMesh(mesh): return sgBFunction_dag.getNodeFromHistory(mesh, 'skinCluster')
def combineSkinCluster( skinedObjs ): import sgBFunction_dag numVertices = None for skinedObj in skinedObjs: objShape = sgBFunction_dag.getShape( skinedObj ) fnMesh = om.MFnMesh( sgBFunction_dag.getMDagPath( objShape ) ) if not numVertices: numVertices = fnMesh.numVertices() else: if numVertices != fnMesh.numVertices(): cmds.error( "Selected meshs not same objects" ) skinJoints = [] weightList = [ [] for i in range( numVertices ) ] for skinedObj in skinedObjs: skinCluster = sgBFunction_dag.getNodeFromHistory( skinedObj, 'skinCluster' ) if not skinCluster: continue skinCluster = skinCluster[0] fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) ) plugMatrix = fnNode.findPlug( 'matrix' ) plugMatrixMaxLogicalIndex = 0 for i in range( plugMatrix.numElements() ): logicalIndex = plugMatrix[i].logicalIndex() if logicalIndex > plugMatrixMaxLogicalIndex: plugMatrixMaxLogicalIndex = logicalIndex connections = om.MPlugArray() skinedJointIndices = [] origSkinedJointIndicesMap = [ -1 for i in range( plugMatrixMaxLogicalIndex+1 ) ] for i in range( plugMatrix.numElements() ): plugMatrix[i].connectedTo( connections, True, False ) if not connections.length(): continue skinJointName = om.MFnDagNode( connections[0].node() ).fullPathName() if not skinJointName in skinJoints: skinJoints.append( skinJointName ) jntIndex = skinJoints.index( skinJointName ) origSkinedJointIndicesMap[ plugMatrix[i].logicalIndex() ] = jntIndex skinedJointIndices.append( jntIndex ) plugWeightList = fnNode.findPlug( 'weightList' ) for i in range( plugWeightList.numElements() ): plugWeights = plugWeightList[i].child( 0 ) for j in range( plugWeights.numElements() ): logicalIndex = plugWeights[j].logicalIndex() weightValue = plugWeights[j].asFloat() jntIndex = origSkinedJointIndicesMap[ logicalIndex ] weightList[i].append( [jntIndex, weightValue] ) newMesh = cmds.createNode( 'mesh' ) srcShape = sgBFunction_dag.getShape( skinedObjs[0] ) newMeshObj = sgBFunction_dag.getParent( newMesh ) cmds.connectAttr( srcShape+'.outMesh', newMesh+'.inMesh' ) cmds.refresh() cmds.disconnectAttr( srcShape+'.outMesh', newMesh+'.inMesh' ) node = cmds.deformer( newMeshObj, type='skinCluster' )[0] for i in range( len( skinJoints ) ): cmds.connectAttr( skinJoints[i]+'.wm', node+'.matrix[%d]' % i ) bindPreMatrix = cmds.getAttr( skinJoints[i]+'.wim' ) cmds.setAttr( node+'.bindPreMatrix[%d]' % i, bindPreMatrix, type='matrix' ) for i in range( len( weightList ) ): for logicalIndex, value in weightList[i]: cmds.setAttr( node+'.weightList[%d].weights[%d]' %( i, logicalIndex ), value ) cmds.skinPercent( node, normalize=True )