bradon

edge to joint v11

Feb 18th, 2013
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.23 KB | None | 0 0
  1.  
  2. #===============================================================================
  3. # Create Joints on Edges
  4. # author: Bradon Webb
  5. # 02/17/13
  6. #
  7. #
  8. # To use script select edges from a polygon mesh in order that you want the joint chain
  9. # run script and it will make joints where each edge was.
  10. #
  11. # You need to manually do a rigid bind the joints to the mesh
  12. #===============================================================================
  13.  
  14. import maya.cmds as mc
  15. import maya.OpenMaya as om
  16. import pymel.core as pm
  17. import math
  18.  
  19.  
  20. def getDistance(vec1, vec2):
  21.     '''
  22.    @summary:
  23.        test two points in space to determine which one is bigger
  24.    @arguments:
  25.            two point vectors
  26.    @returns:
  27.            the differnce between the two points
  28.    '''
  29.    
  30.     dist = vec1 - vec2
  31.     # normalize to 1
  32.     distNormalize = dist.normal()
  33.    
  34.     # round values for easy reading
  35.     distRounded = om.MVector(round(distNormalize.x,2), round(distNormalize.y,2), round(distNormalize.z,2))
  36.    
  37.     #print 'RAW:', dist
  38.     print 'ROUNDED:', distRounded.x,distRounded.y,distRounded.z
  39.     print 'NORMALIZED', distNormalize
  40.    
  41.     return dist
  42.     #return math.sqrt(dist.x**2 + dist.y**2 + dist.z**2)
  43.  
  44.  
  45. def createHierarchy(nodeList=['object1,object2']):
  46.     '''
  47.    @summary:
  48.        will create a hierarchy chain, simmilar to a joint hierarchy out of a list of objects
  49.    @arguments:
  50.        list of object names
  51.    @returns:
  52.        nothing
  53.    '''
  54.     #reverse the list
  55.     nodeList.reverse()
  56.    
  57.     # get the length of the list
  58.     selectionLength = len(nodeList)
  59.    
  60.     # Loop through the selection list
  61.     for index, node in enumerate(nodeList):
  62.         # Check to make sure its not the last element in the list
  63.         if index < (selectionLength - 1):
  64.             # parent the node to the previously selected node
  65.             mc.parent(node, nodeList[index + 1])            
  66.             # Debuggin
  67.             #print "node", node
  68.             #print "child", nodeList[index + 1]
  69.             #print "index", index
  70.  
  71.  
  72. def calculateEdgeCenter(edge='polyObject.e[0]'):
  73.     '''
  74.    @summary:
  75.        gets the worldspace center given edge
  76.        libraries pymel, openMaya
  77.    @arguments:
  78.        edge = name of the edge as a string
  79.    @returns:
  80.        worldspace XYZ coordinates of the center of that edge
  81.   '''
  82.     edge = pm.MeshEdge(edge)
  83.    
  84.     # get the centerpoint of the edge
  85.     edgept = edge.__apimfn__().center(om.MSpace.kWorld)
  86.     edgecenterPoint = pm.datatypes.Point(edgept)
  87.    
  88.     print 'EDGECENTER:', edgecenterPoint
  89.     return edgecenterPoint
  90.  
  91. def getVertexNormal(edge):
  92.     '''
  93.    @summary:
  94.        gets the vertex normal given an edge
  95.    @arguments:
  96.            name of an edge
  97.    @returns:
  98.            the normal of the first vertex attached to the edge
  99.    '''
  100.  
  101.     vtxfaces = mc.polyListComponentConversion(edge, fromEdge=True, toVertexFace=True)
  102.     flatnormals = mc.polyNormalPerVertex(vtxfaces, q=True, xyz=True)
  103.  
  104.     normals = []
  105.     normals = zip(*[iter(flatnormals)]*3)
  106.    
  107.     #print 'NORMAL:', normals[0]
  108.     return normals[0]
  109.  
  110. def createLineVector(point1 = om.MVector(0,0,0), point2 = om.MVector(1,1,0), name='vector'):
  111.     '''
  112.    @summary:
  113.        given two point MVectors create a line - good for visualizing normals and angles
  114.    @arguments:
  115.        Point1 = MVector
  116.        point2 = MVector
  117.        name = string, names the created line
  118.    @returns:
  119.        curve name
  120.    '''
  121.  
  122.     newCurve = mc.curve(name=name, worldSpace=True, degree=1,
  123.                         point=[(point1.x, point1.y, point1.z),
  124.                                (point2.x, point2.y, point2.z)])
  125.     return newCurve
  126.  
  127. def calculateRotations(pointOrigin=[0,0,0], pointX=[1,0,0], pointUP=[0,1,0]):
  128.     '''
  129.    @summary:
  130.        calculates Euler rotation values 3 point locations (MVector)
  131.    @arguments:
  132.        pointOrigin = position of origin point (MVector)
  133.        pointX = position of x point (MVector)
  134.        pointUP = position of up point (MVector)
  135.    @returns:
  136.        Euler rotation to rotate the object back
  137.        [x,y,z]
  138.    '''
  139.     #rotOrder = mc.getAttr('%s.rotateOrder'%node)
  140.     # hard code rotation order to xyz
  141.     rotOrder = 0
  142.    
  143.     # Get Point Positions
  144.     originPosition = pointOrigin
  145.     XDirection = pointX
  146.     UPDirection = pointUP
  147.     #worldOrigin = om.MVector(0,0,0)
  148.    
  149.     # Subtract Positions for Vector
  150.     UpVector = originPosition - UPDirection
  151.          
  152.     XAxis = XDirection - originPosition
  153.     ZAxis = UpVector^XAxis
  154.     YAxis = ZAxis^XAxis
  155.    
  156.     # Debugging
  157.     #print 'XAxis:', XAxis.x, XAxis.y, XAxis.z
  158.     #print 'UpVector:', UpVector.x, UpVector.y, UpVector.z
  159.     #print 'ZAxis:', ZAxis.x, ZAxis.y, ZAxis.z
  160.     #print 'YAxis:', YAxis.x, YAxis.y, YAxis.z
  161.        
  162.     XAxisNormalize = XAxis.normal()
  163.     YAxisNormalize = YAxis.normal()
  164.     ZAxisNormalize = ZAxis.normal()
  165.        
  166.     # Create lines in space for each axis: visual aid
  167.     #xNormalCurve = createLineVector(point1=worldOrigin, point2=XAxisNormalize,  name='XAxisNormalize')
  168.     #yNormalCurve = createLineVector(point1=worldOrigin, point2=YAxisNormalize,  name='YAxisNormalize')
  169.     #zNormalCurve = createLineVector(point1=worldOrigin, point2=ZAxisNormalize,  name='ZAxisNormalize')
  170.    
  171.     # Create axis group and move to origin point: visual aid
  172.     #waxisGroup = mc.group([xNormalCurve,yNormalCurve,zNormalCurve], name='{node}_axisGroup'.format(node=node))
  173.    
  174.     # Debugging            
  175.     #print 'XAxisNormalize:', XAxisNormalize.x, XAxisNormalize.y, XAxisNormalize.z
  176.     #print 'YAxisNormalize:', YAxisNormalize.x, YAxisNormalize.y, YAxisNormalize.z
  177.     #print 'ZAxisNormalize:', ZAxisNormalize.x, ZAxisNormalize.y, ZAxisNormalize.z
  178.        
  179.     # pack values into matrix      
  180.     matrix = om.MMatrix()
  181.        
  182.     om.MScriptUtil.setDoubleArray(matrix[0], 0, XAxisNormalize.x) # Sets the first row, first column
  183.     om.MScriptUtil.setDoubleArray(matrix[0], 1, XAxisNormalize.y) # Sets the first row, second column
  184.     om.MScriptUtil.setDoubleArray(matrix[0], 2, XAxisNormalize.z) # Sets the first row, third column
  185.        
  186.     om.MScriptUtil.setDoubleArray(matrix[1], 0, YAxisNormalize.x) # Sets the second row, first column
  187.     om.MScriptUtil.setDoubleArray(matrix[1], 1, YAxisNormalize.y) # Sets the second row, second column
  188.     om.MScriptUtil.setDoubleArray(matrix[1], 2, YAxisNormalize.z) # Sets the second row, third column
  189.        
  190.     om.MScriptUtil.setDoubleArray(matrix[2], 0, ZAxisNormalize.x) # Sets the third row, first column
  191.     om.MScriptUtil.setDoubleArray(matrix[2], 1, ZAxisNormalize.y) # Sets the third row, second column
  192.     om.MScriptUtil.setDoubleArray(matrix[2], 2, ZAxisNormalize.z) # Sets the third row, third column            
  193.        
  194.     # converts inverse matrix to center rotate points to 0
  195.     matrixInverse = matrix.inverse()
  196.        
  197.     # Convert to MTransformationMatrix to extract rotations
  198.     mTransformMtx = om.MTransformationMatrix(matrix)
  199.     mTransformMtxInverse = om.MTransformationMatrix(matrixInverse)
  200.                
  201.     # Get the euler rotations
  202.     eulerRot = mTransformMtx.eulerRotation()
  203.     eulerRotInverse = mTransformMtxInverse.eulerRotation()
  204.        
  205.     # sort to the proper rotate order
  206.     eulerRot.reorderIt(rotOrder)
  207.     eulerRotInverse.reorderIt(rotOrder)
  208.  
  209.     # convert radians to degrees
  210.     rotAngle = [math.degrees(angle) for angle in (eulerRot.x, eulerRot.y, eulerRot.z)]
  211.     rotAngleInverse = [math.degrees(angle) for angle in (eulerRotInverse.x, eulerRotInverse.y, eulerRotInverse.z)]
  212.        
  213.     print 'ANGLES: ', rotAngle
  214.     print "----------------------------"
  215.     #print 'ANGLES INVERSE:', rotAngleInverse
  216.        
  217.     #return rotAngleInverse, rotAngle
  218.     return rotAngle
  219.  
  220.  
  221. def createJointControls():
  222.     '''
  223.    @summary:
  224.        creates a joint at the center of every selected edge
  225.    @arguments:
  226.        needs a selection of edges
  227.    @returns:
  228.        JointChain
  229.    '''
  230.  
  231.     # This code works to retain the selected orderd
  232.     selectedEdgeList = mc.ls(orderedSelection=True, long=True)
  233.     #print 'EDGELIST:', selectedEdgeList
  234.  
  235.     # clear the selection
  236.     mc.select(clear=True)
  237.    
  238.     # create a list to store the joints
  239.     jointList = []
  240.    
  241.     numberOfEdges = len(selectedEdgeList)
  242.    
  243.     # for each edge in the list create a joint    
  244.     for index, selectedEdge in enumerate(selectedEdgeList):
  245.        
  246.         # test to make sure you are not on the last edge
  247.         if index < (numberOfEdges - 1):
  248.             # calculate the center of the next edge in the list
  249.             # this will be used to orient the joint
  250.             XDirection = om.MVector(calculateEdgeCenter(selectedEdgeList[index+1]))
  251.         else:
  252.             print "X_ DEFAULT"
  253.             XDirection = om.MVector(0,0,0)
  254.                    
  255.         # Main Function
  256.         # get the centerPoint this will be used for the joint center
  257.         edgeCenter = calculateEdgeCenter(selectedEdge)
  258.        
  259.         # Main Function
  260.         # get the Y axis of the Joint this will be used to get the up orientation
  261.         upVector = (getVertexNormal(selectedEdge))
  262.         #print 'UPVECTOR:', upVector
  263.        
  264.         mayaUPVector = om.MVector(upVector[0],upVector[1],upVector[2])
  265.         #print 'MAYAVECTOR:', mayaUPVector.x
  266.        
  267.         UPDirection = mayaUPVector + edgeCenter
  268.            
  269.         # create X Vector Visual Display    
  270.         #createLineVector(edgeCenter, XDirection, name='XVecotor')
  271.         #mc.select(clear=True)
  272.        
  273.         # Main Function
  274.         # get the rotation of the edge based on three points
  275.         rotationAngle = calculateRotations(pointOrigin=edgeCenter, pointX=XDirection, pointUP=UPDirection)
  276.        
  277.         # create Joint at the edge center and aligned to the edge
  278.         joint = mc.joint(position=edgeCenter, orientation=rotationAngle)
  279.        
  280.         # clear selection so the joints do not attach to one another
  281.         mc.select(clear=True)
  282.        
  283.         #append joint name to list
  284.         jointList.append(joint)
  285.    
  286.     # attach all the joints in a chain    
  287.     createHierarchy(nodeList=jointList)
  288.    
  289.     #newBindSkin " -byClosestPoint -toSkeleton";
  290.        
  291.  
  292. createJointControls()
Advertisement
Add Comment
Please, Sign In to add comment