Skip to content

A non recursive implementation of ray_color #624

@D-K-E

Description

@D-K-E

I would like to suggest a simple non recursive implementation for ray_color function to be mentioned in an alternative listing during the first book around chapter 8.

I realize that it is maybe outside of the current scope of the first book, where everything is as simple as possible. However, since portability is also a concern for the first book, and it is not possible to use recursion in glsl and OpenCL, it might help to briefly at least mention a non recursive implementation from which the reader might build her own version for more complicated stuff later on.

Here is my proposition:

color ray_color2(const Ray &r, const HittableList &scene, int depth) {
  Ray r_in = Ray(r.origin, r.direction);
  color rcolor = color(1,1,1);
  while (true) {
    HitRecord record;
    if (depth <= 0) {
      // final case
      return color(0);
    }
    if (scene.hit(r_in, 0.001, INF, record)) {
      // recursive case
      point3 target = record.point + random_in_hemisphere(record.normal);
      r_in = Ray(record.point, target - record.point);
      depth--;
      rcolor *= 0.5;
    } else {
      // no hit so bye
      vec3 direction = unit_vector(r_in.direction);
      double temp = 0.5 * (direction.y() + 1.0);
      rcolor *= (1.0 - temp) * color(1,1,1) + temp * color(0.5, 0.7, 1.0);
      return rcolor;
    }
  }
}

Note that I am not using any call stack to emulate the recursion. The function correctly renders the figure in Rendering of diffuse spheres with hemispherical scattering, I also ported it to glsl and it works over there as well.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions