Get component-wise maximum of vector in GLSL
Asked Answered
T

2

20

I need to get the maximum of a vec3 in GLSL. Currently I am doing

max(max(col.r, col.g),col.b)

It works. But I am wondering if there a better way to do this with one built-in function call?

Timi answered 18/1, 2015 at 1:14 Comment(0)
T
26

That is the best you are going to do in GLSL, unfortunately.

I have gotten used to writing that sort of thing. However, if it bothers you, you can always write your own function that does that.

For example:

float max3 (vec3 v) {
  return max (max (v.x, v.y), v.z);
}
Tankard answered 18/1, 2015 at 22:28 Comment(0)
H
0

While for vec3 you need two max operations, for vec4 you do not need three, two are enough:

vec2 maxPairs = max(v.xy, v.zw);
float maxValue = max(maxPairs.x, maxPairs.y);

It may even be extended to finding max of two vec4 with three max:

vec4 v = max(a, b);
vec2 maxPairs = max(v.xy, v.zw);
float maxValue = max(maxPairs .x, maxPairs.y);

Note: I doubt it will make any difference on todays hardware, and if it does, the optimizer will probably rearrange the code for you anyway. I feel a bit nostalgic about times when "code golf" like this was a regular part of my work.

Harlem answered 9/9, 2023 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.