2

I'd like to convert a worldspace position (x,y,z) to screenspace coordinates (x,y) from the selected camera point of view. I'm a bit limited by the fact I can't load extra modules (e.g. numpy). Is there an affordable way to do this?

2
  • Why can't you load other modules? Apr 22, 2018 at 16:58
  • Not allowed to manage my computer and add extra modules... May 12, 2019 at 9:00

1 Answer 1

2

I finally found how to do this on the internet. Just call this procedure with a camera name and the worldspace coordinate of a point as attributes.

def worldSpaceToScreenSpace(camera, worldPoint):

    # get current resolution
    resWidth = mc.getAttr('defaultResolution.width')
    resHeight = mc.getAttr('defaultResolution.height')

    # get the dagPath to the camera shape node to get the world inverse matrix
    selList = om.MSelectionList()
    selList.add(camera)
    dagPath = om.MDagPath()
    selList.getDagPath(0,dagPath)
    dagPath.extendToShape()
    camInvMtx = dagPath.inclusiveMatrix().inverse()

    # use a camera function set to get projection matrix, convert the MFloatMatrix 
    # into a MMatrix for multiplication compatibility
    fnCam = om.MFnCamera(dagPath)
    mFloatMtx = fnCam.projectionMatrix()
    projMtx = om.MMatrix(mFloatMtx.matrix)

    # multiply all together and do the normalisation
    mPoint = om.MPoint(worldPoint[0],worldPoint[1],worldPoint[2]) * camInvMtx * projMtx;
    x = (mPoint[0] / mPoint[3] / 2 + .5) * resWidth
    y = (mPoint[1] / mPoint[3] / 2 + .5) * resHeight

    return [x,y]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.