title: Ray Tracing with JS
body: <p>I'm making a small ray tracing example with JavaScript, but I have a problem. When I'm trying to calculate the reflected color it always returns [255,255,255] and I don't know why. If object is specular I trace a ray and it returns 255,255,255. (Line 114 - 124 js)</p>
  <p>In addition the spheres makes the shadows of the light ok, but no the shadows of for example (sphere 1 to sphere 2). I think the problem is in the function isLightVisible(line 89-98 js)</p>
  <p>Finally I think that they don't respect which is in front of which one.</p>
  <p>HTML CODE:</p>
  <pre><code>&lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Ray Tracing Example&lt;/title&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
          &lt;h1&gt;Ray Tracing&lt;/h1&gt;
  
              &lt;table&gt;
                  &lt;th&gt;
                      &lt;canvas id=&quot;glcanvas&quot; style=&quot;border: solid;&quot; width=&quot;400&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;
                      &lt;button onclick=&quot;start()&quot;&gt; Start &lt;/button&gt;
                  &lt;/th&gt;
              &lt;/table&gt;
  
          &lt;p style=&quot;text-indent:85px;&quot;&gt;Camera Position: [0, 0, 0]&lt;/p&gt;
  
          &lt;script type=&quot;text/javascript&quot; src=&quot;raytracingV2.js&quot;&gt;&lt;/script&gt;
          &lt;script src=&quot;gl-matrix/common.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/vec3.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/vec2.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/vec4.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/vec4.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/mat4.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/mat3.js&quot;&gt;&lt;/script&gt;
          &lt;script type=&quot;text/javascript&quot; src=&quot;gl-matrix/quat.js&quot;&gt;&lt;/script&gt;
  
          &lt;script type=&quot;text/javascript&quot;&gt;
  
              function start () {
                  // Inicialitzem el RayTracing
                  inicialitzar(Scene);
              }
  
              var Screen = {
                  width   : 0,
                  height  : 0,
                  canvas  : null,
                  context : null,
                  buffer  : null,
              };
  
              var Scene = {
  
                  Fons: [0, 0, 0],
  
                  Shapes: [
                      {
  
                          id      : &quot;esfera_blava&quot;,
                          tipus   : &quot;esfera&quot;,
                          radi    : 0.25,
                          centre  : [-0.3,0,1],
                          point   : [-0.3,0,1],
                      
                          color: [155, 200, 155],
                          specular: 0.2,
                          lambert: 0.7,
                          ambient: 0.1,
                          // Material:
                          // Rd, Rs, Ra (colors)
                          // alpha specular (float)
                          //  Reflexion and/or Transmision (float)
  
                      },
                      {
  
                          id      : &quot;esfera_vermella&quot;,
                          tipus   : &quot;esfera&quot;,
                          radi    : 0.25,
                          centre  : [0.3,0,1.4],
                          point   : [0.3,0,1.4],
  
                          color: [200, 155, 155],
                          specular: 0.2,
                          lambert: 0.7,
                          ambient: 0.1,
                          // Material:
                          // Rd, Rs, Ra (colors)
                          // alpha specular (float)
                          //  Reflexion and/or Transmision (float)
  
                          },
                  ],
                  Camera: {
                      position: [0,0,0],  // posicio camera
                      up      : [0,1,0],      // vector amunt
                      centre  : [0,0,-1],     // centre escena
                      fov     : 60,           // field of view
                      X       : vec3.create(),
                      Z       : vec3.create(),
                      Y       : vec3.create(),
                  },
                  Lights: [
                      {
                          position: vec3.create(), // S'emplena segons els valors entrats
                          color   : vec3.create(), // S'emplena segons els valors entrats
                      },
                      {
                          position: vec3.create(), // S'emplena segons els valors entrats
                          color   : vec3.create(), // S'emplena segons els valors entrats
                      },
                                          {
                          position: vec3.create(), // S'emplena segons els valors entrats
                          color   : vec3.create(), // S'emplena segons els valors entrats
                      },
                  ]
              };
          &lt;/script&gt;
  
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  <p>RAY TRACING JS CODE</p>
  <pre><code>
  // RAY TRACING - example //
  
  // Inicialitzem el RayTracing
  function inicialitzar(Scene) {
  
      // Parametres de les llums
      // Put it interactively
      Scene.Lights[0].position = [-1, 2, 4];
      Scene.Lights[0].color = [0.4, 0.4, 0.4];
      Scene.Lights[1].position = [1, 4, 4];
      Scene.Lights[1].color = [1, 0, 0];
      Scene.Lights[1].position = [-1, -4, -4];
      Scene.Lights[1].color = [1, 0, 0];
  
      Screen.canvas = document.getElementById(&quot;glcanvas&quot;);
      if (Screen.canvas == null)  {
          alert(&quot;Invalid element: &quot; + id);
          return;
      }
      Screen.context = Screen.canvas.getContext(&quot;2d&quot;);
      if(Screen.context == null){
          alert(&quot;Could not get context&quot;);
          return;
      }
      Screen.width = Screen.canvas.width;
      Screen.height = Screen.canvas.height;
      Screen.buffer = Screen.context.createImageData(Screen.width,Screen.height);
  
      // Calculem els eixos de la camera
      calcularEixos(Scene);
  
      // Calculem els increments i P0 (GLOBALS)
      incX = calcularIncrementX(Scene.Camera,Screen);
      incY = calcularIncrementY(Scene.Camera,Screen);
      P0 = calcularP0(incX,incY,Scene.Camera,Screen);
  
      // Executem RayTracing
      rayTracing(Scene, Screen);
      Screen.context.putImageData(Screen.buffer, 0, 0);
  };
  
  function sphereIntersection(sphere, ray, scene){
  
      var eye_to_center = vec3.subtract(sphere.point, scene.Camera.position);
  
      var v = vec3.dot(eye_to_center, vec3.clone(ray));
  
      var eoDot = vec3.dot(eye_to_center,eye_to_center);
  
      var discriminant = sphere.radi * sphere.radi -eoDot + v * v;
  
      if (discriminant&lt;0){
          return;
      }else{
          return v - Math.sqrt(discriminant);
      }
  }
  
  // Calcular increment de X
  function calcularIncrementX(Cam,Scr) {
      var rati = (Scr.height/Scr.width);
  
      var theta = (Cam.fov * Math.PI / 180);
      var w = 2*Math.tan(theta/2); // Calculem w' = 2*tg(theta/2)
      var h = w*rati; // Calculem h' = w'*rati
  
      var aux = w/Scr.width; // w'/W
      var incX = vec3.scale(Cam.X,aux); // Calculem increment de X (X * 2*tg(theta/2)/W)
  
      return incX;
  }
  
  
  // Calcular increment de Y
  function calcularIncrementY(Cam,Scr) {
      var rati = (Scr.height/Scr.width);
  
      var theta = (Cam.fov * Math.PI / 180);
      var w = 2*Math.tan(theta/2); // Calculem w' = 2*tg(theta/2)
      var h = w*rati; // Calculem h' = w'*rati
  
      var aux = rati*w/Scr.height; // rati*w'/H
      var incY = vec3.scale(Cam.Y,aux); // Calculem increment de Y (Y * 2*tg(theta/2)/W)
  
      return incY;
  }
  
  function isLightVisible(pt, scene, light){
      var distObject = intersectarScene(
          {
              point:pt,
              vector: vec3.unitVector(vec3.sub(pt, light)),
          },
          scene
      );
      return distObject[0] &gt; -0.005;
  }
  
  function surface(ray, scene, object, pointAtTime, normal, depth){
      var b = object.color;
      var c = [0,0,0];
      var lambertAmount = 0;
  
      if (object.lambert){
          for (var i = 0; i&lt;scene.Lights.length; i++){
              var lightPoint = scene.Lights[i].position;
              if (!isLightVisible(pointAtTime, scene, lightPoint)) continue;
              var contribution = vec3.dot(vec3.unitVector(vec3.subtract(lightPoint, pointAtTime)), normal);
              if (contribution &gt; 0) lambertAmount += contribution;
          }
      }
  
      if (object.specular){
          var reflectedRay = {
              point: pointAtTime,
              vector: vec3.reflectThrough(vec3.clone(ray), normal),
          };
          var reflectedColor = trace(reflectedRay, scene, ++depth);
  
          if(reflectedColor){
              c = vec3.add(c, vec3.scale(reflectedColor, object.specular));
          }
      }
  
      lambertAmount = Math.min(1,lambertAmount);
      var a = vec3.scale(b, lambertAmount * object.lambert);
      var d = vec3.scale(b, object.ambient);
  
      var color = vec3.add3(a, d, c); 
  
      return color;
  }
  
  // Calcular P0
  function calcularP0(incX,incY,Cam,Scr) {
  
      var P = vec3.subtract(Cam.position,Cam.Z); // Calculem P (O - Z)
      var aux = vec3.scale(incX,((Scr.width-1)/2)); // Increment de X * (W-1)/2
      var aux2 = vec3.scale(incY,((Scr.height-1)/2)); // Increment de Y * (H-1)/2
      var aux3 = vec3.subtract(P,aux); // P - Increment de X * (W-1)/2
      var P0 = vec3.add(aux3,aux2); // Calculem P0 (P - Increment de X * (W-1)/2 + Increment de Y * (H-1)/2)
  
      return P0;
  }
  
  
  // Calcular els eixos de la camera
  function calcularEixos(Scene) {
      Scene.Camera.Z = vec3.normalize(vec3.subtract(Scene.Camera.position, Scene.Camera.centre)); // |O - C|
      Scene.Camera.X = vec3.normalize(vec3.cross(Scene.Camera.up, Scene.Camera.Z)); // |up x Z|
      Scene.Camera.Y = vec3.cross(Scene.Camera.Z, Scene.Camera.X); // Z x X
  
  }
  
  
  function plot(x,y,color){
      var index = (x+y*Screen.buffer.width)*4;
      Screen.buffer.data[index+0] = color[0];
      Screen.buffer.data[index+1] = color[1];
      Screen.buffer.data[index+2] = color[2];
      Screen.buffer.data[index+3] = 255;
      return index;
  }
  
  function sphereNormal(sphere, pos) {
      return vec3.unitVector(vec3.subtract(pos, sphere.point));
  }
  
  function intersectarScene(ray, scene) {
      var closest = [Infinity, null];
  
      for (var i = 0; i&lt; scene.Shapes.length; i++){
          var object = scene.Shapes[i];
          var dist = sphereIntersection(object, ray,scene);
          if (dist !== undefined &amp;&amp; dist &lt; closest[0]) {
              closest = [dist, object];
          }
      }
      return closest;
  }
  
  function trace(ray, scene, depth){
  
      if (depth &gt; 3) return;
  
      var distObject = intersectarScene(ray,scene);
      if (distObject[0] === Infinity) {
          return [255,255,255];
        }
        
      var dist = distObject[0];
      var object = distObject[1];
      var pointAtTime = vec3.add(scene.Camera.position, vec3.scale(vec3.clone(ray), dist));
      return surface(ray,scene,object,pointAtTime, sphereNormal(object, pointAtTime), depth);
  }
  
  // Pintar cada pixel
  function rayTracing(Scene, Screen) {
      console.log(incX);
      for(var x = 0; x &lt; Screen.width; x++){
          for (y = 0; y &lt; Screen.height; y++){
              var rDirection = computeRay(incX,incY,P0,Scene.Camera,x,y);
              var color = trace(rDirection, Scene, 0);
              plot(x,y,color);
          }
      }
  }
  
  
  // Computar el raig
  function computeRay(incX,incY,P0,Cam,x,y){
  
      // Calculem la direccio per a cada pixel
      var aux = vec3.scale(incX,x); // Increment de X * x
      var aux2 = vec3.scale(incY,y); // Increment de Y * y
      var aux3 = vec3.add(P0,aux); // P0 + Increment de X * x
      var aux4 = vec3.subtract(aux3,aux2); // P0 + Increment de X * x - Increment de Y * y
      var ray = vec3.subtract(aux4,Cam.position); // Obtenim raig (P0 + Increment de X * x - Increment de Y * y - O)
      var rayNorm = vec3.normalize(ray); // Normalitzem el raig
  
      return rayNorm;
  }
  
  </code></pre>
  <p>VECTOR JS CODE:</p>
  <pre><code>/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
  
  Redistribution and use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:
  
    * Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
  
  /**
   * @class 3 Dimensional Vector
   * @name vec3
   */
  var vec3 = {};
  
  vec3.ZERO = { x: 0, y: 0, z: 0 };
  
  /**
   * Creates a new, empty vec3
   *
   * @returns {vec3} a new 3D vector
   */
  vec3.create = function() {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = 0;
      out[1] = 0;
      out[2] = 0;
      return out;
  };
  
  /**
   * Creates a new vec3 initialized with values from an existing vector
   *
   * @param {vec3} a vector to clone
   * @returns {vec3} a new 3D vector
   */
  vec3.clone = function(a) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0];
      out[1] = a[1];
      out[2] = a[2];
      return out;
  };
  
  vec3.unitVector = function(a){
      return vec3.scale(a, 1/vec3.len(a));
  };
  
  /**
   * Creates a new vec3 initialized with the given values
   *
   * @param {Number} x X component
   * @param {Number} y Y component
   * @param {Number} z Z component
   * @returns {vec3} a new 3D vector
   */
  vec3.fromValues = function(x, y, z) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = x;
      out[1] = y;
      out[2] = z;
      return out;
  };
  
  /**
   * Copy the values from one vec3 to another
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the source vector
   * @returns {vec3} out
   */
  vec3.copy = function(a) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0];
      out[1] = a[1];
      out[2] = a[2];
      return out;
  };
  
  
  /**
   * Set the components of a vec3 to the given values
   *
   * @param {vec3} out the receiving vector
   * @param {Number} x X component
   * @param {Number} y Y component
   * @param {Number} z Z component
   * @returns {vec3} out
   */
  vec3.set = function(x, y, z) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = x;
      out[1] = y;
      out[2] = z;
      return out;
  };
  
  /**
   * Adds two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.add = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] + b[0];
      out[1] = a[1] + b[1];
      out[2] = a[2] + b[2];
      return out;
  };
  
  vec3.unitVector = function(a){
      return vec3.scale(a, 1/vec3.len(a));
  };
  
  vec3.reflectThrough = function(a, normal){
      var d = vec3.scale(normal, vec3.dot(a,normal));
      return vec3.sub(vec3.scale(d,2),a);
  };
  
  /**
   * Adds three vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.add3 = function(a, b, c) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] + b[0] + c[0];
      out[1] = a[1] + b[1] + c[1];
      out[2] = a[2] + b[2] + c[2];
      return out;
  };
  
  /**
   * Subtracts vector b from vector a
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.subtract = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] - b[0];
      out[1] = a[1] - b[1];
      out[2] = a[2] - b[2];
      return out;
  };
  
  /**
   * Alias for {@link vec3.subtract}
   * @function
   */
  vec3.sub = vec3.subtract;
  
  /**
   * Multiplies two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.multiply = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] * b[0];
      out[1] = a[1] * b[1];
      out[2] = a[2] * b[2];
      return out;
  };
  
  /**
   * Alias for {@link vec3.multiply}
   * @function
   */
  vec3.mul = vec3.multiply;
  
  /**
   * Divides two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.divide = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] / b[0];
      out[1] = a[1] / b[1];
      out[2] = a[2] / b[2];
      return out;
  };
  
  /**
   * Alias for {@link vec3.divide}
   * @function
   */
  vec3.div = vec3.divide;
  
  /**
   * Returns the minimum of two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.min = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = Math.min(a[0], b[0]);
      out[1] = Math.min(a[1], b[1]);
      out[2] = Math.min(a[2], b[2]);
      return out;
  };
  
  /**
   * Returns the maximum of two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.max = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = Math.max(a[0], b[0]);
      out[1] = Math.max(a[1], b[1]);
      out[2] = Math.max(a[2], b[2]);
      return out;
  };
  
  /**
   * Scales a vec3 by a scalar number
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the vector to scale
   * @param {Number} b amount to scale the vector by
   * @returns {vec3} out
   */
  vec3.scale = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] * b;
      out[1] = a[1] * b;
      out[2] = a[2] * b;
      return out;
  };
  
  /**
   * Adds two vec3's after scaling the second operand by a scalar value
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @param {Number} scale the amount to scale b by before adding
   * @returns {vec3} out
   */
  vec3.scaleAndAdd = function(a, b, scale) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = a[0] + (b[0] * scale);
      out[1] = a[1] + (b[1] * scale);
      out[2] = a[2] + (b[2] * scale);
      return out;
  };
  
  /**
   * Calculates the euclidian distance between two vec3's
   *
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {Number} distance between a and b
   */
  vec3.distance = function(a, b) {
      var x = b[0] - a[0],
          y = b[1] - a[1],
          z = b[2] - a[2];
      return Math.sqrt(x*x + y*y + z*z);
  };
  
  /**
   * Alias for {@link vec3.distance}
   * @function
   */
  vec3.dist = vec3.distance;
  
  /**
   * Calculates the squared euclidian distance between two vec3's
   *
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {Number} squared distance between a and b
   */
  vec3.squaredDistance = function(a, b) {
      var x = b[0] - a[0],
          y = b[1] - a[1],
          z = b[2] - a[2];
      return x*x + y*y + z*z;
  };
  
  /**
   * Alias for {@link vec3.squaredDistance}
   * @function
   */
  vec3.sqrDist = vec3.squaredDistance;
  
  /**
   * Calculates the length of a vec3
   *
   * @param {vec3} a vector to calculate length of
   * @returns {Number} length of a
   */
  vec3.length = function (a) {
      var x = a[0],
          y = a[1],
          z = a[2];
      return Math.sqrt(x*x + y*y + z*z);
  };
  
  /**
   * Alias for {@link vec3.length}
   * @function
   */
  vec3.len = vec3.length;
  
  /**
   * Calculates the squared length of a vec3
   *
   * @param {vec3} a vector to calculate squared length of
   * @returns {Number} squared length of a
   */
  vec3.squaredLength = function (a) {
      var x = a[0],
          y = a[1],
          z = a[2];
      return x*x + y*y + z*z;
  };
  
  /**
   * Alias for {@link vec3.squaredLength}
   * @function
   */
  vec3.sqrLen = vec3.squaredLength;
  
  /**
   * Negates the components of a vec3
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a vector to negate
   * @returns {vec3} out
   */
  vec3.negate = function(a) {
      var out = new GLMAT_ARRAY_TYPE(3);
      out[0] = -a[0];
      out[1] = -a[1];
      out[2] = -a[2];
      return out;
  };
  
  /**
   * Normalize a vec3
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a vector to normalize
   * @returns {vec3} out
   */
  vec3.normalize = function(a) {
      var out = new GLMAT_ARRAY_TYPE(3);
      var x = a[0],
          y = a[1],
          z = a[2];
      var len = x*x + y*y + z*z;
      if (len &gt; 0) {
          //TODO: evaluate use of glm_invsqrt here?
          len = 1 / Math.sqrt(len);
          out[0] = a[0] * len;
          out[1] = a[1] * len;
          out[2] = a[2] * len;
      }
      return out;
  };
  
  /**
   * Calculates the dot product of two vec3's
   *
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {Number} dot product of a and b
   */
  vec3.dot = function (a, b) {
      return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  };
  
  /**
   * Computes the cross product of two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @returns {vec3} out
   */
  vec3.cross = function(a, b) {
      var out = new GLMAT_ARRAY_TYPE(3);
      var ax = a[0], ay = a[1], az = a[2],
          bx = b[0], by = b[1], bz = b[2];
  
      out[0] = ay * bz - az * by;
      out[1] = az * bx - ax * bz;
      out[2] = ax * by - ay * bx;
      return out;
  };
  
  /**
   * Performs a linear interpolation between two vec3's
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the first operand
   * @param {vec3} b the second operand
   * @param {Number} t interpolation amount between the two inputs
   * @returns {vec3} out
   */
  vec3.lerp = function (a, b, t) {
      var out = new GLMAT_ARRAY_TYPE(3);
      var ax = a[0],
          ay = a[1],
          az = a[2];
      out[0] = ax + t * (b[0] - ax);
      out[1] = ay + t * (b[1] - ay);
      out[2] = az + t * (b[2] - az);
      return out;
  };
  
  /**
   * Generates a random vector with the given scale
   *
   * @param {vec3} out the receiving vector
   * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
   * @returns {vec3} out
   */
  vec3.random = function (scale) {
      var out = new GLMAT_ARRAY_TYPE(3);
      scale = scale || 1.0;
  
      var r = GLMAT_RANDOM() * 2.0 * Math.PI;
      var z = (GLMAT_RANDOM() * 2.0) - 1.0;
      var zScale = Math.sqrt(1.0-z*z) * scale;
  
      out[0] = Math.cos(r) * zScale;
      out[1] = Math.sin(r) * zScale;
      out[2] = z * scale;
      return out;
  };
  
  /**
   * Transforms the vec3 with a mat4.
   * 4th vector component is implicitly '1'
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the vector to transform
   * @param {mat4} m matrix to transform with
   * @returns {vec3} out
   */
  vec3.transformMat4 = function(a, m) {
      var out = new GLMAT_ARRAY_TYPE(3);
      var x = a[0], y = a[1], z = a[2];
      out[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
      out[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
      out[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
      return out;
  };
  
  /**
   * Transforms the vec3 with a mat3.
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the vector to transform
   * @param {mat4} m the 3x3 matrix to transform with
   * @returns {vec3} out
   */
  vec3.transformMat3 = function(a, m) {
      var out = new GLMAT_ARRAY_TYPE(3);
      var x = a[0], y = a[1], z = a[2];
      out[0] = x * m[0] + y * m[3] + z * m[6];
      out[1] = x * m[1] + y * m[4] + z * m[7];
      out[2] = x * m[2] + y * m[5] + z * m[8];
      return out;
  };
  
  /**
   * Transforms the vec3 with a quat
   *
   * @param {vec3} out the receiving vector
   * @param {vec3} a the vector to transform
   * @param {quat} q quaternion to transform with
   * @returns {vec3} out
   */
  vec3.transformQuat = function(a, q) {
      var out = new GLMAT_ARRAY_TYPE(3);
      // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
  
      var x = a[0], y = a[1], z = a[2],
          qx = q[0], qy = q[1], qz = q[2], qw = q[3],
  
          // calculate quat * vec
          ix = qw * x + qy * z - qz * y,
          iy = qw * y + qz * x - qx * z,
          iz = qw * z + qx * y - qy * x,
          iw = -qx * x - qy * y - qz * z;
  
      // calculate result * inverse quat
      out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
      out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
      out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
      return out;
  };
  
  /**
   * Perform some operation over an array of vec3s.
   *
   * @param {Array} a the array of vectors to iterate over
   * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
   * @param {Number} offset Number of elements to skip at the beginning of the array
   * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
   * @param {Function} fn Function to call for each vector in the array
   * @param {Object} [arg] additional argument to pass to fn
   * @returns {Array} a
   * @function
   */
  vec3.forEach = (function() {
      var vec = vec3.create();
  
      return function(a, stride, offset, count, fn, arg) {
          var i, l;
          if(!stride) {
              stride = 3;
          }
  
          if(!offset) {
              offset = 0;
          }
          
          if(count) {
              l = Math.min((count * stride) + offset, a.length);
          } else {
              l = a.length;
          }
  
          for(i = offset; i &lt; l; i += stride) {
              vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2];
              fn(vec, vec, arg);
              a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2];
          }
          
          return a;
      };
  })();
  
  /**
   * Returns a string representation of a vector
   *
   * @param {vec3} vec vector to represent as a string
   * @returns {String} string representation of the vector
   */
  vec3.str = function (a) {
      return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
  };
  
  if(typeof(exports) !== 'undefined') {
      exports.vec3 = vec3;
  }
  </code></pre>