I am trying to use basic lighting techniques described in Metal By Tutorials to produce a diffuse, ambient, and specular light on my models.
I have used this lighting algorithm plenty of times and it works great, but the past 2 times the specular color seems to produce a characteristic green and yellow noise. Even without the specular color, the diffuse and ambient colors seem to produce this awful noise.
Any ideas as to why this would be happening?
I wonder if the fact that I do not use a renderer class is causing this problem.
Here is fragment shader code:
fragment float4 fragmentmain(const VOUT in [[stage_in]],
texture2d<float> texture1 [[texture(0)]],
constant FRAGMENTUNIFORMS &data [[buffer(2)]],
constant LIGHT *lights [[buffer(3)]])
{
constexpr sampler texturesampler;
float3 basecolor = texture1.sample(texturesampler, in.coords).rgb;
float3 diffusecolor;
float3 ambientcolor;
float3 specularcolor;
float3 materialspecularcolor = float3(1,1,1);
float shine = 32;
float3 normaldirection = normalize(in.normal);
for (uint i = 0 ; i < data.lightcount ; i++) {
LIGHT light = lights[i];
if (light.type == sun) {
float3 lightdirection = normalize(-light.position);
float diffuseintensity = saturate(-dot(lightdirection, normaldirection));
diffusecolor = light.color * basecolor * diffuseintensity;
if (diffuseintensity > 0) {
float3 reflection = reflect(lightdirection, normaldirection);
float3 cameradirection = normalize(in.position.xyz - data.cameraposition);
float specularintensity = pow(saturate(-dot(reflection, cameradirection)), shine);
specularcolor = light.color * materialspecularcolor * specularintensity;
}
} else if (light.type == ambient) {
ambientcolor = light.color * light.intensity;
}
}
float3 color = diffusecolor + ambientcolor + specularcolor;
return float4(color, 1);
}