I recently added support to phong shading in a cpu ray-tracer and the colors are all messed-up:
Some relevant code:
Vec3f camera_dir (xx_array[x],py,scene->getCameraDirZ());
camera_dir.normalize ();
Vec3f hit_normal = (1 - u - v) * vert1 + u * vert2 + v * vert3;
hit_normal.normalize ();
Vec3f light_ray_dir (current.pos - intersection);
float squared_length = light_ray_dir.normalize_return_squared_lenght ();
Vec3f reflected = light_ray_dir - 2 * (light_ray_dir * hit_normal) * hit_normal;
reflected.normalize();
specular_color += light_intensity * std::pow (std::max(0.f,reflected*camera_dir),mat.ns);
final_color = diffuse_color * mat.ks; + specular_color * mat.kd; (if is only difusse * mat.ks or mat.kd it produces the second image)
Some possibly relevant information
The four last lines are consecutive, although the last one happens outside the for loop responsible for doing the shading calculations for each light.
The two "hit_normal" lines happens earlier, they are before the aforementioned loop start.
The first two happens in the beginning of the ray-tracer, in earlier lines of the two for loops responsible for the image pixels.
if I swap the reflected calculation from
Vec3f reflected = light_ray_dir - 2 * (light_ray_dir * hit_normal) * hit_normal;
to:
Vec3f reflected = 2 * (light_ray_dir * hit_normal) * hit_normal - light_ray_dir;
image only changes slightly:
As code shows, all three component vectors (hit_normal, reflected, light_ray_dir, camera_dir) are normalized.
So I ask for suggestions of how to debug the issue, suggestions of what can be wrong. Thanks for the attention.