4
$\begingroup$

Working on optimizing a fragment shader which is slowing down my OpenGL ES 2.0 shader based game. This is used with a shadow buffer to determine if the fragment/pixel is inside a shadow volume.

The problem/slowdown is the fact I need a branch if or function to determine a 1.0 (no shadow) or 0.0 (shadowed) based on comparison of the frag's shadow Z and shadow buffer Z.

    // SLOWEST
    if ( shadowValue > shadowTexZ ) return 1.0; else return 0.0;

    // ALSO SLOW
    return clamp( 1.0 + (shadowValue - shadowTexZ) * 1000.0, 0.0, 1.0 );

    // SLIGHT LESS SLOW
    return max(sign(shadowValue - shadowTexZ), 0.0);

    // ALSO SLOW
    return sign( shadowValue - shadowTexZ ) * 0.5 + 0.5;

If I disable the shadow test all together, GPU time in Xcode is 12ms and solid 60fps. With the test on it jumps to 26ms and drops the framerate unacceptably to 40fps.

Thanks!

$\endgroup$
  • $\begingroup$ I wonder if it's the texture read(s?) that are slow. If you don't use the value that results from the texture read, it probably isn't even doing the texture read. You could try doing dummer math with those values to see if it's still slow. like maybe return shadowValue + shadowTexZ; $\endgroup$ – Alan Wolfe Sep 23 '16 at 23:22
  • $\begingroup$ I also think the compiler may be optimizing out some parts of your code if you comment this line. Please check the lower level generated code to be sure. Moreover, you should check the step function documentation for optimizing out this particular branch. $\endgroup$ – vgs Sep 24 '16 at 4:42
2
$\begingroup$

I think the most efficient way might be either

return float(shadowValue > shadowTexZ);

or

return step(shadowTexZ, shadowValue);
$\endgroup$
  • 2
    $\begingroup$ Could you share you reasons for settling on these approaches? The logic behind it or profiling evidence perhaps? $\endgroup$ – trichoplax Sep 25 '16 at 11:40
  • $\begingroup$ The first one to me seems like the most straightforward approach to obtain the desired result and the second one is something the GPU potentially might be better suited for than comparisons and type casting. Maybe I'm completely wrong, but it's worth a try at least. $\endgroup$ – Detheroc Sep 25 '16 at 14:30
  • 2
    $\begingroup$ These seem like points worth expanding your answer with. $\endgroup$ – trichoplax Sep 25 '16 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.