I implemented phong shading on my raytracer. Unfortunatelly I am receiving a segmentation fault when running it. The likely cause is related to the "specular_color" Vec3f variable (with is an object made of three floats). When I print its values, I receive:
specular_color: inf inf inf
To figure out the reason was not complicated:
It is calculated this way:
specular_color += light_intensity * std::pow (reflected*camera_dir,mat.ns);
where mat.ns is the specular exponent, that exhibits the expected values.
reflected*camera_dir is the cause, because it always end being a big value. In three of four of my test cases it is a five digit value. In the other is a six digit value (close to seven). So five or six digit values taken to any exponent that isn't fairly close to one is likely to overflow the float variables.
Now the questions is why these values are so big, if they can or cannot be that way. If they cannot, then likely there is a bug in previous code. If they can, all that is missing is to normalize the reflected vector (camera_dir is already unitary)
Reflected vector is calculated this way:
Vec3f reflected = light_ray_dir - 2 * (light_ray_dir * hit_normal) * hit_normal;
where light_ray_dir is calculated as:
Vec3f light_ray_dir (current.pos - intersection);
With current being the name of the light_source and intersection being the point of encounter of the ray with the triangle.
It always worked fine when it did only diffuse light.
hit_normal, however, is new code and is calculated as:
Vec3f hit_normal = (1 - u - v) * vert1 + u * vert2 + v * vert3;
with u and v being the barycentric coordinates and vertX the triangle's vertices.
So what seems more likely? A more complex bug perhaps in the above code or just a missing normalization to the reflected vector. Or perhaps something else? Thanks for your time.