Python maya.OpenMaya.MScriptUtil() Examples

The following are 29 code examples for showing how to use maya.OpenMaya.MScriptUtil(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module maya.OpenMaya , or try the search function .

Example 1
Project: spore   Author: wiremas   File: spore_sampler.py    License: MIT License 6 votes vote down vote up
def sample_triangle(self,triangle_id, point_id):
        """ sample a random point on a the given triangle """

        r = random.random()
        s = random.random()

        if r + s >= 1:
            r = 1 - r
            s = 1 - s

        r = om.MScriptUtil(r).asFloat()
        s = om.MScriptUtil(s).asFloat()

        r = self.geo_cache.AB[triangle_id] * r
        s = self.geo_cache.AC[triangle_id] * s

        p = om.MPoint(r + s + om.MVector(self.geo_cache.p0[triangle_id]))
        u = 0
        v = 0

        self.point_data.set(point_id, p, self.geo_cache.normals[triangle_id],
                            self.geo_cache.poly_id[triangle_id], u, v) 
Example 2
Project: spore   Author: wiremas   File: spore_sampler.py    License: MIT License 6 votes vote down vote up
def get_rotation(self, direction, weight, min_rot, max_rot):
        """ get rotation from a matrix pointing towards the given direction
        slerped by the given weight into the world up vector and added a random
        rotation between min and max rotation """

        r_x = math.radians(random.uniform(min_rot[0], max_rot[0]))
        r_y = math.radians(random.uniform(min_rot[1], max_rot[1]))
        r_z = math.radians(random.uniform(min_rot[2], max_rot[2]))
        util = om.MScriptUtil()
        util.createFromDouble(r_x, r_y, r_z)
        rotation_ptr = util.asDoublePtr()

        matrix = om.MTransformationMatrix()
        matrix.setRotation(rotation_ptr, om.MTransformationMatrix.kXYZ)
        world_up = om.MVector(0, 1, 0)
        rotation = om.MQuaternion(world_up, direction, weight)
        matrix = matrix.asMatrix() * rotation.asMatrix()
        rotation = om.MTransformationMatrix(matrix).rotation().asEulerRotation()

        return om.MVector(math.degrees(rotation.x),
                          math.degrees(rotation.y),
                          math.degrees(rotation.z)) 
Example 3
Project: spore   Author: wiremas   File: brush_state.py    License: MIT License 6 votes vote down vote up
def world_to_view(self, position, invert_y=True):
        """ convert the given 3d position to 2d viewpor coordinates
        :param invert_y bool: convert between qt and maya coordinane space """

        view = window_utils.active_view()
        x_util = om.MScriptUtil()
        y_util = om.MScriptUtil()

        x_ptr = x_util.asShortPtr()
        y_ptr = y_util.asShortPtr()
        view.worldToView(position, x_ptr, y_ptr)
        x_pos = x_util.getShort(x_ptr)
        y_pos = y_util.getShort(y_ptr)

        if invert_y:
            y_pos = view.portHeight() - y_pos

        return (x_pos, y_pos) 
Example 4
Project: spore   Author: wiremas   File: window_utils.py    License: MIT License 6 votes vote down vote up
def world_to_view(position, invert_y=True):
    """ convert the given 3d position to 2d viewpor coordinates
    :param invert_y bool: convert between qt and maya coordinane space """

    view = active_view()
    x_util = om.MScriptUtil()
    y_util = om.MScriptUtil()

    x_ptr = x_util.asShortPtr()
    y_ptr = y_util.asShortPtr()
    view.worldToView(position, x_ptr, y_ptr)
    x_pos = x_util.getShort(x_ptr)
    y_pos = y_util.getShort(y_ptr)

    if invert_y:
        y_pos = view.portHeight() - y_pos

    return (x_pos, y_pos) 
Example 5
Project: mgear_core   Author: mgear-dev   File: skin.py    License: MIT License 6 votes vote down vote up
def getCurrentWeights(skinCls, dagPath, components):
    """Get the skincluster weights

    Arguments:
        skinCls (PyNode): The skincluster node
        dagPath (MDagPath): The skincluster dagpath
        components (MObject): The skincluster components

    Returns:
        MDoubleArray: The skincluster weights

    """
    weights = OpenMaya.MDoubleArray()
    util = OpenMaya.MScriptUtil()
    util.createFromInt(0)
    pUInt = util.asUintPtr()
    skinCls.__apimfn__().getWeights(dagPath, components, weights, pUInt)
    return weights

######################################
# Skin Collectors
###################################### 
Example 6
Project: maya-skinning-tools   Author: robertjoosten   File: skin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getSkinWeights(dag, skinCluster, component):
    """
    Get the skin weights of the original vertex and of its connected vertices.

    :param OpenMaya.MDagPath dag:
    :param OpenMayaAnim.MFnSkinCluster skinCluster:
    :param OpenMaya.MFn.kMeshVertComponent component:
    :return: skin weights and number of influences
    :rtype: tuple(OpenMaya.MDoubleArray, int)
    """
    # weights variables
    weights = OpenMaya.MDoubleArray()

    # influences variables
    influenceMSU = OpenMaya.MScriptUtil()
    influencePTR = influenceMSU.asUintPtr()

    # get weights
    skinCluster.getWeights(dag, component, weights, influencePTR)

    # get num influences
    num = OpenMaya.MScriptUtil.getUint(influencePTR)

    return weights, num 
Example 7
Project: cross3d   Author: blurstudio   File: mayascenewrapper.py    License: MIT License 6 votes vote down vote up
def _getchildShapeNodes(cls, nativeObject):
		""" A Maya helper that returns a generator of all shape nodes for the provided transform node.
		
		Args:
			nativeObject (OpenMaya.MObject): The object to get the shape nodes of.
		"""
		if nativeObject.apiType() == om.MFn.kTransform:
			path = om.MDagPath.getAPathTo(nativeObject)
			numShapes = om.MScriptUtil()
			numShapes.createFromInt(0)
			numShapesPtr = numShapes.asUintPtr()
			path.numberOfShapesDirectlyBelow(numShapesPtr)
			for index in range(om.MScriptUtil(numShapesPtr).asUint()):
				p = om.MDagPath.getAPathTo(nativeObject)
				p.extendToShapeDirectlyBelow(index)
				yield p.node() 
Example 8
Project: cross3d   Author: blurstudio   File: mayascenewrapper.py    License: MIT License 6 votes vote down vote up
def _getShapeNode(cls, nativeObject):
		""" A Maya Helper that returns the first shape node of the provided transform node.
		
		If no shape node exists the nativeObject is returned.
		
		Args:
			nativeObject (OpenMaya.MObject): The MObject to get the first shape node from.
		
		Returns:
			OpenMaya.MObject: The first shape node of the transform or the passed in object.
		"""
		if nativeObject.apiType() == om.MFn.kTransform:
			path = om.MDagPath.getAPathTo(nativeObject)
			numShapes = om.MScriptUtil()
			numShapes.createFromInt(0)
			numShapesPtr = numShapes.asUintPtr()
			path.numberOfShapesDirectlyBelow(numShapesPtr)
			if om.MScriptUtil(numShapesPtr).asUint():
				# TODO: Should this return the last shape, instead of the first?
				path.extendToShapeDirectlyBelow(0)
				return path.node()
		return nativeObject 
Example 9
Project: dpAutoRigSystem   Author: nilouco   File: sqSpaceSwitcher.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_tm_offset(self, _nParent, _nDriven=None, _type="t"):
        """
        Get the offset between the driven and a driver node
        """
        if _nDriven is None:
            _nDriven = self.nSwConstRecept

        mStart = om.MMatrix()
        mEnd = om.MMatrix()

        wmStart = _nParent.worldMatrix.get().__melobject__()
        wmEnd = _nDriven.worldMatrix.get().__melobject__()

        om.MScriptUtil().createMatrixFromList(wmStart, mStart)
        om.MScriptUtil().createMatrixFromList(wmEnd, mEnd)

        mOut = om.MTransformationMatrix(mEnd * mStart.inverse())

        if _type == "t":
            # Extract Translation
            vTran = om.MVector(mOut.getTranslation(om.MSpace.kTransform))
            vTranPymel = [vTran.x, vTran.y, vTran.z]
            return vTranPymel
        if _type == "r":
            # Extract Rotation
            ro = _nDriven.rotateOrder.get()
            vRot = om.MEulerRotation(mOut.eulerRotation().reorder(ro))
            vRotDeg = [math.degrees(vRot.x), math.degrees(vRot.y), math.degrees(vRot.z)]
            return vRotDeg 
Example 10
Project: dpAutoRigSystem   Author: nilouco   File: dpUtils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def extract_world_scale_from_matrix(obj):
    world_matrix = cmds.getAttr(obj + ".worldMatrix")
    mMat = om.MMatrix()
    om.MScriptUtil.createMatrixFromList(world_matrix, mMat)
    mTransform = om.MTransformationMatrix(mMat)
    scale_util = om.MScriptUtil()
    scale_util.createFromDouble(0.0, 0.0, 0.0)
    ptr = scale_util.asDoublePtr()
    mTransform.getScale(ptr, om.MSpace.kWorld)

    x_scale = om.MScriptUtil.getDoubleArrayItem(ptr, 0)
    y_scale = om.MScriptUtil.getDoubleArrayItem(ptr, 1)
    z_scale = om.MScriptUtil.getDoubleArrayItem(ptr, 2)

    return [x_scale, y_scale, z_scale] 
Example 11
Project: spore   Author: wiremas   File: spore_context.py    License: MIT License 5 votes vote down vote up
def randomize_rotation(self, rotation, random_weight):
        """ randomize the given rotation values by 10 degrees multiply
        by the random_weight """

        factor = 5 * random_weight
        rand_x = np.radians(random.uniform(-factor, factor))
        rand_y = np.radians(random.uniform(-factor, factor))
        rand_z = np.radians(random.uniform(-factor, factor))

        util = om.MScriptUtil()
        util.createFromDouble(rand_x, rand_y, rand_z)
        rand_rot_ptr = util.asDoublePtr()

        rand_mat = om.MTransformationMatrix()
        rand_mat.setRotation(rand_rot_ptr, om.MTransformationMatrix.kXYZ)

        util.createFromDouble(np.radians(rotation.x),
                              np.radians(rotation.y),
                              np.radians(rotation.z))
        rot_ptr = util.asDoublePtr()

        rot_mat = om.MTransformationMatrix()
        rot_mat.setRotation(rot_ptr, om.MTransformationMatrix.kXYZ)

        result_mat = rot_mat.asMatrix() * rand_mat.asMatrix()
        rotation = om.MTransformationMatrix(result_mat).rotation()
        return om.MVector(math.degrees(rotation.asEulerRotation().x),
                        math.degrees(rotation.asEulerRotation().y),
                        math.degrees(rotation.asEulerRotation().z)) 
Example 12
Project: spore   Author: wiremas   File: spore_context.py    License: MIT License 5 votes vote down vote up
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)) 
Example 13
Project: spore   Author: wiremas   File: geo_cache.py    License: MIT License 5 votes vote down vote up
def create_uv_lookup(self):
        """ create a dict with an entry for every vertex and a list of
        neighbouring faces as well as a kd tree tro look up close face ids """

        self.logger.debug('Create UV lookup for the current GeoCache')

        util = om.MScriptUtil()
        connected_faces = om.MIntArray()

        mesh_fn = om.MFnMesh(self.mesh)
        num_verts = mesh_fn.numVertices()
        points = np.zeros(shape=(num_verts, 2))

        vert_iter = om.MItMeshVertex(self.mesh)
        while not vert_iter.isDone():

            index = vert_iter.index()
            vert_iter.getConnectedFaces(connected_faces)
            self.neighbor_lookup[index] = [connected_faces[i] for i in xrange(connected_faces.length())]

            util.createFromDouble(0.0, 0.0)
            uv_ptr = util.asFloat2Ptr()
            vert_iter.getUV(uv_ptr)
            u_coord = util.getFloat2ArrayItem(uv_ptr, 0, 0)
            v_coord = util.getFloat2ArrayItem(uv_ptr, 0, 1)
            points[index] = (u_coord, v_coord)

            vert_iter.next()

        self.uv_kd_tree = kd_tree(points) 
Example 14
Project: spore   Author: wiremas   File: mesh_utils.py    License: MIT License 5 votes vote down vote up
def get_uv_at_point(target, point, uv_set=None, poly_id=None):
    """ get closest UV coords of the target at the given point
    :param target str: name of the target object
    :param point MPoint: """

    util = om.MScriptUtil()
    uv_coords_ptr = util.asFloat2Ptr()

    mesh_fn = get_mesh_fn(target)
    mesh_fn.getUVAtPoint(point, uv_coords_ptr, om.MSpace.kObject, uv_set, poly_id)

    u_coord = util.getFloat2ArrayItem(uv_coords_ptr, 0, 0)
    v_coord = util.getFloat2ArrayItem(uv_coords_ptr, 0, 1)

    return u_coord, v_coord 
Example 15
Project: spore   Author: wiremas   File: brush_utils.py    License: MIT License 5 votes vote down vote up
def get_rotation(initial_rotation, dir_vector, vector_weight):
    """ Get euler rotation values based on given min/max rotation, a direction
    vector and a weight for the given vector. slerp between direction vector and
    world up vector.
    :param min_rotation tuple(x,y,z): minimum rotation values
    :param max_rotation tuple(x,y,z): maximum rotation values
    :param dir_vector MVector: direction of instance y-up
    :param weight float(0-1): the weigth of the direction
    :return MVector: Mvector containing euler rotation values """

    world_up = om.MVector(0, 1, 0)
    rotation = om.MQuaternion(world_up, dir_vector, vector_weight)

    # get random rotation
    #  r_x = math.radians(random.uniform(min_rotation[0], max_rotation[0]))
    #  r_y = math.radians(random.uniform(min_rotation[1], max_rotation[1]))
    #  r_z = math.radians(random.uniform(min_rotation[2], max_rotation[2]))

    mat = om.MTransformationMatrix()

    util = om.MScriptUtil()
    util.createFromDouble(initial_rotation[0], initial_rotation[1], initial_rotation[2])
    rotation_ptr = util.asDoublePtr()
    mat.setRotation(rotation_ptr, om.MTransformationMatrix.kXYZ)

    mat = mat.asMatrix() * 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)) 
Example 16
Project: maya-retarget-blendshape   Author: robertjoosten   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getAverageLength(dag, component, space):
    """
    Get average length of connected edges.
    
    :param OpenMaya.MDagPath dag: 
    :param OpenMaya.MFnSingleIndexedComponent component: 
    :param OpenMaya.MSpace space:
    :return: Average length of the connected edges
    :rtype: float
    """
    total = 0
    
    lengthUtil = OpenMaya.MScriptUtil()
    lengthPtr = lengthUtil.asDoublePtr()

    # get connected edges
    connected = OpenMaya.MIntArray()

    iterate = OpenMaya.MItMeshVertex(dag, component)
    iterate.getConnectedEdges(connected)
    
    # ignore if no edges are connected
    if not connected.length():
        return 0
    
    # get average
    component = asComponent(connected, OpenMaya.MFn.kMeshEdgeComponent)
    iterate = OpenMaya.MItMeshEdge(dag, component)
    while not iterate.isDone():
        iterate.getLength(lengthPtr, space)
        total += lengthUtil.getDouble(lengthPtr)
        
        iterate.next()
        
    return total/connected.length()


# ---------------------------------------------------------------------------- 
Example 17
Project: mgear_core   Author: mgear-dev   File: curve.py    License: MIT License 5 votes vote down vote up
def getCurveParamAtPosition(crv, position):
    """Get curve parameter from a position

    Arguments:
        position (list of float): Represents the position in worldSpace
            exp: [1.4, 3.55, 42.6]
        crv (curve): The  source curve to get the parameter.

    Returns:
        list: paramenter and curve length
    """
    point = om.MPoint(position[0], position[1], position[2])

    dag = om.MDagPath()
    obj = om.MObject()
    oList = om.MSelectionList()
    oList.add(crv.name())
    oList.getDagPath(0, dag, obj)

    curveFn = om.MFnNurbsCurve(dag)
    length = curveFn.length()
    crv.findParamFromLength(length)

    paramUtill = om.MScriptUtil()
    paramPtr = paramUtill.asDoublePtr()

    point = curveFn.closestPoint(point, paramPtr, 0.001, om.MSpace.kObject)
    curveFn.getParamAtPoint(point, paramPtr, 0.001, om.MSpace.kObject)

    param = paramUtill.getDouble(paramPtr)

    return param, length 
Example 18
Project: mgear_core   Author: mgear-dev   File: meshNavigation.py    License: MIT License 5 votes vote down vote up
def getClosestPolygonFromTransform(geo, loc):
    """Get closest polygon from transform

    Arguments:
        geo (dagNode): Mesh object
        loc (matrix): location transform

    Returns:
        Closest Polygon

    """
    if isinstance(loc, pm.nodetypes.Transform):
        pos = loc.getTranslation(space='world')
    else:
        pos = datatypes.Vector(loc[0], loc[1], loc[2])

    nodeDagPath = OpenMaya.MObject()
    try:
        selectionList = OpenMaya.MSelectionList()
        selectionList.add(geo.name())
        nodeDagPath = OpenMaya.MDagPath()
        selectionList.getDagPath(0, nodeDagPath)
    except Exception as e:
        raise RuntimeError("OpenMaya.MDagPath() failed "
                           "on {}. \n {}".format(geo.name(), e))

    mfnMesh = OpenMaya.MFnMesh(nodeDagPath)

    pointA = OpenMaya.MPoint(pos.x, pos.y, pos.z)
    pointB = OpenMaya.MPoint()
    space = OpenMaya.MSpace.kWorld

    util = OpenMaya.MScriptUtil()
    util.createFromInt(0)
    idPointer = util.asIntPtr()

    mfnMesh.getClosestPoint(pointA, pointB, space, idPointer)
    idx = OpenMaya.MScriptUtil(idPointer).asInt()

    return geo.f[idx], pos 
Example 19
Project: instanceAlongCurve   Author: mmerchante   File: instanceAlongCurve.py    License: MIT License 5 votes vote down vote up
def getRampValueAtNormalizedPosition(self, rampValues, v):

        util = OpenMaya.MScriptUtil()
        util.createFromDouble(0.0)
        valuePtr = util.asFloatPtr()
        
        position = math.fmod((v * rampValues.rampRepeat) + rampValues.rampOffset, 1.0)
        rampValues.ramp.getValueAtPosition(position, valuePtr)

        return util.getFloat(valuePtr) 
Example 20
Project: instanceAlongCurve   Author: mmerchante   File: instanceAlongCurve.py    License: MIT License 5 votes vote down vote up
def hasShapeBelow(self, dagPath):

        sutil = OpenMaya.MScriptUtil()
        uintptr = sutil.asUintPtr()
        sutil.setUint(uintptr , 0)

        dagPath.numberOfShapesDirectlyBelow(uintptr)

        return sutil.getUint(uintptr) > 0 
Example 21
Project: cmt   Author: chadmv   File: shortcuts.py    License: MIT License 5 votes vote down vote up
def get_int_ptr():
    util = OpenMaya.MScriptUtil()
    util.createFromInt(0)
    return util.asIntPtr() 
Example 22
Project: cmt   Author: chadmv   File: shortcuts.py    License: MIT License 5 votes vote down vote up
def ptr_to_int(int_ptr):
    return OpenMaya.MScriptUtil.getInt(int_ptr) 
Example 23
Project: cmt   Author: chadmv   File: skinio.py    License: MIT License 5 votes vote down vote up
def __get_current_weights(self, dag_path, components):
        """Get the current skin weight array.

        :param dag_path: MDagPath of the deformed geometry.
        :param components: Component MObject of the deformed components.
        :return: An MDoubleArray of the weights.
        """
        weights = OpenMaya.MDoubleArray()
        util = OpenMaya.MScriptUtil()
        util.createFromInt(0)
        ptr = util.asUintPtr()
        self.fn.getWeights(dag_path, components, weights, ptr)
        return weights 
Example 24
Project: ml_tools   Author: morganloomis   File: ml_centerOfMass.py    License: MIT License 5 votes vote down vote up
def getFacesArea(faces):
    '''
    Get the area of a list of mesh faces.
    '''

    total=0
    for f in faces:
        om.MGlobal.clearSelectionList()
        om.MGlobal.selectByName(f)
        sList = om.MSelectionList()
        om.MGlobal.getActiveSelectionList(sList)

        sIter = om.MItSelectionList(sList, om.MFn.kMeshPolygonComponent) #change1

        dagPath = om.MDagPath()
        component = om.MObject()

        sIter.getDagPath(dagPath, component) #change2
        polyIter = om.MItMeshPolygon(dagPath, component)

        util = om.MScriptUtil()
        util.createFromDouble(0.0)
        ptr = util.asDoublePtr()
        polyIter.getArea(ptr, om.MSpace.kWorld)
        area = om.MScriptUtil(ptr).asDouble()
        total+=area

    return total 
Example 25
Project: maya-spline-ik   Author: robertjoosten   File: curve.py    License: GNU General Public License v3.0 4 votes vote down vote up
def nearestPointOnCurve(curve, pos):
    """
    Find the nearest point on a curve, the function will return
    the parameter and point. The point is of type OpenMaya.MPoint.
    
    :param str curve:
    :param list pos:
    :return: parameter, point
    :rtype: float, OpenMaya.MPoint
    """
    mFnCurve = api.asMFnNurbsCurve(curve)

    pUtil = OpenMaya.MScriptUtil()
    pPtr = pUtil.asDoublePtr()

    point = mFnCurve.closestPoint(
        OpenMaya.MPoint(*pos),
        pPtr,
        0.001,
        OpenMaya.MSpace.kWorld
    )

    return pUtil.getDouble(pPtr), point


# ---------------------------------------------------------------------------- 
Example 26
Project: spore   Author: wiremas   File: spore_context.py    License: MIT License 4 votes vote down vote up
def get_rotation(self, flag, normal, index=0):
        """ generate new rotation values based on the brush state
        if we are in drag mode we maintain old rotation values and adjust
        rotation to the new normal. we can use the index arg to set a
        specific index for the last placed objects """

        dir_vector = self.get_alignment(normal)
        vector_weight = self.brush_state.settings['strength']
        world_up = om.MVector(0, 1, 0)
        rotation = om.MQuaternion(world_up, dir_vector, vector_weight)

        # when we in drag mode we want to maintain old rotation values
        if self.brush_state.shift_mod and flag != SporeToolCmd.k_click:
            initial_rotation = self.initial_rotation[index]

        # otherwise we generate new values
        else:
            # get random rotation
            min_rotation = self.brush_state.settings['min_rot']
            max_rotation = self.brush_state.settings['max_rot']
            r_x = math.radians(random.uniform(min_rotation[0], max_rotation[0]))
            r_y = math.radians(random.uniform(min_rotation[1], max_rotation[1]))
            r_z = math.radians(random.uniform(min_rotation[2], max_rotation[2]))
            self.initial_rotation.set(om.MVector(r_x, r_y, r_z), index)
            initial_rotation = self.initial_rotation[index]
            #  rotation = brush_utils.get_rotation(self.initial_rotation, direction,

        mat = om.MTransformationMatrix()

        util = om.MScriptUtil()
        util.createFromDouble(initial_rotation.x,
                              initial_rotation.y,
                              initial_rotation.z)
        rotation_ptr = util.asDoublePtr()
        mat.setRotation(rotation_ptr, om.MTransformationMatrix.kXYZ)

        mat = mat.asMatrix() * 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)) 
Example 27
Project: mViewportDrawOpenGL   Author: volodinroman   File: ViewportPainter.py    License: MIT License 4 votes vote down vote up
def getMouseIntersect(self):

        sourcePnt = OpenMaya.MPoint(0,0,0)
        rayDir = OpenMaya.MVector(0,0,0)
        maximumDistance = 9999999999
        viewHeight = self.view3D.portHeight()
        
        hitNormal = OpenMaya.MVector()
        
        intersectedObject = None
        intersectedPoint = OpenMaya.MFloatPoint()
        intersectedFace = 0

        hitFace = OpenMaya.MScriptUtil()
        hitFace.createFromInt(0)
        hitFacePtr = hitFace.asIntPtr()

        hitDistance = OpenMaya.MScriptUtil(0.0)
        hitDistancePtr = hitDistance.asFloatPtr()

        self.view3D.viewToWorld(int(self.userMouseEvents.M_posX), int(viewHeight - self.userMouseEvents.M_posY), sourcePnt, rayDir)

        
        direction = OpenMaya.MFloatVector(rayDir.x, rayDir.y, rayDir.z).normal()

        iter = OpenMaya.MItDependencyNodes(OpenMaya.MFn.kMesh)

        while not iter.isDone():

            node =iter.thisNode()
            dagPath = OpenMaya.MDagPath.getAPathTo(node)

            hitPoint = OpenMaya.MFloatPoint()
            source = OpenMaya.MFloatPoint(sourcePnt.x, sourcePnt.y, sourcePnt.z)
            direction = OpenMaya.MFloatVector(direction.x,direction.y,direction.z)

            if dagPath.isVisible():
                mesh = OpenMaya.MFnMesh(dagPath)
                intersected = mesh.closestIntersection(source, direction, None, None, False, OpenMaya.MSpace.kWorld, 9999999999, True, None, hitPoint, hitDistancePtr, hitFacePtr, None, None, None, 0.0001)
                
                if intersected:
                    intersectionDistance = hitDistance.getFloat(hitDistancePtr)
                    if intersectionDistance < maximumDistance:
                        maximumDistance = intersectionDistance
                        intersectedPoint = hitPoint
                        intersectedFace =  OpenMaya.MScriptUtil(hitFacePtr).asInt()
                        mesh.getClosestNormal(OpenMaya.MPoint(intersectedPoint),hitNormal,OpenMaya.MSpace.kWorld)
                        intersectedObject = dagPath.fullPathName()

            iter.next()

        if intersectedPoint.x + intersectedPoint.y + intersectedPoint.z == 0:
            return None, None, None
        else:
            return intersectedPoint, intersectedFace, intersectedObject 
Example 28
Project: anima   Author: eoyilmaz   File: closestPointOnCurve.py    License: MIT License 4 votes vote down vote up
def compute(self, plug, dataBlock):
        if plug == closestPointOnCurve.aOutPosition or plug == closestPointOnCurve.aOutParam:
            dataHandle = dataBlock.inputValue(closestPointOnCurve.aInCurve)
            inputAsCurve = dataHandle.asNurbsCurve()
            
            #if not inputAsCurve.hasFn(OpenMaya.MFn.kNurbsCurve):
            #    return OpenMaya.kUnknownParameter
            
            dataHandle = dataBlock.inputValue(closestPointOnCurve.aInPosition)
            
            inPositionAsFloat3 = dataHandle.asFloat3()
            inPosition = OpenMaya.MPoint(
                inPositionAsFloat3[0],
                inPositionAsFloat3[1],
                inPositionAsFloat3[2]
            )
            
            # connect the MFnNurbsCurve
            # and ask the closest point
            
            nurbsCurveFn = OpenMaya.MFnNurbsCurve(inputAsCurve)
            
            # get and set outPosition
            outParam = OpenMaya.MScriptUtil()
            outParam.createFromDouble(0)
            outParamPtr = outParam.asDoublePtr() 
            
            # get position and paramater
            outPosition = nurbsCurveFn.closestPoint(
                inPosition, True, outParamPtr, 0.001, OpenMaya.MSpace.kWorld
            )
            
            outputHandle = dataBlock.outputValue(
                closestPointOnCurve.aOutPosition
            )
            outputHandle.set3Float(outPosition.x, outPosition.y, outPosition.z)
            
            # get and set outNormal
            #outNormal = nurbsCurveFn.normal(parameter, OpenMaya.MSpace.kWorld)
            #outputHandle = dataBlock.outputValue(closestPointOnCurve.aOutNormal)
            #outputHandle.set3Float(outNormal.x, outNormal.y, outNormal.z)
            #outputHandle.set3Float(0, 1, 0 )
            
            # get and set the uvs
            outputHandle = dataBlock.outputValue(closestPointOnCurve.aOutParam)
            #outputHandle.setFloat(OpenMaya.MScriptUtil(outParamPtr).asDouble())
            outputHandle.setFloat(OpenMaya.MScriptUtil.getDouble(outParamPtr))
            
            dataBlock.setClean(plug)
        else:
            return OpenMaya.kUnknownParameter

# creator 
Example 29
Project: anima   Author: eoyilmaz   File: randomizeUVDeformer.py    License: MIT License 4 votes vote down vote up
def deform(self, data_block, geometry_iterator, local_to_world_matrix, geometry_index):
        """do deformation
        """
        envelope_attribute = OpenMayaMPx.cvar.MPxDeformerNode_envelope
        envelope_value = data_block.inputValue(envelope_attribute).asFloat()

        input_geometry_object = \
            self.get_deformer_input_geometry(data_block, geometry_index)

        # Obtain the list of normals for each vertex in the mesh.
        mesh_fn = OpenMaya.MFnMesh(input_geometry_object)

        uv_shell_array = OpenMaya.MIntArray()
        u_array = OpenMaya.MFloatArray()
        v_array = OpenMaya.MFloatArray()
        script_util = OpenMaya.MScriptUtil(0)
        shells_ptr = script_util.asUintPtr()

        mesh_fn.getUvShellsIds(uv_shell_array, shells_ptr)
        mesh_fn.getUVs(u_array, v_array)

        max_offset_attr_handle = \
            data_block.inputValue(RandomizeDeformer.aMaxOffset)
        max_offset = max_offset_attr_handle.asInt()

        # compute and write the new uvs
        for uv_id in xrange(len(u_array)):
            shell_id = uv_shell_array[uv_id]
            offset_u = shell_id % max_offset
            u_array[uv_id] += offset_u

        mesh_fn.setUVs(u_array, v_array)

        uv_shell_array.clear()
        u_array.clear()
        v_array.clear()

        # # Iterate over the vertices to move them.
        # while not geometry_iterator.isDone():
        #     # Obtain the vertex normal of the geometry.
        #     # This normal is the vertex's averaged normal value if that
        #     # vertex is shared among several polygons.
        #     vertex_index = geometry_iterator.index()
        #     normal = OpenMaya.MVector(normals[vertex_index])
        #  Cast the MFloatVector into a simple vector.
        #
        #     # Increment the point along the vertex normal.
        #     point = geometry_iterator.position()
        #     newPoint = \
        #         point + (normal * vertexIncrement * meshInflation * envelopeValue)
        #
        #     # Clamp the new point within the bounding box.
        #     self.clampPointInBoundingBox(newPoint, boundingBox)
        #
        #     # Set the position of the current vertex to the new point.
        #     geometry_iterator.setPosition(newPoint)
        #
        #     # Jump to the next vertex.
        #     geometry_iterator.next()