Understanding gl_WorldRayDirectionEXT in GLSL

In hardware-accelerated ray tracing with GLSL, gl_WorldRayDirectionEXT is a built-in input variable that provides the direction vector of the currently evaluated ray in world-space coordinates. Available within stages such as hit shaders (closest-hit and any-hit) and miss shaders, this variable is fundamental for evaluating lighting models, sampling environment maps, and calculating view-dependent shading effects.

Definition and Functionality

In GLSL (via the GL_EXT_ray_tracing extension), gl_WorldRayDirectionEXT is defined as:

in vec3 gl_WorldRayDirectionEXT;

It contains the exact direction vector supplied to the traceRayEXT() call that spawned the traversal. Because this vector is represented in world coordinates, it is unaffected by the instance transformations of any geometries encountered along the ray's path.

Role in Hit Shaders

Within closest-hit (rchit) and any-hit (rahit) shaders, gl_WorldRayDirectionEXT represents the incoming path of the ray relative to the scene:

  • View Vector Calculations: Shaders typically negate gl_WorldRayDirectionEXT (-gl_WorldRayDirectionEXT) to construct the view direction vector (\(V\)) used in standard BRDFs (Bidirectional Reflectance Distribution Functions), specular highlights, and Fresnel equations.
  • Secondary Ray Spawning: When computing reflections or refractions, gl_WorldRayDirectionEXT serves as the incident vector passed to GLSL functions such as reflect() or refract() alongside the world-space surface normal.
  • Contrast with Object Space: While gl_WorldRayDirectionEXT remains in the global coordinate frame, GLSL also provides gl_ObjectRayDirectionEXT, which transforms the direction into the local coordinate system of the hit instance. gl_WorldRayDirectionEXT avoids the need to manually transform vectors back to world space for lighting calculations.

Role in Miss Shaders

In miss shaders (rmiss), which execute when a ray fails to intersect any geometry within the acceleration structure:

  • Environment Mapping: gl_WorldRayDirectionEXT provides the direction required to sample equirectangular or cubemap environment textures (skyboxes).
  • Atmospheric Effects: It allows procedural calculations, such as sun-sky gradients, horizon blending, or distance-based fog, based purely on the direction in which the camera or surface was looking.

Normalization Caveat

The value stored in gl_WorldRayDirectionEXT preserves the exact magnitude and normalization state of the vector originally passed to traceRayEXT(). If the ray was cast using a non-normalized direction, gl_WorldRayDirectionEXT will also be non-normalized. For operations requiring unit vectors—such as dot products for diffuse and specular lighting—the vector should be explicitly normalized using normalize(gl_WorldRayDirectionEXT).