Skip to content

Instantly share code, notes, and snippets.

@ivogrig
Last active June 18, 2016 01:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivogrig/44d3bdd978fa23b61bb8 to your computer and use it in GitHub Desktop.
Save ivogrig/44d3bdd978fa23b61bb8 to your computer and use it in GitHub Desktop.
Test is a given point is visible in the camera and Convert between 3d and screen coordinates
# Test is a given point is visible in the camera
# Convert between 3d and screen coordinates
import modo
# Assuming the camera is also the active view
def pointInCamera(cam, position):
aperture_x = cam.channel(lx.symbol.sICHAN_CAMERA_APERTUREX).get()
aperture_y = cam.channel(lx.symbol.sICHAN_CAMERA_APERTUREY).get()
sv = lx.service.View3Dport()
view = lx.object.View3D( sv.View(sv.Current()) )
zeroa, zerob, width, height = view.Bounds()
print 'View dimensions in pixels: ', width, height
# Multiply position with camera matrix
mat1 = modo.Matrix4(position=position)
mat2 = modo.Matrix4(modo.Camera('Camera').channel('worldMatrix').get())
mat3 = mat1 * mat2.inverted()
posInCamSpace = modo.Vector3(mat3.position).normal()
# Bail out if point is behind of the camera
if not posInCamSpace < 0.0:
return False
# Convert to screen coordinates (optionally)
x = ( posInCamSpace.x / (-posInCamSpace.z) ) / 10.0 / aperture_x
y = ( posInCamSpace.y / (-posInCamSpace.z) ) / 10.0 / aperture_y
print x,y
xpos = (( x + 1.0) / 2.0) * float(width)
ypos = (( y + 1.0) / 2.0) * float(height)
print 'x coordinate: ', xpos
print 'y coordinate: ', ypos
# Point is visible if x and y values are in range -1.0 to +1.0
return abs(x) <= 1.0 and abs(y) <= 1.0
scene = modo.Scene()
# Create a locator if it does not exist
try:
scene.ItemLookup('Locator')
except LookupError:
locator = scene.addItem(lx.symbol.sITYPE_LOCATOR)
cam = modo.Camera('Camera')
pos = locator.position.get()
# Move the locator around and run the script in the script editor to test
print pointInCamera(cam, pos )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment