Created
August 29, 2015 11:31
-
-
Save SEVEZ/1462354b852356629d65 to your computer and use it in GitHub Desktop.
Get object screen position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use M3dView. | |
def screenPositionAPI(panel, pos): | |
mp = OpenMaya.MPoint(pos[0], pos[1], pos[2]) | |
m3v = OpenMayaUI.M3dView.active3dView() | |
OpenMayaUI.M3dView.getM3dViewFromModelPanel(panel, m3v) | |
xp = OpenMaya.MScriptUtil().asShortPtr() | |
yp = OpenMaya.MScriptUtil().asShortPtr() | |
ret = m3v.worldToView(mp, xp, yp) | |
x = OpenMaya.MScriptUtil().getShort(xp) | |
y = OpenMaya.MScriptUtil().getShort(yp) | |
xPtr = OpenMaya.MScriptUtil().asUintPtr() | |
yPtr = OpenMaya.MScriptUtil().asUintPtr() | |
widthPtr = OpenMaya.MScriptUtil().asUintPtr() | |
heightPtr = OpenMaya.MScriptUtil().asUintPtr() | |
m3v.viewport(xPtr, yPtr, widthPtr, heightPtr) | |
viewWidth = OpenMaya.MScriptUtil().getUint( widthPtr ) | |
viewHeight = OpenMaya.MScriptUtil().getUint( heightPtr ) | |
return (float(x)/float(viewWidth), float(y)/float(viewHeight)) | |
# Or calculate by yourself(using inverse Matrix) | |
def screenPositionAPI2(cam, pos): | |
mp = OpenMaya.MPoint(pos[0], pos[1], pos[2]) | |
camDagPath = mDagPathFromName(cam) | |
mtx = camDagPath.inclusiveMatrixInverse() | |
newPos = mp * mtx | |
resX = - newPos.x / newPos.z * cmds.camera(cam, q=True, fl=True) | |
resY = - newPos.y / newPos.z * cmds.camera(cam, q=True, fl=True) | |
resX /= cmds.camera(cam, q=True, hfa=True)/ 25.4 | |
resY /= cmds.camera(cam, q=True, vfa=True)/ 25.4 | |
# This one is better | |
import math | |
def screenPositionAPI3(cam, pos): | |
mp = OpenMaya.MPoint(pos[0], pos[1], pos[2]) | |
camDagPath = mDagPathFromName(cam) | |
mtx = camDagPath.inclusiveMatrixInverse() | |
newPos = mp * mtx | |
hfv = cmds.camera(cam, q=True, hfv=True) | |
resX = ((newPos.x/(-newPos.z))/math.tan(math.radians(hfv/2)))/2.0; | |
vfv = cmds.camera(cam, q=True, vfv=True) | |
resY = ((newPos.y/(-newPos.z))/math.tan(math.radians(vfv/2)))/2.0; | |
return (resX, resY) | |
return (resX, resY) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment