1
$\begingroup$

i'm currently following a tutorial on youtube to get started with computer graphics (shaders) and it contains the following GLSL code:

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy * 2. - 1.; // Normalize & center
    uv.x *= iResolution.x / iResolution.y; // Account for aspect ratio

    float d = length(uv);
    fragColor = vec4(d, d, d, 1.0);
}

However, in the tutorial the two first lines are simplified into:

    vec2 uv = (fragCoord * 2.0 - iResolution.xy) / iResolution.y;

I can't understand how this simplification is made. I think I found the first part by merging both expressions in one:

    vec2 uv = (fragCoord * 2.0 / iResolution.xy - 1.0) * vec2(iResolution.x / iResolution.y, 1.0);

If possible, could anyone provide me with the detailed steps of this simplification please ?

This is a picture of the expected result:enter image description here

Thank you

$\endgroup$

1 Answer 1

1
$\begingroup$

Is this what you are looking for?

fragCoord and iResolution are both of vec2 type and the vector division is element-wise. So the first step get you:

vec2 uv = fragCoord / iResolution.xy * 2. - 1.; // Normalize & center
// uv.x = fragCoord.x / iResolution.x * 2. - 1.

In the second step, we multiply uv.x by iResolution.x / iResolution.y so basically:

uv.x = (fragCoord.x / iResolution.x * 2. - 1.) * iResolution.x / iResolution.y
// this can be simplified to the following since iResolution.x is cancelled out.
uv.x = fragCoord.x / iResolution.y * 2. - iResolution.x / iResolution.y

You will find the uv.x is exactly the x field of:

vec2 uv = (fragCoord * 2.0 - iResolution.xy) / iResolution.y;
// uv.x = (fragCoord.x * 2.0 - iResolution.x) / iResolution.y
// = fragCoord.x / iResolution.y * 2.0 - iResolution.x / iResolution.y;

which is the simplified version in the tutorial.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.