Milkshake.io logo

Lightmapping in ThreeJS

alt text

Three Lightmap Baker is a project demonstrating GPU-accelerated lightmap generation in Three.js. Built using excellent libraries including Three Mesh BVH, Three GPU Pathtracer, and XAtlas-Three, it showcases how to bake realistic lighting directly in the browser.

How it works

  1. Pass all the geometry into XAtlas-Three (UV unwrapping library). This will generate a "UV2" attribute on the geometry.
  2. Render the geometries vertices in the UV2 space. Create two textures (resolution being the lightmap resolution), using the gl_FragColor to encode world position and the normal. This is packing Vec3 data into a texture using the RGB channel.
alt textalt text

Visual reference: Using these textures as the lightmap (using UV2).

  1. These two textures are effectively a 2D array of World Position & Normals covering the entire geometry.
  2. Iterate through each World Position & Normal. Cast rays at each position to calculate incoming light.
alt text

Visual reference: Creating arrows for each world position & the normal

  1. The Three Mesh BVH library helps improve the performance of raycasting, it also allows raycasting on the GPU (this is super fast).
  2. Using A LOT of copy & pasted code from Three GPU Pathtracer to generate light
alt textalt text

Further Reading / Watching