def transfer_rotation_to_joint_orient(obj): """ In Maya it is not possible to do a "makeIdentity" command on a joint that is bound to a skinCluster. This method bypass this limitation. """ mfn = obj.__apimfn__() rotation_orig = OpenMaya.MEulerRotation() mfn.getRotation(rotation_orig) rotation_xyz = rotation_orig.reorder(OpenMaya.MEulerRotation.kXYZ) # Apply existing jointOrient values orientation_orig = OpenMaya.MEulerRotation() mfn.getOrientation(orientation_orig) rotation_xyz *= orientation_orig def is_attr_accessible(attr): return not attr.isFreeToChange() == OpenMaya.MPlug.kFreeToChange if is_attr_accessible(obj.rotateX) or is_attr_accessible(obj.rotateY) or is_attr_accessible(obj.rotateZ): pymel.warning("Can't transfer rotation to joint orient. {0} rotation is locked.".format(obj.name())) return if is_attr_accessible(obj.jointOrientX) or is_attr_accessible(obj.jointOrientY) or is_attr_accessible(obj.jointOrientZ): pymel.warning("Can't transfer rotation to joint orient. {0} jointOrient is locked.".format(obj.name())) return obj.jointOrientX.set(math.degrees(rotation_xyz.x)) obj.jointOrientY.set(math.degrees(rotation_xyz.y)) obj.jointOrientZ.set(math.degrees(rotation_xyz.z)) obj.rotateX.set(0) obj.rotateY.set(0) obj.rotateZ.set(0)
def blendOrient(self, handle1, handle2, weight_Val, rotInter): valueList = [0, 0, 0] if weight_Val == 0.0: for k in range(3): valueList[k] = handle1[k] elif weight_Val == 1.0: for k in range(3): valueList[k] = handle2[k] else: if rotInter == 0: for k in range(3): valueList[k] = handle1[k] + (handle2[k] - handle1[k]) * weight_Val else: startEuler = OpenMaya.MEulerRotation(handle1[0], handle1[1], handle1[2], 0) reachEuler = OpenMaya.MEulerRotation(handle2[0], handle2[1], handle2[2], 0) startQuat = startEuler.asQuaternion() reachQuat = reachEuler.asQuaternion() blendQuat = self.slerp(startQuat, reachQuat, weight_Val) blendRot = blendQuat.asEulerRotation() valueList[0] = blendRot.x valueList[1] = blendRot.y valueList[2] = blendRot.z return valueList
def joint(name, parent=None, matrix=None, color=None, radius=1, useJointOrient=False): ''' Create a Joint node Args: name (str): Name of the node parent (str): Parent node matrix (math3d.Transformation||math3d.Matrix4||list of float): The world transformation color (triplet of float): Color of the shape radius (float): Size of the shape useJointOrient (bool): Use the jointOrient Attribute to set the rotation Returns: str ''' jnt = cmds.createNode("joint", name=name) cmds.setAttr(jnt + ".radius", radius) if parent: # Maya has a tendency to add an inbetween parent when parenting joint in absolute. m = cmds.xform(jnt, q=True, matrix=True, worldSpace=True) jnt = cmds.parent(jnt, parent, relative=True)[0] m = cmds.xform(jnt, matrix=m, worldSpace=True) attributes.setColor(jnt, color) # Transform if matrix is not None: attributes.setMatrix(jnt, matrix, worldSpace=True) if useJointOrient: # Because Joints are fun, you actually want the orientation # to be on the JointOrientation and not the Rotation # It only really matters when you use a ikhandle, but better safe than sorry rot = cmds.getAttr(jnt + ".rotate")[0] ori = cmds.getAttr(jnt + ".jointOrient")[0] eRot = om.MEulerRotation(math.radians(rot[0]), math.radians(rot[1]), math.radians(rot[2]), om.MEulerRotation.kXYZ) eOri = om.MEulerRotation(math.radians(ori[0]), math.radians(ori[1]), math.radians(ori[2]), om.MEulerRotation.kXYZ) qRot = eRot.asQuaternion() qOri = eOri.asQuaternion() q = qRot * qOri e = q.asEulerRotation() e = (math.degrees(e.x), math.degrees(e.y), math.degrees(e.z)) try: # The joint might be locked or connected, int that case we don't do anything. cmds.setAttr(jnt + ".rotate", 0, 0, 0) cmds.setAttr(jnt + ".jointOrient", *e) except: pass return jnt
def getRotationYEditMatrix( mouseX, mouseY ): import math if Window_global.ui_orientEditMode.currentText() == 'Only Y': srcPoint = Tool_global.intersectPoint srcViewPoint = Functions.worldPointToViewPoint( srcPoint ) mousePoint = OpenMaya.MPoint( mouseX, mouseY, 0 ) mouseWorldPoint = Functions.viewPointToWorldPoint( mousePoint ) srcViewPointToWorld = Functions.viewPointToWorldPoint( srcViewPoint ) directionVector = mouseWorldPoint - srcViewPointToWorld camVector = Functions.getCamVector() crossVector = directionVector ^ camVector viewPointVector = OpenMaya.MVector(mousePoint) - OpenMaya.MVector(srcViewPoint) rotValue = viewPointVector.x / Tool_global.targetViewSize * 45 trMtx = OpenMaya.MTransformationMatrix() euler = OpenMaya.MEulerRotation( 0.0,math.radians(rotValue),0.0 ) quat = euler.asQuaternion() trMtx.setRotationQuaternion( quat.x, quat.y, quat.z, quat.w ) return trMtx.asMatrix() else: return OpenMaya.MMatrix()
def testImportStaticPerspectiveCamera(self): (cameraFn, transformFn) = self._GetMayaCameraAndTransform('PerspCamStatic') self.assertTrue(Gf.IsClose(cameraFn.nearClippingPlane(), 0.1, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.farClippingPlane(), 10000.0, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.focalLength(), 35.0, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.focusDistance(), 5.0, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.fStop(), 11.0, 1e-6)) self.assertTrue( Gf.IsClose(cameraFn.horizontalFilmAperture(), 1.417322, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.horizontalFilmOffset(), 1.0, 1e-6)) self.assertFalse(cameraFn.isOrtho()) self.assertTrue( Gf.IsClose(cameraFn.verticalFilmAperture(), 0.944882, 1e-6)) self.assertTrue(Gf.IsClose(cameraFn.verticalFilmOffset(), 2.0, 1e-6)) rotation = OpenMaya.MEulerRotation() transformFn.getRotation(rotation) rotVec = Gf.Vec3d(self._ConvertRadiansToDegrees(rotation.x), self._ConvertRadiansToDegrees(rotation.y), self._ConvertRadiansToDegrees(rotation.z)) self.assertTrue(Gf.IsClose(rotVec, Gf.Vec3d(45.0, 0.0, 0.0), 1e-6)) translation = transformFn.getTranslation(OpenMaya.MSpace.kTransform) transVec = Gf.Vec3d(translation.x, translation.y, translation.z) self.assertTrue(Gf.IsClose(transVec, Gf.Vec3d(0.0, -5.0, 5.0), 1e-6)) # There should be no animation on either the camera shape or the transform. self.assertFalse(OpenMayaAnim.MAnimUtil.isAnimated(cameraFn.object())) self.assertFalse( OpenMayaAnim.MAnimUtil.isAnimated(transformFn.object()))
def align(src, tgt, key=False): ''' this is separated into a separate proc, because its less "user friendly" ie require less syntax to work its better to call zooAlign in non speed intensive operations because the syntax for this command may change if the scope of the script is expanded in future - ie I add more functionality ''' try: #grab the positions and rotations of the src object in world space srcRp = OpenMaya.MVector(*cmd.getAttr(src + '.rp')[0]) srcMatrix = api.getMDagPath(src).inclusiveMatrix() srcRp *= srcMatrix tgtRp = OpenMaya.MVector(*cmd.getAttr(tgt + '.rp')[0]) tgtMatrix = api.getMDagPath(tgt).exclusiveMatrix() tgtMatrixInv = api.getMDagPath(tgt).exclusiveMatrixInverse() tgtRp *= tgtMatrix print mayaVectors.MayaVector(tgtRp) xformMatrix = srcMatrix * tgtMatrixInv new = mayaVectors.MayaMatrix(xformMatrix) pos = new.get_position() - mayaVectors.MayaVector( tgtRp) + mayaVectors.MayaVector(srcRp) cmd.setAttr(tgt + '.t', *pos) cmd.setAttr(tgt + '.r', *new.get_rotXYZ(asdeg=True)) raise Exception srcRo = kM_ROOS[cmd.getAttr(src + ".ro")] tgtRo = kM_ROOS[cmd.getAttr(tgt + ".ro")] rot = OpenMaya.MVector(*cmd.xform(src, q=True, ws=True, ro=True)) rot = OpenMaya.MEulerRotation(rot, srcRo).asMatrix() tgtXformMatrixInv = api.getMDagPath(tgt).exclusiveMatrixInverse() except RuntimeError, x: print 'ERRR', x return
def rotateOutside(self, *rot): trMtx = OpenMaya.MTransformationMatrix() trMtx.rotateTo( OpenMaya.MEulerRotation(math.radians(rot[0]), math.radians(rot[1]), math.radians(rot[2]))) self.m = self.m * trMtx.asMatrix()
def alignToRef(self): if len(self.refVerts) == 0: cmds.error("Reference vertexes are not defined. Please define ref first.") selection = cmds.ls(sl=True, long=True) cmds.select(cmds.polyListComponentConversion(toVertex=True), replace=True) verts = cmds.filterExpand(sm=31, expand=True, fullPath=True) shape = str(self.refVerts[0]).split(".")[0] refTransform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0] shape = str(verts[0]).split(".")[0] objTransform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0] objTransformMatrixInverse = getTransformMatrix(objTransform).inverse() refRot = cmds.xform(refTransform, q=True, ws=True, ro=True) refAngle = om.MEulerRotation(math.radians(refRot[0]), math.radians(refRot[1]), math.radians(refRot[2]), om.MEulerRotation.kXYZ) for vert in verts: refVertIndex = self.findNearestVertIndex(vert) refNormal = cmds.polyNormalPerVertex(self.refVerts[refVertIndex], q=True, xyz=True) vec = om.MVector(refNormal[0], refNormal[1], refNormal[2]) refNormal = vec.rotateBy(refAngle) normalVector = om.MVector(refNormal[0], refNormal[1], refNormal[2]) newVector = normalVector * objTransformMatrixInverse # Assuming normals are equal for all triangles at this vert, and using the first triple. cmds.polyNormalPerVertex(vert, xyz=(newVector[0], newVector[1], newVector[2])) cmds.select(selection, r=True)
def CartesianToPolar(rotation): v = om.MVector(0, 0, 1) m = om.MTransformationMatrix() rotation = map(math.radians, rotation) e = om.MEulerRotation() e.setValue(rotation[0], rotation[1], rotation[2]) m.rotateBy(e, om.MSpace.kWorld) v = v * m.asMatrix() # r = math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z) # print "V", v.x, v.y, v.z, r # phi = math.pi/2.0 # theta = 1.0 # #if v.x != 0.0: # phi = math.atan2(v.y,v.x) # #if v.z != 0.0: # theta = math.atan2(math.sqrt(v.x * v.x + v.y * v.y),v.z) #if v.x != 0.0: # phi = math.atan(v.y/v.x) #else: # phi = math.pi/2.0 #theta = math.acos(v.z/r) theta = math.asin(v.y) phi = math.asin(v.z) t = math.degrees(theta) p = math.degrees(phi) if v.x < 0.0: p = 180 - p polar = (p, t) return polar
def rotate_into(self, direction, rotation): """ slerp the given rotation values into the direction given by the brush_state @param direction MVector: the target direction @param rotation MVector: current euler rotation """ vector_weight = self.brush_state.settings['strength'] up_vector = om.MVector(0, 1, 0) local_up = up_vector.rotateBy(om.MEulerRotation(math.radians(rotation.x), math.radians(rotation.y), math.radians(rotation.z))) target_rotation = om.MQuaternion(local_up, direction, vector_weight) util = om.MScriptUtil() x_rot = np.radians(rotation.x) y_rot = np.radians(rotation.y) z_rot = np.radians(rotation.z) util.createFromDouble(x_rot, y_rot, z_rot) rotation_ptr = util.asDoublePtr() mat = om.MTransformationMatrix() mat.setRotation(rotation_ptr, om.MTransformationMatrix.kXYZ) mat = mat.asMatrix() * target_rotation.asMatrix() rotation = om.MTransformationMatrix(mat).rotation() return om.MVector(math.degrees(rotation.asEulerRotation().x), math.degrees(rotation.asEulerRotation().y), math.degrees(rotation.asEulerRotation().z))
def OutputAnimationData(obj, outfilepath, sf, ef): dagNode = OpenMaya.MFnDagNode(obj) dagPath = dagNode.fullPathName() namefix = cleanMayaLongName(dagPath[1:]) outfilepath = 'C://' #DEBUG DEBUG fHandle = open((outfilepath + '/' + namefix + '.chan'), "w") MANIM = OpenMayaAnim.MAnimControl() for i in range(sf, ef): MANIM.setCurrentTime(OpenMaya.MTime(i)) fn = OpenMaya.MFnTransform(obj) TRANSLATION = fn.getTranslation(0) oiler = OpenMaya.MEulerRotation() ROTATION = fn.getRotation(oiler) ROTVEC = OpenMaya.MVector(oiler.asVector()) line = (str(TRANSLATION[0]) + ' ' + str(TRANSLATION[1]) + ' ' + str(TRANSLATION[2]) + ' ' + str(radian_to_degree(ROTVEC[0])) + ' ' + str(radian_to_degree(ROTVEC[1])) + ' ' + str(radian_to_degree(ROTVEC[2])) + '\n') fHandle.write(line) fHandle.close() MANIM.setCurrentTime(OpenMaya.MTime(0))
def getPointArrayWithOffset(point_pos, pos_offset=None, rot_offset=None): """Get Point array with offset Convert a list of vector to a List of float and add the position and rotation offset. Arguments: point_pos (list of vector): Point positions. pos_offset (vector): The position offset of the curve from its center. rot_offset (vector): The rotation offset of the curve from its center. In radians. Returns: list of vector: the new point positions """ points = [] for v in point_pos: if rot_offset: mv = om.MVector(v.x, v.y, v.z) mv = mv.rotateBy( om.MEulerRotation(rot_offset.x, rot_offset.y, rot_offset.z, om.MEulerRotation.kXYZ)) v = datatypes.Vector(mv.x, mv.y, mv.z) if pos_offset: v = v + pos_offset points.append(v) return points
def setRotate_keepJointOrient(mtx, jnt): jntP = cmds.listRelatives(jnt, p=1)[0] joValue = cmds.getAttr(jnt + '.jo')[0] joMEuler = om.MEulerRotation(math.radians(joValue[0]), math.radians(joValue[1]), math.radians(joValue[2])) joTransform = mpx.MPxTransformationMatrix(om.MMatrix()) joTransform.rotateBy(joMEuler) jo_im = joTransform.asMatrixInverse() jntP_wim_list = cmds.getAttr(jntP + '.wim') jntP_wim = om.MMatrix() om.MScriptUtil.createMatrixFromList(jntP_wim_list, jntP_wim) cuMtx = mtx * jntP_wim * jo_im transform = mpx.MPxTransformationMatrix(cuMtx) rot = transform.eulerRotation().asVector() degrees = [math.degrees(rot.x), math.degrees(rot.y), math.degrees(rot.z)] for i in range(len(degrees)): if degrees[i] > 180: degrees[i] = degrees[i] - 360 elif degrees[i] < -180: degrees[i] = degrees[i] + 360 cmds.setAttr(jnt + '.r', *degrees)
def rotateVector(vA, RotdegV): eRot = om.MEulerRotation(math.radians(RotdegV.x), math.radians(RotdegV.y), math.radians(RotdegV.z)) vB = vA.rotateBy(eRot) vB.x = round(vB.x, 6) vB.y = round(vB.y, 6) vB.z = round(vB.z, 6) return vB
def __init__(self): ompx.MPxLocatorNode.__init__(self) self.constraintVector = om.MVector() self.aimObjVector = om.MVector() self.upObjVector = om.MVector() self.projectedVector = om.MVector() self.aimEueler = om.MEulerRotation() self.theta = 0
def bdMain(): dagPath = om.MDagPath() mObj = om.MObject() selection = om.MSelectionList() status = om.MGlobal.getActiveSelectionList(selection) try: status = selection.getDependNode(0,mObj) except: sys.stderr.write('Nothing is selected, you need to select the IK handle') return if mObj.hasFn(om.MFn.kIkHandle): ikHandleFn = oma.MFnIkHandle(mObj) startJointPath = om.MDagPath() ikHandleFn.getStartJoint(startJointPath) startJointTransformNode = startJointPath.transform() startJointTransformFn = om.MFnTransform(startJointTransformNode) print startJointTransformFn.name() rotateOrientation = startJointTransformFn.rotateOrientation(om.MSpace.kTransform) rotateOrientationEuler = rotateOrientation .asEulerRotation() print 'Rotation axis', math.degrees(rotateOrientationEuler.x), math.degrees(rotateOrientationEuler.y), math.degrees(rotateOrientationEuler.z) matrix = om.MTransformationMatrix(startJointTransformFn.transformationMatrix()) rotOrderAxis = matrix.rotationOrder() print rotOrderAxis quatRotation = om.MQuaternion() startJointTransformFn.getRotation(quatRotation) eulerRotation = quatRotation.asEulerRotation() print 'Local Rotation ', math.degrees(eulerRotation.x), math.degrees(eulerRotation.y), math.degrees(eulerRotation.z) translation = matrix.getTranslation(om.MSpace.kWorld) print 'World transation', translation.x, translation.y, translation.z ikJoint = oma.MFnIkJoint(startJointTransformNode) jointOrient = om.MEulerRotation() quatJointOrient = om.MQuaternion() ikJoint.getRotation(quatJointOrient) ikJoint.getOrientation(jointOrient) print 'Joint orientation', math.degrees(jointOrient.x) , math.degrees(jointOrient.y), math.degrees(jointOrient.z) globalRot = om.MQuaternion() globalRot = rotateOrientation * quatRotation * quatJointOrient globalRotEuler = globalRot.asEulerRotation() print 'World orientation', math.degrees(globalRot.x) , math.degrees(globalRot.y), math.degrees(globalRot.z) print bdGetChainLength(ikJoint)
def getEulerRotationQuaternion(upvector, directionvector): ''' returns the x,y,z degree angle rotation corresponding to a direction vector input: upvector (MVector) & directionvector (MVector) ''' quat = om.MQuaternion(upvector, directionvector) quatAsEuler = om.MEulerRotation() quatAsEuler = quat.asEulerRotation() return math.degrees(quatAsEuler.x), math.degrees(quatAsEuler.y), math.degrees(quatAsEuler.z)
def alignAverage(self): if len(self.refVerts) == 0: cmds.error("Reference vertexes are not defined. Please define ref first.") selection = cmds.ls(sl=True, long=True) cmds.select(cmds.polyListComponentConversion(toVertex=True), replace=True) verts = cmds.filterExpand(sm=31, expand=True, fullPath=True) shape = str(self.refVerts[0]).split(".")[0] obj1Transform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0] n1Rot = cmds.xform(obj1Transform, q=True, ws=True, ro=True) n1Angle = om.MEulerRotation(math.radians(n1Rot[0]), math.radians(n1Rot[1]), math.radians(n1Rot[2]), om.MEulerRotation.kXYZ) shape = str(verts[0]).split(".")[0] obj2Transform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0] n2Rot = cmds.xform(obj2Transform, q=True, ws=True, ro=True) n2Angle = om.MEulerRotation(math.radians(n2Rot[0]), math.radians(n2Rot[1]), math.radians(n2Rot[2]), om.MEulerRotation.kXYZ) for vert in verts: refIndex = self.findNearestVertIndex(vert) vecData = cmds.polyNormalPerVertex(self.refVerts[refIndex], q=True, xyz=True) vec1 = om.MVector(vecData[0], vecData[1], vecData[2]) vec1 = vec1.rotateBy(n1Angle) vecData = cmds.polyNormalPerVertex(vert, q=True, xyz=True) vec2 = om.MVector(vecData[0], vecData[1], vecData[2]) vec2 = vec2.rotateBy(n2Angle) averageNormal = (vec1 + vec2) / 2.0 n1New = averageNormal * getTransformMatrix(obj1Transform).inverse() cmds.polyNormalPerVertex(self.refVerts[refIndex], xyz=(n1New.x, n1New.y, n1New.z)) n2New = averageNormal * getTransformMatrix(obj2Transform).inverse() cmds.polyNormalPerVertex(vert, xyz=(n2New.x, n2New.y, n2New.z)) cmds.select(selection, r=True)
def computeOffsetOrientation(self, offsetValue, controlValue, rotationOrder): blendvalue = [0, 0, 0] offsetMatrix = OpenMaya.MEulerRotation(offsetValue[0], offsetValue[1], offsetValue[2], 0).asMatrix() controlMatrix = OpenMaya.MEulerRotation(controlValue[0], controlValue[1], controlValue[2], rotationOrder).asMatrix() blendMatrix = controlMatrix * offsetMatrix matFn = OpenMaya.MTransformationMatrix(blendMatrix) blendRot = matFn.eulerRotation() blendvalue[0] = blendRot.x blendvalue[1] = blendRot.y blendvalue[2] = blendRot.z return blendvalue
def redoIt(self): ''' Create and manipulate the nodes to form the joint chain. ''' # Perform the operations enqueued within our reference to MDagModifier. self.dagModifier.doIt() # ======================================= # JOINT MANIPULATION # ======================================= # We can now use the function sets on the newly created DAG objects. jointFn = OpenMayaAnim.MFnIkJoint() for i in range(1, len(self.jointObjects)): jointFn.setObject(self.jointObjects[i]) # We set the orientation for our joint to be 'jointOrientation' degrees, to form an arc. # We use MFnIkJoint.setOrientation() instead of MFnTransform.setRotation() to let the # inverse-kinematic handle maintain the curvature. global jointOrientation rotationAngle = OpenMaya.MAngle(jointOrientation, OpenMaya.MAngle.kDegrees) jointFn.setOrientation( OpenMaya.MEulerRotation(rotationAngle.asRadians(), 0, 0, OpenMaya.MEulerRotation.kXYZ)) # We translate the joint by 'jointDistance' units along its parent's y axis. global jointDistance translationVector = OpenMaya.MVector(0, jointDistance, 0) jointFn.setTranslation(translationVector, OpenMaya.MSpace.kTransform) # ======================================= # IK HANDLE MANIPULATION # ======================================= # We will use the MEL command 'ikHandle' to create the handle which will move our joint chain. This command # will be enqueued in our reference to the MDagModifier so that it can be undone in our call to MDagModifier.undoIt(). # Obtain the DAG path of the first joint. startJointDagPath = OpenMaya.MDagPath() jointFn.setObject(self.jointObjects[0]) jointFn.getPath(startJointDagPath) # Obtain the DAG path of the effector. effectorDagPath = OpenMaya.MDagPath() effectorFn = OpenMayaAnim.MFnIkEffector(self.effectorObj) effectorFn.getPath(effectorDagPath) # Enqueue the following MEL command with the DAG paths of the start joint and the end effector. self.dagModifier.commandToExecute('ikHandle -sj ' + startJointDagPath.fullPathName() + ' -ee ' + effectorDagPath.fullPathName()) # We call MDagModifier.doIt() to effectively execute the MEL command and create the ikHandle. self.dagModifier.doIt()
def doIt(self, args): """ Parse arguments and then call doItQuery() """ # parse the arguments try: argData = om.MArgDatabase( self.syntax(), args) # if this fails, it will raise its own exception... except: pass # ...so we can just pass here else: # validate the provided selection list sList = om.MSelectionList() argData.getObjects(sList) iter = om.MItSelectionList(sList, om.MFn.kTransform) if iter.isDone( ) or not iter.itemType() == om.MItSelectionList.kDagSelectionItem: selectionStrings = [] sList.getSelectionStrings(selectionStrings) raise Exception('%s is not a valid transform node.\n' % selectionStrings[0]) iter.getDagPath(self.__transformPath) self.__transformFn.setObject(self.__transformPath) # establish the parameters for computation if argData.isFlagSet(AR_TransformCmd.kWorldSpaceFlag): self.__space = om.MSpace.kWorld # use the transform node's rotate order as the default value rotation = om.MEulerRotation() self.__transformFn.getRotation(rotation) self.__rotateOrder = rotation.order if argData.isFlagSet(AR_TransformCmd.kRotateOrderFlag): rotateOrderStr = argData.flagArgumentString( AR_TransformCmd.kRotateOrderFlag, 0) try: self.__rotateOrder = kRotateOrderMapping[ rotateOrderStr.lower()] except: self.displayWarning( '%s is not a valid rotate order. Rotate order of %s is being used instead.' % (rotateOrderStr, self.__transformPath.partialPathName())) # determine which flags are set and perform the query self.__translationArg = argData.isFlagSet( AR_TransformCmd.kTranslationFlag) self.__rotationArg = argData.isFlagSet( AR_TransformCmd.kRotationFlag) self.__quaternionArg = argData.isFlagSet( AR_TransformCmd.kQuaternionFlag) self.doItQuery()
def getPointArrayWithOffset(point_pos, pos_offset=None, rot_offset=None): points = [] for v in point_pos: if rot_offset: mv = om.MVector(v.x,v.y,v.z) mv = mv.rotateBy(om.MEulerRotation(rot_offset.x, rot_offset.y, rot_offset.z, om.MEulerRotation.kXYZ)) v = dt.Vector(mv.x,mv.y,mv.z) if pos_offset: v = v + pos_offset points.append(v) return points
def euler2mat(_euler, _roo, degrees=True): roo = _roo.lower() if degrees: rx = _euler[0] * Deg2Rad ry = _euler[1] * Deg2Rad rz = _euler[2] * Deg2Rad else: rx = _euler[0] ry = _euler[1] rz = _euler[2] euler = OM.MEulerRotation(rx, ry, rz, rooStr2Int[roo]) return euler.asMatrix()
def checkUpAxis(self, matrix): """ Check the scene's up axis, and convert the given transform matrix if necessary. """ if OpenMaya.MGlobal.isYAxisUp(): tMatrix = OpenMaya.MTransformationMatrix( matrix ) tMatrix.rotateBy( OpenMaya.MEulerRotation(math.radians(90), 0, 0), OpenMaya.MSpace.kTransform ) oTrans = tMatrix.getTranslation(OpenMaya.MSpace.kTransform) oTrans = OpenMaya.MVector( oTrans[0], -oTrans[2], oTrans[1] ) tMatrix.setTranslation(oTrans, OpenMaya.MSpace.kTransform) return self.checkScale( tMatrix.asMatrix() ) else: return self.checkScale( matrix )
def compute(self, plug, dataBlock): if plug == RotateByNode.outMatrix: dataHandleJointOrient = dataBlock.inputValue(RotateByNode.inRotate) # input rotate is defined in radians inputRotate = dataHandleJointOrient.asDouble3() dataHandleInMatrix = dataBlock.inputValue(RotateByNode.inMatrix) inMatrix = dataHandleInMatrix.asMatrix() matrixList = [[ OpenMaya.MScriptUtil.getDoubleArrayItem(inMatrix[row], col) for col in range(4) ] for row in range(4)] print 'in Matrix' print matrixList # This is our rotation order rotOrder = OpenMaya.MEulerRotation.kXYZ # Create the MEulerRotation inputEuler = OpenMaya.MEulerRotation(inputRotate[0], inputRotate[1], inputRotate[2], rotOrder) # Get the quaternion equivalent inputQuaternion = inputEuler.asQuaternion() inputQuaternionInvert = inputQuaternion.inverse() # inverse the quaternion worldTransformMatrix = OpenMaya.MTransformationMatrix(inMatrix) # get out matrix outTransformMatrix = worldTransformMatrix.rotateBy( inputQuaternionInvert, OpenMaya.MSpace.kTransform) outMatrix = outTransformMatrix.asMatrix() matrixList = [[ OpenMaya.MScriptUtil.getDoubleArrayItem(outMatrix[row], col) for col in range(4) ] for row in range(4)] print 'out Matrix:' print matrixList dataHandleOutMatrix = dataBlock.outputValue(RotateByNode.outMatrix) dataHandleOutMatrix.setMMatrix(outMatrix) dataBlock.setClean(plug) else: return "UnKnown"
def set_ktransform(self, mobject, data): mfn_transform = OpenMaya.MFnTransform(mobject) tx, ty, tz = data['translate'] translate_mvector = OpenMaya.MVector(tx, ty, tz) mfn_transform.setTranslation(translate_mvector, OpenMaya.MSpace.kTransform) radians = [math.radians(x) for x in data['rotate']] euler_rotation = OpenMaya.MEulerRotation(radians[0], radians[1], radians[2]) mfn_transform.setRotation(euler_rotation) scale_util = OpenMaya.MScriptUtil() scale_util.createFromList(data['scale'], 3) double = scale_util.asDoublePtr() mfn_transform.setScale(double) return mfn_transform
def euler_to_quat(rot): """ Converts euler to quaternion :param rot: :return: """ # This is our rotation order rotOrder = om.MEulerRotation.kXYZ # Create the MEulerRotation euler = om.MEulerRotation(math.radians(rot[0]), math.radians(rot[1]), math.radians(rot[2]), rotOrder) # Get the quaternion equivalent quaternion = euler.asQuaternion() # Access the components return [quaternion.x, quaternion.y, quaternion.z, quaternion.w]
def getLocalAxes(self, eulerRotAngle, isEulerAngle=True): axisX = OpenMaya.MVector(1, 0, 0) axisY = OpenMaya.MVector(0, 1, 0) axisZ = OpenMaya.MVector(0, 0, 1) if (isEulerAngle == True): for i in range(3): eulerRotAngle[i] = eulerRotAngle[i] * (self.PI / 180.0) rot = OpenMaya.MEulerRotation(eulerRotAngle[0], eulerRotAngle[1], eulerRotAngle[2], OpenMaya.MEulerRotation.kXYZ) axisX = axisX.rotateBy(rot) axisY = axisY.rotateBy(rot) axisZ = axisZ.rotateBy(rot) tempAxis = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]] for i in range(3): tempAxis[0][i] = axisX[i] tempAxis[1][i] = axisY[i] tempAxis[2][i] = axisZ[i] return tempAxis
def vectorTwinSpaceMirror(self,vector,master,twin,pivot,axis): ''' Transform a vector to twin local space after mirroring across the pivot object's specified axis @param vector: The vector to be transformed @type vector: list @param master: Vectors initial local space object (parent) @type master: string @param twin: Vectors destination local space object @type twin: string @param pivot: Pivot object across which the vector will be mirrored @type pivot: string @param axis: Axis across which the vector will be mirrored @type axis: string or int ''' # Check inputs if not mc.objExists(master): raise Exception('Master object '+master+' does not exist') if not mc.objExists(twin): raise Exception('Twin object '+twin+' does not exist') if not mc.objExists(pivot): raise Exception('Pivot object '+pivot+' does not exist') # Get Twin Parent twinParent = '' try: twinParent = str(mc.listRelatives(twin,p=1)[0]) except: pass if type(axis) == str: axis = self.axisIndex[axis] # Get vector in world space vector = self.transformVector(vector,master,transformAsPoint=False,invertTransform=False) # Mirror vector across pivot axis vector = self.transformVector(vector,pivot,transformAsPoint=False,invertTransform=True) vector[axis] *= -1 vector = self.transformVector(vector,pivot,transformAsPoint=False,invertTransform=False) # Get axis in local twin local space if twinParent: vector = self.transformVector(vector,twinParent,transformAsPoint=False,invertTransform=True) # Compensate for joint orientation if mc.objectType(twin) == 'joint': jointOrient = mc.getAttr(twin+'.jointOrient')[0] jointOrient = [jointOrient[i]/self.radian for i in range(3)] jointOrientMatrix = OpenMaya.MEulerRotation(jointOrient[0],jointOrient[1],jointOrient[2],0).asMatrix() vector = OpenMaya.MVector(vector[0],vector[1],vector[2]) * jointOrientMatrix.inverse() return vector
def OutputTransform(obj, mode): output = [] if obj.hasFn(OpenMaya.MFn.kTransform) == 0: print 'ERROR NO XFORM DETECTED' if obj.hasFn(OpenMaya.MFn.kTransform): XFORMNODE = OpenMaya.MFnTransform(obj) TRANSLATION = XFORMNODE.getTranslation(0) #TRANSLATION if mode == 't': output.append(TRANSLATION[0]) output.append(TRANSLATION[1]) output.append(TRANSLATION[2]) ###ROTATION if mode == 'r': oiler = OpenMaya.MEulerRotation() ROTATION = XFORMNODE.getRotation(oiler) ROTVEC = OpenMaya.MVector(oiler.asVector()) output.append(radian_to_degree(ROTVEC[0])) output.append(radian_to_degree(ROTVEC[1])) output.append(radian_to_degree(ROTVEC[2])) return output