three-gpu-pathtracer

repository·main·Indexed 23 days ago

https://github.com/gkjohnson/three-gpu-pathtracer

A path tracing renderer and utilities for three.js built on top of three-mesh-bvh. It uses WebGL 2 to enable high-quality, physically based rendering on the GPU. Key features include the WebGLPathTracer core class, PhysicalCamera for depth of field, PhysicalSpotLight with IES profile support, and specialized materials like FogVolumeMaterial and DenoiseMaterial. It supports MeshStandardMaterial and MeshPhysicalMaterial, and provides utilities for generating blurred environment maps and procedural equirectangular textures.

Tokens
4.8K
Snippets
3
Records
35
Agent score
82%

What's inside three-gpu-pathtracer

  1. Run examples locally

    main

    To run and modify the examples locally, ensure you have Node and NPM installed. You will also need make and a C++ compiler (e.g., build-essential on Debian/Ubuntu) to install dependencies.

    1. Install dependencies: npm install
    2. Start the demos: npm start
    3. Access via: http://localhost:1234/<demo-name.html>
    npm install
    npm start
  2. Extend MeshStandardMaterial for Path Tracing

    main

    When using WebGLPathTracer, you can augment standard MeshStandardMaterial objects with two specific properties to control how they interact with the path tracer:

    • matte: If true, the object is rendered as completely matte against the environment (useful for compositing).
    • castShadow: If true, the object will cast shadows in the path-traced scene.
  3. Initialize a basic WebGLPathTracer renderer

    main

    To use the path tracer, create a new WebGLPathTracer instance by passing an existing THREE.WebGLRenderer. You must then call .setScene(scene, camera) to associate the path tracer with your Three.js scene and camera. To render, call .renderSample() within your animation loop.

    import * as THREE from 'three';
    import { WebGLPathTracer } from 'three-gpu-pathtracer';
    
    // init scene, camera, controls, etc
    
    renderer = new THREE.WebGLRenderer();
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    
    pathTracer = new WebGLPathTracer( renderer );
    pathTracer.setScene( scene, camera );
    
    animate();
    
    function animate() {
    	requestAnimationFrame( animate );
    	pathTracer.renderSample();
    }
  4. Generate a blurred environment map

    main

    Using a pre-blurred environment map can improve frame convergence time at the cost of sharp reflections. You can use BlurredEnvMapGenerator to create a PMREM blurred environment map from a texture.

    import { BlurredEnvMapGenerator } from 'three-gpu-pathtracer';
    
    // ...
    
    const envMap = await new HDRLoader().setDataType( THREE.FloatType ).loadAsync( envMapUrl );
    const generator = new BlurredEnvMapGenerator( renderer );
    const blurredEnvMap = generator.generate( envMap, 0.35 );
    
    // render!
  5. Extend MaterialBase for custom shaders

    main

    MaterialBase is a convenience class that extends THREE.ShaderMaterial. It automatically maps object properties to shader uniforms, making it easier to manage shader data.

    Use setDefine(name, value) to manage shader #define statements. If value is null or undefined, the define is removed. Changing a define automatically sets Material.needsUpdate to true.

  6. Use PhysicalSpotLight and ShapedAreaLight

    main

    The library provides specialized light classes for path tracing:

    PhysicalSpotLight (extends THREE.SpotLight):

    • radius: Radius of the spotlight surface. Increasing this adds softness to shadows.
    • iesMap: A Texture describing directional light intensity (load via IESLoader).

    ShapedAreaLight (extends THREE.RectAreaLight):

    • isCircular: If true, the area light is rendered as a circle instead of a rectangle.
  7. Use GradientEquirectTexture for sky/environment backgrounds

    main

    The GradientEquirectTexture class creates a gradient texture suitable for equirectangular environment maps.

    Properties:

    • exponent: A Number that controls the gradient curve.
    • topColor: A THREE.Color representing the top of the gradient.
    • bottomColor: A THREE.Color representing the bottom of the gradient.

    Methods:

    • update(): Refreshes the texture.
  8. WebGLPathTracer API Reference

    main

    The WebGLPathTracer is the core class for GPU path tracing.

    Core Methods:

    • setScene(scene, camera): Sets the scene and camera. Call this when geometry, materials, or the camera object changes. It is relatively expensive.
    • setSceneAsync(scene, camera, options): Asynchronous version of setScene. Requires calling setBVHWorker first.
    • updateCamera(): Call when camera parameters change.
    • updateMaterials(): Call when material properties change. Supports additional properties: matte (boolean) and castShadow (boolean).
    • updateEnvironment(): Call when scene environment or background properties change.
    • updateLights(): Call when lights are added, removed, or modified.
    • renderSample(): Renders a single sample. If renderToCanvas is true, it updates the canvas.
    • reset(): Restarts the rendering process.
    • dispose(): Disposes of path tracer assets.
  9. Apply DenoiseMaterial as a final post-processing pass

    main

    DenoiseMaterial is a material based on glslSmartDeNoise designed to be used as the final pass on the screen. It handles tonemapping and color space conversions.

    Uniforms:

    • sigma (Number, default 5.0): The standard deviation.
    • kSigma (Number, default 1.0): The sigma coefficient. The radius of the circular kernel is calculated as kSigma * sigma.
    • threshold (Number, default 0.03): The edge sharpening threshold.
  10. Use FogVolumeMaterial for volumetric fog

    main

    FogVolumeMaterial extends MeshStandardMaterial and is used to render fog-like volumes. It utilizes the standard color, emissive, and emissiveIntensity fields.

    Warning: Fog volumes can significantly increase render times due to the high number of extra light bounces required.

    Key Property:

    • density: Controls the particulate density of the volume.
  11. Check device compatibility with CompatibilityDetector

    main

    Use CompatibilityDetector to verify if the user's device can reliably run the path tracer by checking struct precision and shader compilation.

    Usage:

    1. Instantiate with a WebGLRenderer and a Material to test.
    2. Call .detect() to get the result.
  12. Important limitations and requirements (Gotchas)

    main

    When using three-gpu-pathtracer, be aware of the following constraints:

    • WebGL Version: Requires WebGL2.
    • Textures: All textures must use the same wrap and interpolation flags.
    • Lighting: SpotLights, DirectionalLights, and PointLights are only supported when using MIS (Multiple Importance Sampling).
    • Materials: Only MeshStandardMaterial and MeshPhysicalMaterial are supported.
    • Geometry: Instanced geometry and interleaved buffers are not supported.
    • Emissive: Emissive materials are supported but do not benefit from MIS.