Skip to content

Instantly share code, notes, and snippets.

@thegedge
Last active December 12, 2015 12:09
Show Gist options
  • Save thegedge/4769985 to your computer and use it in GitHub Desktop.
Save thegedge/4769985 to your computer and use it in GitHub Desktop.
Ray/sphere intersection in Python
#!/usr/bin/env python
import timeit
def dot(a, b):
"""Dot product"""
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
def rs_intersect(R0, d, C, r):
"""Ray/sphere intersection"""
R0 = (R0[0] - C[0], R0[1] - C[1], R0[2] - C[2])
dDotR0 = dot(d, R0)
t = -dDotR0 - (dDotR0*dDotR0 - dot(R0, R0) + r*r)**0.5
return (R0[0] + t*d[0], R0[1] + t*d[1], R0[2] + t*d[2])
R0 = (0, 0, -10)
d = (0.01/1.002, 0.01/1.002, 1/1.002)
C = (0, 0, 0)
r = 1
def test():
global R0, d, C, r
rs_intersect(R0, d, C, r)
print timeit.timeit('test()', setup='from __main__ import test; gc.enable()', number=1000000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment