Ray Tracing in a Weekend Part 2 - The vec3 class


The vec3 class

In part 1 I made a simple image by assigning rgb values to individual variables in a loop across the x- and y-coordinates.

This example produces the same image, but introduces the vec3 class used to perform calculations with 3-dimensional vectors and access them as x, y, z-coordinates or r, g, b-color values.

The code below is complete, but feel free to download the complete repo from https://github.com/celeph/ray-tracing-in-a-weekend.

=== vec3.h

#ifndef VEC3H
#define VEC3H

#include <math.h>
#include <stdlib.h>
#include <iostream>

class vec3 {
public:
  float e[3];

  vec3() {}
  vec3(float e0, float e1, float e2) {
    e[0] = e0;
    e[1] = e1;
    e[2] = e2;
  }

  inline float x() const { return e[0]; }
  inline float y() const { return e[1]; }
  inline float z() const { return e[2]; }

  inline float r() const { return e[0]; }
  inline float g() const { return e[1]; }
  inline float b() const { return e[2]; }

  inline const vec3& operator+() const { return *this; }
  inline vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); }
  inline float operator[](int i) const { return e[i]; }
  inline float& operator[](int i) { return e[i]; }

  inline vec3& operator+=(const vec3 &v2);
  inline vec3& operator-=(const vec3 &v2);
  inline vec3& operator*=(const vec3 &v2);
  inline vec3& operator/=(const vec3 &v2);
  inline vec3& operator*=(const float t);
  inline vec3& operator/=(const float t);

  inline float length() const {
    return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
  }

  inline float squared_length() const {
    return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
  }

  inline void make_unit_vector();
};

inline std::istream& operator>>(std::istream &is, vec3 &t) {
  is >> t.e[0] >> t.e[1] >> t.e[2];
  return is;
}

inline std::ostream& operator<<(std::ostream &os, const vec3 &t) {
  os << t.e[0] << " " << t.e[1] << " " << t.e[2];
  return os;
}

inline void vec3::make_unit_vector() {
  float k = 1.0 / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
  e[0] *= k;
  e[1] *= k;
  e[2] *= k;
}

inline vec3 operator+(const vec3 &v1, const vec3 &v2) {
  return vec3(v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]);
}

inline vec3 operator-(const vec3 &v1, const vec3 &v2) {
  return vec3(v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]);
}

inline vec3 operator*(const vec3 &v1, const vec3 &v2) {
  return vec3(v1.e[0] * v2.e[0], v1.e[1] * v2.e[1], v1.e[2] * v2.e[2]);
}

inline vec3 operator/(const vec3 &v1, const vec3 &v2) {
  return vec3(v1.e[0] / v2.e[0], v1.e[1] / v2.e[1], v1.e[2] / v2.e[2]);
}

inline vec3 operator*(float t, const vec3 &v) {
  return vec3(t * v.e[0], t * v.e[1], t * v.e[2]);
}

inline vec3 operator/(const vec3 &v, float t) {
  return vec3(v.e[0] / t, v.e[1] / t, v.e[2] / t);
}

inline vec3 operator*(const vec3 &v, float t) {
  return vec3(t * v.e[0], t * v.e[1], t * v.e[2]);
}

inline float dot(const vec3 &v1, const vec3 &v2) {
  return v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2];
}

inline vec3 cross(const vec3 &v1, const vec3 &v2) {
  return vec3(
    (v1.e[1] * v2.e[2] - v1.e[2] * v2.e[1]),
    (-(v1.e[0] * v2.e[2] - v1.e[2] * v2.e[0])),
    (v1.e[0] * v2.e[1] - v1.e[1] * v2.e[0])
  );
}

inline vec3& vec3::operator+=(const vec3 &v) {
  e[0] += v.e[0];
  e[1] += v.e[1];
  e[2] += v.e[2];
  return *this;
}

inline vec3& vec3::operator*=(const vec3 &v) {
  e[0] *= v.e[0];
  e[1] *= v.e[1];
  e[2] *= v.e[2];
  return *this;
}

inline vec3& vec3::operator/=(const vec3 &v) {
  e[0] /= v.e[0];
  e[1] /= v.e[1];
  e[2] /= v.e[2];
  return *this;
}

inline vec3& vec3::operator-=(const vec3 &v) {
  e[0] -= v.e[0];
  e[1] -= v.e[1];
  e[2] -= v.e[2];
  return *this;
}

inline vec3& vec3::operator*=(const float t) {
  e[0] *= t;
  e[1] *= t;
  e[2] *= t;
  return *this;
}

inline vec3& vec3::operator/=(const float t) {
  float k = 1.0/t;
  e[0] *= k;
  e[1] *= k;
  e[2] *= k;
  return *this;
}

inline vec3 unit_vector(vec3 v) {
  return v / v.length();
}

#endif

=== vec3-example.cpp

#include <iostream>
#include “vec3.h”
int main() {
  int nx = 200;
  int ny = 100;
  std::cout << “P3\n” << nx << “ ” << ny << “\n255\n”;
  for (int j = ny-1; j >= 0; j–) {
    for (int i = 0; i < nx; i++) {
      vec3 col( float(i) / float(nx), float(j) / float(ny), 0.2 );
      int ir = int(255.99 * col[0]);
      int ig = int(255.99 * col[1]);
      int ib = int(255.99 * col[2]);
      std::cout << ir << “ ” << ig << “ ” << ib << “\n”;
    }
  }
}

=== Makefile


CC = g++
CFLAGS = -g
INCFLAGS = -I./


RM = /bin/rm -f
all: vec3-example

vec3-example: vec3-example.o
    $(CC) $(CFLAGS) -o vec3-example vec3-example.o

vec3-example.o: vec3-example.cpp
    $(CC) $(CFLAGS) $(INCFLAGS) -c vec3-example.cpp

clean:
    $(RM) *.o vec3-example *.ppm

run: vec3-example
    ./vec3-example > vec3-example.ppm

vec3 with Javascript and 2D Canvas

Here’s also the same example in Javascript. I apologize if the Javascript code is not super fancy or modern. I know kids these days do a lot differently. :)

class vec3 {
  constructor(e0,e1,e2) {
    this.e = [];
    this.e[0] = parseFloat(e0);
    this.e[1] = parseFloat(e1);
    this.e[2] = parseFloat(e2);
  }
  
  get x() { return this.e[0]; }
  get y() { return this.e[1]; }
  get z() { return this.e[2]; }
  get r() { return this.e[0]; }
  get g() { return this.e[1]; }
  get b() { return this.e[2]; }

  toString() { return '('+this.e[0]+','+this.e[1]+','+this.e[2]+')'; }
  
  add(summand) {
    if (summand.constructor.name == this.constructor.name) { // perform vec3 + vec3
      return new vec3(this.e[0]+summand.e[0], this.e[1]+summand.e[1], this.e[2]+summand.e[2]);
    } else { // perform vec3 + float
      summand = parseFloat(summand);
      return new vec3(this.e[0]+summand, this.e[1]+summand, this.e[2]+summand);
    }
  }

  sub(subtrahend) {
    if (subtrahend.constructor.name == this.constructor.name) { // perform vec3 - vec3
      return new vec3(this.e[0]-subtrahend.e[0], this.e[1]-subtrahend.e[1], this.e[2]-subtrahend.e[2]);
    } else { // perform vec3 - float
      subtrahend = parseFloat(subtrahend);
      return new vec3(this.e[0]-subtrahend, this.e[1]-subtrahend, this.e[2]-subtrahend);
    }
  }
  
  mul(factor) {
    if (factor.constructor.name == this.constructor.name) { // perform vec3 * vec3
      return new vec3(this.e[0]*factor.e[0], this.e[1]*factor.e[1], this.e[2]*factor.e[2]);
    } else { // perform vec3 * float
      factor = parseFloat(factor);
      return new vec3(this.e[0]*factor, this.e[1]*factor, this.e[2]*factor);
    }
  }
  
  div(divisor) {
    if (divisor.constructor.name == this.constructor.name) { // perform vec3 / vec3
      return new vec3(this.e[0]/divisor.e[0], this.e[1]/divisor.e[1], this.e[2]/divisor.e[2]);
    } else { // perform vec3 / float
      divisor = 1/parseFloat(divisor);
      return this.mul(divisor);
    }
  }
  
  dot(v2) {
    if (v2.constructor.name == this.constructor.name) { // perform vec3 dot vec3
      return this.e[0]*v2.e[0] + this.e[1]*v2.e[1] + this.e[2]*v2.e[2];
    } else return this;
  }
  
  cross(v2) {
    if (v2.constructor.name == this.constructor.name) { // perform vec3 cross vec3
      return new vec3( (this.e[1]*v2.e[2] - this.e[2]*v2.e[1]),
        (-(this.e[0]*v2.e[2] - this.e[2]*v2.e[0])),
        (this.e[0]*v2.e[1] - this.e[1]*v2.e[0]) );
    } else return this;
  }
  
  length() {
    return Math.sqrt(this.e[0]*this.e[0] + this.e[1]*this.e[1] + this.e[2]*this.e[2]);
  }
  
  squared_length() {
    return this.e[0]*this.e[0] + this.e[1]*this.e[1] + this.e[2]*this.e[2];
  }
  
  make_unit_vector() {
    var k = 1.0 / this.length();
    return this.mul(k);
  }
  
  unit_vector() {
    return this.div(this.length()); 
  }
}

var example = {
  main: function() {
    var c = document.getElementById('example');
    var ctx = c.getContext('2d');
        
    var nx = 200;
    var ny = 100;
    for (var j = ny-1; j >= 0; j--) {
      for (var i = 0; i < nx; i++) {
        var color = new vec3(parseFloat(i)/parseFloat(nx), parseFloat(j)/parseFloat(ny), 0.2);
        color = color.mul(255.99);
        ctx.fillStyle = 'rgb('+parseInt(color.r)+','+parseInt(color.g)+','+parseInt(color.b)+')';
        ctx.fillRect(i, ny-j, 1, 1);
      }
    }
  }
};
window.onload = function() { example.main(); };