gandeev
gandeev

Reputation: 11

Initializing global variables in glsl?

works fine in my setup but want to be sure. using glsl 430 and I have this in my geometry shader

#version 430
layout (points) in;
layout (triangle_strip) out;
layout (max_vertices = 24) out;

uniform mat4 u_projMatrix;
uniform mat4 u_viewMatrix;

mat4 viewProjection = u_projMatrix * u_viewMatrix;

void someFunction1(){
 // uses viewProjection 
}

void someFunction2(){
 // uses viewProjection 
}

void main()
{
  // uses viewProjection 
}

my concern is with viewProjection , I expect viewProjection to be initialized before main(). I went through the glsl manual and looks like it will do exactly that and should compile fine.If it is not valid code can someone please refer me to the section in the spec, thanks

Upvotes: 1

Views: 1230

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473192

Yes, this code is technically fine. The specification allows you to use arbitrary expressions to initialize global variables, even ones which use uniforms and the like. Essentially, they will execute before main starts.

But you shouldn't actually use this.

First, this sort of thing is very uncommon in shader code. As such, OpenGL implementations are less likely to be properly tested against it. Which means that there is a greater chance of the implementation getting this code wrong in some way. It's much safer to just write the code in main.

Second, you're hiding the cost of your shader. If your initializations are not constant expressions, then they will actually cost execution time. But you won't see it in main nor in any function main calls. It will exist outside of what you normally think of as "code". But it will still cost performance.

Upvotes: 1

Related Questions