Reputation: 521
Wondering how to write GLSL functions that can take different kinds of arguments.
From my understanding, in GLSL a * b
can be called for vec2 * vec2
, vec2 * vec3
, ..., vec2 * mat3
, etc. For probably dozens of combinations. I'm wondering how to write this as a function though, to get a better understanding of the language.
Wondering if you need to actually write out every combination:
vec2
multiply(vec2 a, vec2 b) {
return a * b
}
vec3
multiply(vec3 a, vec3 b) {
return a * b
}
....
Or if you can write one function that handles them all:
vec or mat
multiply(a, b) {
return a * b
}
Not sure how it works. Maybe they all need different names:
vec2
multiplyv2(vec2 a, vec2 b) {
return a * b
}
vec3
multiplyv3(vec3 a, vec3 b) {
return a * b
}
....
Update:
First part is solved:
vec2 rotate(vec2 v, float angle) {
return rotation2d(angle) * v;
}
vec3 rotate(vec3 v, vec3 axis, float angle) {
return (rotation3d(axis, angle) * vec4(v, 1.0)).xyz;
}
You can overload functions.
Upvotes: 1
Views: 1706
Reputation: 324
GLSL doesn't have templates or generics so you can't get the compiler to generate instances of the function for different types automatically for you. However as you've discovered, it does support function overloading, so you can reduce the code duplication using a macro to instantiate the same function for different types like so.
#define MULTIPLY_TEMPLATE(type) \
type multiply(type a, type b) { \
return a * b; \
}
MULTIPLY_TEMPLATE(vec2)
MULTIPLY_TEMPLATE(vec3)
MULTIPLY_TEMPLATE(vec4)
Upvotes: 4