Mix
Task
Implement a smooth horizontal transition between two colors on the screen. The first color (color1) should remain solid and unchanged in the initial 25% of the screen width. Beyond this point, a gradual blending should begin, transitioning into the second color (color2). The transition should be fully completed at the right edge of the screen, where the color should match color2 exactly.
Hint
You can use the step function to constrain the interpolation parameter to 0.25, ensuring no transition occurs before this point. Then, normalize the remaining range [0.25, 1.0] into [0.0, 1.0].
Theory
the mix function is used to perform linear interpolation between two values based on a third interpolation factor. This function is commonly used in shaders to smoothly transition between two values, such as colors, positions, or other attributes.
Function Signature
T mix(T start, T end, T t)
How It Works
The mix function takes three arguments: start, end, and t, where start and end are the values to interpolate between, and t is the interpolation factor. The mix function calculates the result as follows:
mix(start, end, t) = start * (1 - t) + end * t
Here's a breakdown of how the mix function works:
- When
tis0, the result is equal tostart. - When
tis1, the result is equal toend. - When
tis between0and1, the result is a linear interpolation betweenstartandend.
Examples
Color interpolation:
vec3 color1 = vec3(1.0, 0.0, 0.0); // red color
vec3 color2 = vec3(0.0, 0.0, 1.0); // blue color
float factor = 0.5; // interpolation factor
// result will be a purple color (halfway between red and blue)
vec3 resultColor = mix(color1, color2, factor);
Interpolating between two positions:
vec3 position1 = vec3(0.0, 0.0, 0.0);
vec3 position2 = vec3(1.0, 1.0, 1.0);
float factor = 0.3;
// result will be a position 30% of the way from position1 to position2
vec3 interpolatedPosition = mix(position1, position2, factor);
HLSL Equivalent
In HLSL, the exact same function exists under the name lerp. It behaves identically to fract in GLSL and supports scalar and vector inputs.