The max() function in GLSL is a built-in function that returns the maximum value between two or more values. Here's a comprehensive overview:
Basic Syntax
glsl
// For two values
float max(float x, float y);
vec2 max(vec2 x, vec2 y);
vec3 max(vec3 x, vec3 y);
vec4 max(vec4 x, vec4 y);
// For vector and scalar
vec2 max(vec2 x, float y);
vec3 max(vec3 x, float y);
vec4 max(vec4 x, float y);
// Component-wise for arrays
float max(float[] values);
Examples
glsl
// Basic usage with floats
float a = 2.5;
float b = 3.7;
float result = max(a, b); // Returns 3.7
// With vectors (component-wise)
vec3 color1 = vec3(0.2, 0.5, 0.8);
vec3 color2 = vec3(0.1, 0.7, 0.4);
vec3 maxColor = max(color1, color2); // Returns vec3(0.2, 0.7, 0.8)
// Vector and scalar
vec3 values = vec3(1.0, 2.0, 3.0);
vec3 result = max(values, 2.5); // Returns vec3(2.5, 2.5, 3.0)
Practical Use Cases
1. Clamping Values
glsl
// Ensure value is at least a minimum
float safeValue = max(inputValue, 0.0);
2. Brightness Adjustment
glsl
// Increase brightness but don't exceed 1.0
vec3 brighterColor = max(color * 1.5, color);
3. Edge Detection
glsl
// Find maximum RGB component for edge detection
float edge = max(max(color.r, color.g), color.b);
4. Normal Mapping
glsl
// Ensure normal components are properly bounded
vec3 normal = normalize(max(texture(normalMap, uv).rgb, 0.0));
Performance Notes
max()is highly optimized in hardware- Component-wise operations are parallelized
- Generally faster than writing custom comparison logic
Related Functions
min()- Returns the minimum valueclamp()- Clamps between min and max valuesmix()- Linear interpolationsmoothstep()- Smooth interpolation
The max() function is essential for many graphics programming tasks, particularly in fragment shaders where you often need to compare and constrain color values or other parameters.