Note that there are some explanatory texts on larger screens.

plurals
  1. POWebGL fragment shader not branching correctly on if statement
    text
    copied!<p>I'm working on a WebGL program which implements shadow mapping. After computing the depth values at each fragment, I have an if statement at the end which computes the lighting based on whether the fragment is in a shadow or not.</p> <pre><code>gl_FragColor = vec4(calcLighting(light0, eye_dir, eye_dir_norm, normal), 1); if (light_tex_coord.z - depth &lt;= 0.0) { gl_FragColor += vec4 ( calcLighting(light1, eye_dir, eye_dir_norm, normal) , 0.0 ); } </code></pre> <p><img src="https://i.stack.imgur.com/Z34bp.png" alt="Shadows not being correctly computed, branch never taken"></p> <p>where <code>depth</code> is the depth of the shadow map and <code>light_tex_coord</code> is the fragment's position in the scene space of <code>light1</code>. <code>light1</code> is a point light rotating around the model, and <code>light0</code> is a point light statically positioned at the camera.</p> <p>The issue here is that the if branch is never taken, so the scene only has <code>light0</code> applied to it. I've checked that <code>depth</code>, <code>light_tex_coord</code>, and <code>calculateLighting</code> work correctly. </p> <p>Here's the strange thing, though, replacing the above with the following code:</p> <pre><code>if (light_tex_coord.z - depth &lt;= 0.0) { gl_FragColor = vec4(0,1,0,1); } else { gl_FragColor = vec4(1,0,0,1); } </code></pre> <p><img src="https://i.stack.imgur.com/0bXdP.png" alt="Shadowed fragments correctly computed and drawn as red and green"></p> <p>Causes shadowed areas to be correctly drawn in red, and unshadowed to be drawn in green. That is, the branch is correctly evaluated. Replacing it with this:</p> <pre><code>gl_FragColor = vec4(calcLighting(light0, eye_dir, eye_dir_norm, normal), 1); gl_FragColor += vec4 ( calcLighting(light1, eye_dir, eye_dir_norm, normal) , 0.0 ); </code></pre> <p><img src="https://i.stack.imgur.com/rJ3vC.png" alt="Lighting computed without shadows"></p> <p>Causes lighting to be correctly computed (sans shadows, though). It seems that when I call the more expensive calcLighting function in the if statement, it doesn't even bother taking it.</p> <p>Further, I've tried applying the lighting in several ways including using the <code>clamp</code> function; always doing the addition and using a terinary operator to multiply the second <code>calcLighting</code> call by 1 or 0, and arranging my if statement in different ways. Nothing seems to work.</p> <p>Is there something I'm missing about how branching works in webgl?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload