0

Following some tutorials of OpenGL I noticed some of them declare some variables like transform matrices and uniform locations on the main loop of the program. From my point of view I thought it would be a bad thing because it would allocate memory for the variables for each loop.

Is this a good thing to do? Why should I calculate the location of a uniform in the shaders very loop if the location won't change?

For example, a statement like this in this code GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model"); will get the same value every loop, why should I use this inside the loop then?

Jean Catanho
  • 326
  • 7
  • 18
  • I think, this is a valid question in the context of OpenGL. It is starkly different from the http://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice-2-parter which is very generic in scope, and in this case has no similarity at all with the asked question. – Sahil Bajaj Jan 21 '16 at 09:39
  • The other question helped me understand somethings related to the topic, but my question is indeed what should I do in the context of OpenGL. – Jean Catanho Jan 22 '16 at 05:19
  • You're right when you say, `glGetUniformLocation` will return the same value every loop, unless the properties of the drawable/mesh get changed resulting in a change in the shader that you use for it. So you can also choose to only do it when such a case happens. But for that you might need to handle a lot of cases in a lot of places depending of the code flow/architecture you've for yourself. – Sahil Bajaj Jan 22 '16 at 05:24
  • So, if I'm sure that the mesh doesn't change through the loop, I can guarantee that I can call `glGetUniformLocation()` outside the loop then? What changes in the mesh could change the uniform location? (should I ask a new question for this one?) – Jean Catanho Jan 22 '16 at 05:39
  • Let's say you apply a filter/texture on the mesh. For that the shader code will be different. It'll invariably have a few more uniforms. Hence the uniform locations might get changed. So yes, you can do it outside the loop, once per lifecycle of the GL context. – Sahil Bajaj Jan 22 '16 at 05:43
  • Now I understand, thank you! – Jean Catanho Jan 22 '16 at 05:48

0 Answers0