Search Unity

Is a static const initialized once or everytime?

Discussion in 'Shaders' started by aubergine, Sep 12, 2019.

  1. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,878
    uniform float var1;
    uniform float var2;
    static const float varSum = var1 + var2;

    What happens to varSum in this situation?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    There are three possibilities I can think of:

    A) The shader compiler throws an error
    B) The shader compiler sets varSum to 0.0
    C) The shader compiler ignores the static const and ... magic happens?

    Option A would be the most correct in my opinion. Since var1 & var2 don't exist at compile time, there's no way for the value to actually be const. A static const variable should mean it is known at compile time and cannot be changed by the shader.

    Option B would be a semi-logical option as var1 and var2 could be considered 0 at compile time. It'd be wrong, but I can see some compiler making this choice.

    Option C would mean the compiler sees that you're not using const values as inputs, and just ignores the modifiers you've set and magically turn that line into a macro that just puts (var1 + var2) into your shader whenever you use varSum. This is highly unlikely ... but I wouldn't put it past some shader compiler to do some bullshi...uh bullish magic like that.
     
  3. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,878
    I think its something like the option c with unity, it does compile and value is correctly set to the sum of uniforms. Probably ignores the static and const or just reinitializes the variable everytime, i dont know.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    Well, it's the default Microsoft shader compiler likely doing this. I want to try this now and look at the compiled shader because that really shouldn't work.
     
  5. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,878
    my compiled shader says:
    and Microsoft says:
    So, it shouldnt work but it does. very strange.