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?
1 Answer
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]