The Skyquad

A skyquad is to a quad what a skybox is to a box. That is, a skyquad is a method of rendering a sky by sending just a single quad down the pipeline. The skyquad as a concept is useful not only in OpenGL, but also in ray tracing, where all we have is a bunch of rays passing through an image plane. In fact, I derived the skyquad from the more general ray equation of my path tracer, so I will start with that first.

The Ray Equation

In a ray tracer, we have a camera and a window into the world - the to-be-rendered-image - and the goal is to determine the ray passing through each of the pixels of the image. This is depicted in the following figure:



  • fovy - the camera's vertical field of view angle.



In addition, we will use the following conventions:



Determining the distance to the image plane

The first step is determining the distance $d$ from the camera to the image plane. The following figure offers a simplified view of the problem for this particular purpose:

From the figure, we can see that:

Solving for $d$ yields:

Deriving the ray equation






The Skyquad in OpenGL

To draw the skyquad, we render a quad directly in NDC space [1], with $z=1$ to force it to appear in the background. For each pixel in the quad, we compute the ray originating from the camera and passing through that pixel. We then use the ray's direction to sample a cubemap texture holding the skybox data, and the fetched texel determines the colour value that we finally assign to that pixel.


  • $(w,h) = (1,1)$


The ray direction vector in NDC space boils down to:




Vertex shader

uniform mat3 Rotation;
uniform float fovy;
uniform float aspect;

layout (location = 0) in vec2 Position;

out vec3 Ray;

vec3 skyRay (vec2 Texcoord)
    float d = 0.5 / tan(fovy/2.0);
    return normalize(vec3((Texcoord.x - 0.5) * aspect, Texcoord.y - 0.5, -d));

void main ()
    Ray = Rotation * skyRay(Position*0.5 + 0.5); // map from [-1,1] to [0,1]
    gl_Position = vec4(Position, 0.0, 1.0);

Fragment shader

uniform samplerCube tex;

in vec3 Ray;

layout (location = 0) out vec4 Colour;

void main ()
    vec3 R = normalize(Ray);

Certainly a lot of maths for such a simple shader! Fortunately they did pay off, and we have a general solution that works for both ray tracing and OpenGL.

And as always, the mandatory screenshot:
