I'm practicing GLSL on ShaderToy

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {

vec2 coord = fragCoord.xy/iResolution.xy;

vec3 background = vec3(1.);

vec3 axesColor = vec3(1.,0.,0.);
vec3 gridColor = vec3(0.85);

vec3 color = background;

const float tickWidth = 0.1;
for(float i = 0.0 ; i < 1.0 ; i += tickWidth)
    if(abs(coord.x - i) < 0.002) color = gridColor;
    if(abs(coord.y - i) < 0.002) color = gridColor;

if(abs(coord.x) < 0.005) color = axesColor;
**if(abs(coord.y) < 0.005) color = axesColor;**
**//color = abs(coord.y) < 0.005 ? axesColor : background;**

fragColor = vec4(color,1.0);  }

my question is on last 3 lines.

First, I used ternary operator for branch, but it made weird result that only drawing "x axes".

However, when I changed the operator to if, it works well. The code drew x, y axes and all grids as I wanted.

So I wonder is there different between if and ternary operation in GLSL? If that, how can I choose correctly?


The difference is obvious. The ternary operator will return one of the two alternative values it is given; that's what it is for. An if condition that doesn't have an else block won't do anything if the condition is false.

The ternary operator version will set color to axesColor or background. But by that point in your code, you've gone past 3 other conditions that may have changed the value of color from its initial value of background. But the ternary operator doesn't care. It will overwrite whatever is in color with either axesColor or background.

What you probably wanted was color = abs(coord.y) < 0.005 ? axesColor : color;, so that the value will be preserved if the condition is false.

  • $\begingroup$ wow, I fully understood, Thanks!! $\endgroup$ – Oh Seo Nov 8 '20 at 15:07
  • $\begingroup$ Doesn't compilers tend to compute both branches of the ternary and just discard when needed? From what I have read smart enough compilers should do the same (when not very performance intensive) with branches. $\endgroup$ – Felipe Gutierrez Nov 9 '20 at 3:24
  • $\begingroup$ @FelipeGutierrez: That has nothing to do with the issue here. That's a matter of optimization. The OP's issue is that the if version specifically does something different from the ?: version. Because they're supposed to do different things; the statements aren't equivalent. $\endgroup$ – Nicol Bolas Nov 9 '20 at 3:37
  • $\begingroup$ Yep I am aware, just adding to the knowledge base I guess. That's why I didn't add it as an answer. $\endgroup$ – Felipe Gutierrez Nov 10 '20 at 3:07

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.