title: Optimization of ray triangle intersection algorithm in numpy
body: <p>I am writing application that loads an STL file via the numpy-stl library and renders an image of it. </p>
  
  <p>For rendering the final image I need to find the intersection point of a ray and a triangle in the mesh</p>
  
  <p>I already implemented <a href="https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm" rel="nofollow noreferrer">Möller–Trumbore intersection algorithm</a> in numpy but performance is really bad with bigger models.</p>
  
  <pre><code>import numpy as np
  
  #Loading the model via file
  self.temp_mesh = Mesh.from_file("test.stl")
  
  def intersectionRayModel(self, rayStart, rayEnd):
      w = rayEnd - rayStart
      w /= np.linalg.norm(w)
  
      data = self.temp_mesh
  
      counter = 0
      for tri in data.vectors+self.pos:
          b = [.0, .0, .0]
  
          e1 = tri[1]
          e1 -= tri[0]
          e2 = tri[2]
          e2 -= tri[0]
  
          n = self.temp_mesh.normals[counter]
  
          q = np.cross(w, e2)
          a = np.dot(e1, q)
  
          counter += 1
          if (np.dot(n, w) &gt;= .0) or (abs(a) &lt;= .0001):
              continue
  
          s = np.array(rayStart)
          s -= tri[0]
          s /= a
  
          r = np.cross(s, e1)
          b[0] = np.dot(s, q)
          b[1] = np.dot(r, w)
          b[2] = 1.0 - b[0] - b[1]
  
          if (b[0] &lt; .0) or (b[1] &lt; .0) or (b[2] &lt; .0):
              continue
  
          t = np.dot(e2, r)
          if t &gt;= .0:
              point = rayStart + t*w
              return True, point
          else:
              continue
  
      return False, None
  </code></pre>
  
  <p>I think a for loop is really bad here, but I was unable to find a way to get rid of it.</p>