7
\$\begingroup\$

My question is about passing variables to GLSL shader. I'm not sure how that works and what are the performance implications.

Say I got a function that accepts a "vec4" variable. The question is - is that variable copied at the entrance? I guess it makes impact on performance if so. And if it happens to be that way is there a way to pass only references like in C/C++?

\$\endgroup\$
2
  • \$\begingroup\$ GLSL doesn't run on the CPU so you shouldn't think about it in the same terms as code that does run on the CPU. \$\endgroup\$ Mar 4, 2014 at 21:00
  • 3
    \$\begingroup\$ This ^ comment is totally uninformative. Tell us how we should think about it, running on the GPU, then.. ¯_(ツ)_/¯ \$\endgroup\$ Jun 19, 2018 at 23:15

2 Answers 2

8
\$\begingroup\$

GLSL always uses copying, but this doesn't have the same performance implications as C++. In particular, because there is no recursion, there isn't a stack, and typically either functions are inlined and optimized there by the GLSL compiler, or parameters are in fixed register locations and copying is unnecessary.

Note that passing by const& in C++ is completely different from "passing by reference." In passing by reference, the function is allowed to change the argument, and these changes are visible to the calling function. "inout" achieves a similar result, but is not quite the same as vec4& in C++ if you pass the same variable to different parameters of a function.

vec4 is a primitive type in GLSL, you can expect it to behave like a int or float for performance. Finally, vec4 is only 128 bits, which is one or two cycles to copy.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Correction: In C++ passing by const& IS passing by reference. It's just a read-only reference. \$\endgroup\$ Sep 25, 2020 at 15:13
0
\$\begingroup\$

You can mark the variable in the signature as "input". This will work as a reference pass (at least I'm the way you have asked).

\$\endgroup\$
1
  • 2
    \$\begingroup\$ this is actually not the case. The GLSL specification states: > 6.1.1 Function Calling Conventions > > Input arguments are copied into the function at call time, and output > arguments are copied back to the caller before function exit. 'in' is the default qualifier and will pass the argument by value. \$\endgroup\$
    – AlvaroSan
    Mar 28, 2017 at 21:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .