### Basic Renderer Setup and Animation Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Initializes the WebGL renderer, sets up the path tracer with the scene and camera, and starts the animation loop for rendering samples. ```javascript 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(); } ``` -------------------------------- ### Import Three.js and GPU Path Tracer Modules Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Imports necessary components from three.js and three-gpu-pathtracer for rendering and material definition. Ensure these libraries are installed. ```javascript import { MeshPhysicalMaterial, Color, DoubleSide, Mesh, CylinderGeometry, Box3 } from 'three'; import { FogVolumeMaterial } from 'three-gpu-pathtracer'; ``` -------------------------------- ### Get Rendered Samples Count Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Read-only property indicating the total number of samples that have been rendered so far. ```js readonly samples : Number ``` -------------------------------- ### EquirectCamera for 360° Panorama Rendering Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Use `EquirectCamera` to render a full 360° equirectangular panorama. This camera type is path tracing only and requires a render target with a 2:1 aspect ratio. The example shows how to export the rendered panorama. ```javascript import { EquirectCamera, WebGLPathTracer } from 'three-gpu-pathtracer'; const camera = new EquirectCamera(); camera.position.set( 0, 1.6, 0 ); // eye height center const pathTracer = new WebGLPathTracer( renderer ); // Set a wide render target for panorama output (2:1 aspect ratio) renderer.setSize( 4096, 2048 ); await pathTracer.setSceneAsync( scene, camera ); function render() { requestAnimationFrame( render ); pathTracer.renderSample(); if ( pathTracer.samples >= 200 ) { // Export the equirect panorama const buffer = new Uint8Array( 4096 * 2048 * 4 ); renderer.readRenderTargetPixels( pathTracer.target, 0, 0, 4096, 2048, buffer ); console.log( 'Panorama ready' ); } } render(); ``` -------------------------------- ### WebGLPathTracer Initialization and Usage Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Demonstrates how to initialize and use the WebGLPathTracer class, including setting up the renderer, camera, scene, and the animation loop for progressive rendering. ```APIDOC ## WebGLPathTracer ### Description The primary entry point for path tracing in three.js. Wraps a `WebGLRenderer` and manages scene BVH construction, camera setup, lighting, and progressive sample accumulation. Call `setScene()` or `setSceneAsync()` once to initialize, then call `renderSample()` inside your animation loop. ### Initialization and Configuration ```javascript // Set up renderer const renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setPixelRatio( window.devicePixelRatio ); document.body.appendChild( renderer.domElement ); // Create path tracer const pathTracer = new WebGLPathTracer( renderer ); pathTracer.bounces = 10; // max ray bounces pathTracer.transmissiveBounces = 5; // extra bounces through glass pathTracer.filterGlossyFactor = 0.5; // reduce fireflies from caustics pathTracer.renderScale = 1.0; // render at full resolution pathTracer.tiles.set( 3, 3 ); // tile rendering for responsiveness pathTracer.dynamicLowRes = true; // show low-res preview while rendering pathTracer.minSamples = 5; // samples before showing result pathTracer.fadeDuration = 300; // ms to fade in path traced result pathTracer.multipleImportanceSampling = true; pathTracer.setBVHWorker( new ParallelMeshBVHWorker() ); // async BVH build ``` ### Scene and Camera Setup ```javascript // Camera const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.025, 500 ); camera.position.set( 0, 2, 10 ); // Controls – reset path tracer on camera move const controls = new OrbitControls( camera, renderer.domElement ); controls.addEventListener( 'change', () => pathTracer.updateCamera() ); // Load scene and environment const scene = new THREE.Scene(); const envTexture = await new HDRLoader().loadAsync( 'env.hdr' ); envTexture.mapping = THREE.EquirectangularReflectionMapping; scene.environment = envTexture; scene.background = envTexture; scene.backgroundBlurriness = 0.05; const gltf = await new GLTFLoader().loadAsync( 'model.glb' ); scene.add( gltf.scene ); // Initialize (builds BVH asynchronously) await pathTracer.setSceneAsync( scene, camera, { onProgress: v => console.log( `BVH build: ${ ( v * 100 ).toFixed( 0 ) }%` ), } ); ``` ### Animation Loop ```javascript // Animation loop function animate() { requestAnimationFrame( animate ); pathTracer.renderSample(); // accumulates one sample console.log( `Samples: ${ pathTracer.samples }` ); } animate(); // Resize handling window.addEventListener( 'resize', () => { renderer.setSize( window.innerWidth, window.innerHeight ); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); pathTracer.updateCamera(); } ); ``` ### Methods - **`constructor(renderer)`**: Initializes the `WebGLPathTracer` with a `THREE.WebGLRenderer` instance. - **`setScene(scene, camera)`**: Sets the scene and camera for path tracing. Builds the BVH synchronously. - **`setSceneAsync(scene, camera, options)`**: Sets the scene and camera for path tracing asynchronously. Builds the BVH in a worker thread. `options` can include an `onProgress` callback. - **`renderSample()`**: Renders one sample per pixel, accumulating toward a noise-free result. Call this in your animation loop. - **`updateCamera()`**: Updates the camera parameters for the path tracer. Call this when the camera or controls change. ### Properties - **`bounces`** (number): Maximum number of ray bounces. - **`transmissiveBounces`** (number): Number of additional bounces for transmissive materials. - **`filterGlossyFactor`** (number): Factor to reduce fireflies from caustics. - **`renderScale`** (number): Scale at which to render the scene (e.g., 1.0 for full resolution). - **`tiles`** (`THREE.Vector2`): Dimensions for tiled rendering. - **`dynamicLowRes`** (boolean): Enables dynamic low-resolution preview while rendering. - **`minSamples`** (number): Minimum samples required before showing the result. - **`fadeDuration`** (number): Duration in milliseconds to fade in the path-traced result. - **`multipleImportanceSampling`** (boolean): Enables multiple importance sampling. - **`samples`** (number): Current number of samples accumulated per pixel. ### BVH Worker - **`setBVHWorker(worker)`**: Sets a WebGL worker for asynchronous BVH construction. ``` -------------------------------- ### Initialize and Render with WebGLPathTracer Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Set up the WebGLPathTracer by configuring its properties, loading scene geometry and environment maps, and then calling renderSample() in an animation loop. Ensure the BVH worker is set for asynchronous BVH building. ```javascript import * as THREE from 'three'; import { WebGLPathTracer } from 'three-gpu-pathtracer'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { ParallelMeshBVHWorker } from 'three-mesh-bvh/worker'; // Set up renderer const renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setPixelRatio( window.devicePixelRatio ); document.body.appendChild( renderer.domElement ); // Create path tracer const pathTracer = new WebGLPathTracer( renderer ); pathTracer.bounces = 10; // max ray bounces pathTracer.transmissiveBounces = 5; // extra bounces through glass pathTracer.filterGlossyFactor = 0.5; // reduce fireflies from caustics pathTracer.renderScale = 1.0; // render at full resolution pathTracer.tiles.set( 3, 3 ); // tile rendering for responsiveness pathTracer.dynamicLowRes = true; // show low-res preview while rendering pathTracer.minSamples = 5; // samples before showing result pathTracer.fadeDuration = 300; // ms to fade in path traced result pathTracer.multipleImportanceSampling = true; pathTracer.setBVHWorker( new ParallelMeshBVHWorker() ); // async BVH build // Camera const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.025, 500 ); camera.position.set( 0, 2, 10 ); // Controls – reset path tracer on camera move const controls = new OrbitControls( camera, renderer.domElement ); controls.addEventListener( 'change', () => pathTracer.updateCamera() ); // Load scene and environment const scene = new THREE.Scene(); const envTexture = await new HDRLoader().loadAsync( 'env.hdr' ); envTexture.mapping = THREE.EquirectangularReflectionMapping; scene.environment = envTexture; scene.background = envTexture; scene.backgroundBlurriness = 0.05; const gltf = await new GLTFLoader().loadAsync( 'model.glb' ); scene.add( gltf.scene ); // Initialize (builds BVH asynchronously) await pathTracer.setSceneAsync( scene, camera, { onProgress: v => console.log( `BVH build: ${ ( v * 100 ).toFixed( 0 ) }%` ), } ); // Animation loop function animate() { requestAnimationFrame( animate ); pathTracer.renderSample(); // accumulates one sample console.log( `Samples: ${ pathTracer.samples }` ); } animate(); // Resize handling window.addEventListener( 'resize', () => { renderer.setSize( window.innerWidth, window.innerHeight ); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); pathTracer.updateCamera(); } ); ``` -------------------------------- ### Initialize Path Tracer with setScene / setSceneAsync Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Use `setScene` for synchronous initialization or `setSceneAsync` with a web worker for non-blocking BVH construction. Call `updateCamera`, `updateMaterials`, `updateLights`, or `updateEnvironment` for incremental scene changes. ```javascript // Synchronous – blocks the browser during BVH construction pathTracer.setScene( scene, camera ); ``` ```javascript // Asynchronous – non-blocking BVH build with progress callback await pathTracer.setSceneAsync( scene, camera, { onProgress: progress => { loadingBar.style.width = `${ progress * 100 }%`; }, } ); ``` ```javascript // Incremental updates after initial setScene – much cheaper than full rebuild controls.addEventListener( 'change', () => pathTracer.updateCamera() ); ``` ```javascript // Call when material properties change (roughness, color, etc.) mesh.material.roughness = 0.2; pathTracer.updateMaterials(); ``` ```javascript // Call when lights are added/removed or their properties change spotLight.intensity = 200; pathTracer.updateLights(); ``` ```javascript // Call when scene.environment or scene.background changes scene.environment = newEnvMap; pathTracer.updateEnvironment(); ``` -------------------------------- ### Get Path Traced Render Target Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Read-only property providing access to the WebGLRenderTarget used for path tracing. This target may change with each `renderSample` call. ```js readonly target : WebGLRenderTarget ``` -------------------------------- ### Load and Configure 'Crab Sculpture' Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a GLB model and applies custom material properties, including floor color and gradient, and sets the number of light bounces. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/threedscans/Crab.glb', rotation: [ - 2 * Math.PI / 4, 0, 0 ], credit: 'Model courtesy of threedscans.com.', bounces: 15, floorColor: '#eeeeee', floorRoughness: 1.0, floorMetalness: 0.0, gradientTop: '#eeeeee', gradientBot: '#eeeeee', postProcess( model ) { let mat = new MeshPhysicalMaterial( { roughness: 0.05, transmission: 1, ior: 1.2, attenuationDistance: 0.06, attenuationColor: 0x46dfea } ) model.traverse( c => { if ( c.material ) c.material = mat; } ); } } ``` -------------------------------- ### Apply DenoiseMaterial for Post-Processing Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Initialize a DenoiseMaterial with parameters for smoothing and edge sharpening. Apply it as a full-screen quad after rendering a path tracing sample to reduce noise. Adjust material properties based on sample count for optimal results. ```javascript import { DenoiseMaterial, WebGLPathTracer } from 'three-gpu-pathtracer'; import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js'; const pathTracer = new WebGLPathTracer( renderer ); await pathTracer.setSceneAsync( scene, camera ); // Create a full-screen denoising quad const denoiseMaterial = new DenoiseMaterial( { sigma: 5.0, // standard deviation — larger = more smoothing kSigma: 1.0, // radius multiplier: radius = kSigma * sigma threshold: 0.03, // edge sharpening threshold — higher = smoother edges } ); const denoiseQuad = new FullScreenQuad( denoiseMaterial ); function animate() { requestAnimationFrame( animate ); // Render a path tracing sample pathTracer.renderToCanvas = false; // we'll composite manually pathTracer.renderSample(); // Apply denoiser as final pass denoiseMaterial.map = pathTracer.target.texture; const autoClear = renderer.autoClear; renderer.autoClear = false; renderer.setRenderTarget( null ); denoiseQuad.render( renderer ); renderer.autoClear = autoClear; } animate(); // Adjust denoiser strength based on sample count // (less denoising needed as samples accumulate) if ( pathTracer.samples > 50 ) { denoiseMaterial.sigma = 1.5; denoiseMaterial.threshold = 0.01; } // Cleanup denoiseQuad.dispose(); denoiseMaterial.dispose(); ``` -------------------------------- ### Create and configure a PhysicalSpotLight with IES profile Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Use PhysicalSpotLight for realistic lighting with soft shadows and IES photometric profiles. Load IES profiles using IESLoader and assign them to the `iesMap` property. Remember to call `pathTracer.updateLights()` after changing light properties. ```javascript import { PhysicalSpotLight, WebGLPathTracer } from 'three-gpu-pathtracer'; import { IESLoader } from 'three/examples/jsm/loaders/IESLoader.js'; const iesTexture = await new IESLoader().loadAsync( 'profile.ies' ); const spotLight = new PhysicalSpotLight( 0xffffff, 500 ); // color, intensity spotLight.position.set( 0, 5, 0 ); spotLight.angle = Math.PI / 6; spotLight.penumbra = 0.2; spotLight.decay = 2; // Soft area shadow (increase to soften shadows) spotLight.radius = 0.3; // IES profile texture for realistic real-world light distribution spotLight.iesMap = iesTexture; scene.add( spotLight ); scene.add( spotLight.target ); const pathTracer = new WebGLPathTracer( renderer ); await pathTracer.setSceneAsync( scene, camera ); // Update after changing light properties spotLight.intensity = 800; pathTracer.updateLights(); ``` -------------------------------- ### .renderSample Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Renders a single sample to the path tracer target. If `renderToCanvas` is enabled, the sample will also be rendered to the canvas. ```APIDOC ## .renderSample ### Description Render a single sample to the path tracer target. If `renderToCanvas` is true then the image is rendered to the canvas. ### Method void ``` -------------------------------- ### Load and Configure 'Elbow Crab Sculpture' Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a GLB model and applies a custom physical material with specific color, roughness, and transmission settings. Includes a post-processing step to modify materials. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/threedscans/Elbow_Crab.glb', rotation: [ 2.5 * Math.PI / 4, Math.PI, 0 ], credit: 'Model courtesy of threedscans.com.', bounces: 15, floorColor: '#eeeeee', floorRoughness: 1.0, floorMetalness: 0.0, gradientTop: '#eeeeee', gradientBot: '#eeeeee', postProcess( model ) { let mat = new MeshPhysicalMaterial( { color: 0xcc8888, roughness: 0.25, transmission: 1, ior: 1.5, side: DoubleSide, } ) model.traverse( c => { if ( c.material ) c.material = mat; } ); } } ``` -------------------------------- ### Load 'Low Poly Rocket' Model Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a GLB model with a specified rotation and credit information. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/lowpoly-space/space_exploration.glb', credit: 'Model by "The Sinking Sun" on Sketchfab', rotation: [ 0, - Math.PI / 3, 0.0 ], } ``` -------------------------------- ### .renderDelay Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Specifies the delay in milliseconds before rendering samples after the path tracer has been reset. ```APIDOC ## .renderDelay ### Description Number of milliseconds to delay rendering samples after the path tracer has been reset. ### Parameters - **renderDelay** (Number) - Default: 100 ``` -------------------------------- ### Render Single Sample Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Renders a single sample to the path tracer target. If `renderToCanvas` is enabled, the result is automatically displayed on the canvas. ```js renderSample() : void ``` -------------------------------- ### Configure Minimum Samples Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Set the minimum number of samples to render before displaying the scene on the canvas. Ensures a basic level of quality before visual feedback. ```js minSamples = 5 : Number ``` -------------------------------- ### .reset Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Restarts the rendering process. ```APIDOC ## .reset ### Description Restart the rendering. ### Method void ``` -------------------------------- ### Load 'Botanists Greenhouse' Model Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a glTF model from a URL, including credit information. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/botanists-greenhouse/scene.gltf', credit: 'Model by "riikkakilpelainen" on Sketchfab.', } ``` -------------------------------- ### Create and Update GradientEquirectTexture Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Instantiate a GradientEquirectTexture with a specified resolution. Modify its top and bottom colors and exponent for gradient transition, then call update(). This texture can be used for scene backgrounds and ambient lighting. ```javascript import { GradientEquirectTexture, WebGLPathTracer } from 'three-gpu-pathtracer'; const gradientMap = new GradientEquirectTexture( 256 ); // resolution (width = height) gradientMap.topColor.set( 0x87ceeb ); // sky blue gradientMap.bottomColor.set( 0x2d4a22 ); // dark green gradientMap.exponent = 3; // higher = harder gradient transition gradientMap.update(); // must call update() after changing colors scene.background = gradientMap; scene.environment = gradientMap; // also use as ambient lighting const pathTracer = new WebGLPathTracer( renderer ); await pathTracer.setSceneAsync( scene, camera ); // Change background color at runtime gradientMap.topColor.set( 0xff8c00 ); // sunset orange gradientMap.bottomColor.set( 0x1a1a2e ); gradientMap.update(); scene.background = gradientMap; pathTracer.updateEnvironment(); ``` -------------------------------- ### Define Model List for Path Tracing Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Configuration object mapping model names to their URLs and optional post-processing functions. Use this to load and customize models for rendering. ```javascript window.MODEL_LIST = { 'M2020 Rover': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/nasa-m2020/Perseverance.glb', credit: 'Model credit NASA / JPL-Caltech', }, 'M2020 Helicopter': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/nasa-m2020/Ingenuity.glb', credit: 'Model credit NASA / JPL-Caltech', }, 'Stalenhag Winter': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/colourdrafts/scene.glb', credit: 'Model by "ganzhugav" on Sketchfab', bounces: 3, postProcess( model ) { const box = new Box3(); box.setFromObject( model ); const fog = new Mesh( new CylinderGeometry( 0.5, 0.5, 1, 20 ), new FogVolumeMaterial( { color: 0xaaaaaa, density: 1, } ) ); fog.scale.subVectors( box.max, box.min ); fog.scale.x += 0.1; fog.scale.y += 0.01; fog.scale.z += 0.1; fog.scale.x = fog.scale.z = Math.max( fog.scale.x, fog.scale.z ); box.getCenter( fog.position ); fog.position.y += 0.02; model.traverse( c => { if ( c.material && c.material.emissive.r < 0.1 ) { c.material.emissive.set( 0 ); } } ); model.add( fog ); } }, 'Gelatinous Cube': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/gelatinous-cube/scene.gltf', credit: 'Model by "glenatron" on Sketchfab.', rotation: [ 0, - Math.PI / 8, 0.0 ], opacityToTransmission: true, bounces: 8, postProcess( model ) { const toRemove = [] model.traverse( c => { if ( c.material ) { if ( c.material instanceof MeshPhysicalMaterial ) { const material = c.material; material.metalness = 0.0; material.ior = 1.2; material.map = null; c.geometry.computeVertexNormals(); } else if ( c.material.opacity < 1.0 ) { toRemove.push( c ); } } } ); toRemove.forEach( c => { c.parent.remove( c ); } ); } }, 'Octopus Tea': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/octopus-tea/scene.gltf', credit: 'Model by "AzTiZ" on Sketchfab.', opacityToTransmission: true, bounces: 8, postProcess( model ) { const toRemove = [] model.updateMatrixWorld(); model.traverse( c => { if ( c.material ) { c.material.emissiveIntensity = 0; if ( c.material instanceof MeshPhysicalMaterial ) { const material = c.material; material.metalness = 0.0; if ( material.transmission === 1.0 ) { material.roughness = 0.0; material.metalness = 0.0; // 29 === glass // 27 === liquid top // 23 === liquid if ( c.name.includes( '29' ) ) { material.ior = 1.52; material.color.set( 0xffffff ); } else { material.ior = 1.2; } } } else if ( c.material.opacity < 1.0 ) { toRemove.push( c ); } } } ); toRemove.forEach( c => { c.parent.remove( c ); } ); } }, 'Scifi Toad': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/scifi-toad/scene.gltf', credit: 'Model by "YuryTheCreator" on Sketchfab.', opacityToTransmission: true, bounces: 8, postProcess( model ) { model.traverse( c => { if ( c.material && c.material instanceof MeshPhysicalMaterial ) { const material = c.material; material.metalness = 0.0; material.ior = 1.645; material.color.lerp( new Color( 0xffffff ), 0.65 ); } } ); } }, 'Halo Twist Ring': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/ring-twist-halo/scene.glb', credit: 'Model credit NASA / JPL-Caltech', opacityToTransmission: true, bounces: 15, postProcess( model ) { model.traverse( c => { if ( c.material ) { if ( c.material instanceof MeshPhysicalMaterial ) { if ( c.material.transmission === 1.0 ) { const material = c.material; material.metalness = 0.0; material.ior = 1.8; material.color.set( 0xffffff ); } } } } ); } }, 'Damaged Helmet': { url: 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf', credit: 'glTF Sample Model.', }, 'Flight Helmet': { url: 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/FlightHelmet/glTF/FlightHelmet.gltf', credit: 'glTF Sample Model.', }, 'Statue': { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-dat' } } ``` -------------------------------- ### WebGLPathTracer.setScene / setSceneAsync Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Initializes or rebuilds the path tracer for a given scene and camera. `setScene()` is synchronous, while `setSceneAsync()` uses a web worker for non-blocking BVH construction. Incremental updates can be performed using `updateCamera()`, `updateMaterials()`, `updateLights()`, or `updateEnvironment()`. ```APIDOC ## WebGLPathTracer.setScene / setSceneAsync ### Description Initializes or rebuilds the path tracer for a given scene and camera. `setScene()` is synchronous; `setSceneAsync()` uses a web worker to build the BVH off the main thread and returns a Promise. Must be called again when geometry changes; use the lighter `updateCamera()`, `updateMaterials()`, `updateLights()`, or `updateEnvironment()` for incremental updates. ### Synchronous Usage ```js pathTracer.setScene( scene, camera ); ``` ### Asynchronous Usage ```js await pathTracer.setSceneAsync( scene, camera, { onProgress: progress => { loadingBar.style.width = `${ progress * 100 }%`; }, } ); ``` ### Incremental Updates ```js // Update camera position or orientation controls.addEventListener( 'change', () => pathTracer.updateCamera() ); // Update material properties (roughness, color, etc.) mesh.material.roughness = 0.2; pathTracer.updateMaterials(); // Update lights (added/removed or property changes) spotLight.intensity = 200; pathTracer.updateLights(); // Update environment or background scene.environment = newEnvMap; pathTracer.updateEnvironment(); ``` ``` -------------------------------- ### Create and configure a FogVolumeMaterial Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Use FogVolumeMaterial on mesh geometry to create volumetric fog. Adjust `density` for fog thickness and `color` for scattering. Volumetric fog increases render time due to additional ray bounces; increase `pathTracer.bounces` for accuracy. Call `pathTracer.updateMaterials()` after changing material properties. ```javascript import { FogVolumeMaterial, PhysicalSpotLight, WebGLPathTracer } from 'three-gpu-pathtracer'; import * as THREE from 'three'; // Create a box-shaped fog volume const fogMaterial = new FogVolumeMaterial(); fogMaterial.color.set( 0xeeeeee ); // scattering color fogMaterial.density = 0.01; // particles per unit — increase for thicker fog fogMaterial.emissive.set( 0x000000 ); fogMaterial.emissiveIntensity = 0; const fogMesh = new THREE.Mesh( new THREE.BoxGeometry( 10, 5, 10 ), fogMaterial ); scene.add( fogMesh ); // A spot light through fog produces dramatic volumetric beams const spotLight = new PhysicalSpotLight( 0xffffff, 800 ); spotLight.position.set( 0, 4.5, 0 ); spotLight.angle = Math.PI / 8; spotLight.penumbra = 0.1; spotLight.radius = 0.1; scene.add( spotLight ); const pathTracer = new WebGLPathTracer( renderer ); pathTracer.bounces = 10; // more bounces needed for accurate volumetric lighting await pathTracer.setSceneAsync( scene, camera ); // Adjust fog density at runtime fogMaterial.density = 0.025; pathTracer.updateMaterials(); ``` -------------------------------- ### .samples Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Read-only property indicating the total number of samples that have been rendered. ```APIDOC ## .samples ### Description The number of samples that have been rendered. ### Returns - **samples** (Number) ``` -------------------------------- ### Load 'Botanists Study' Model Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a glTF model from a URL, including credit information. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/botanists-study/scene.gltf', credit: 'Model by "riikkakilpelainen" on Sketchfab.', } ``` -------------------------------- ### Material Base Set Define Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Sets or deletes a preprocessor define for a material. Updates `Material.needsUpdate` if the define changes. ```javascript setDefine( name : string, value = undefined : any ) : void ``` -------------------------------- ### Create ProceduralEquirectTexture with Generation Callback Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Extend ProceduralEquirectTexture and define a generationCallback to procedurally generate texture pixels based on spherical coordinates, UV, and pixel coordinates. Call update() to rasterize the callback into the texture. ```javascript import { ProceduralEquirectTexture } from 'three-gpu-pathtracer'; import * as THREE from 'three'; const proceduralEnv = new ProceduralEquirectTexture( 1024, 512 ); // generationCallback receives: // polar – THREE.Spherical (theta, phi, radius) // uv – THREE.Vector2 in [0,1] // coord – THREE.Vector2 pixel dimensions // color – THREE.Color to write output into proceduralEnv.generationCallback = ( polar, uv, coord, color ) => { const elevation = Math.cos( polar.phi ); // 1 at top, -1 at bottom if ( elevation > 0.05 ) { // sky color.setRGB( 0.4 + elevation * 0.4, 0.6 + elevation * 0.3, 1.0 ); } else if ( elevation > - 0.05 ) { // horizon glow color.setRGB( 1.0, 0.6, 0.3 ); } else { // ground color.setRGB( 0.15, 0.12, 0.08 ); } }; proceduralEnv.update(); // rasterize the callback into the texture scene.environment = proceduralEnv; scene.background = proceduralEnv; pathTracer.updateEnvironment(); ``` -------------------------------- ### .dispose Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Releases the assets used by the path tracer. Note that materials and textures must be disposed of separately. ```APIDOC ## .dispose ### Description Dispose the path tracer assets. Any materials or textures used must be disposed separately. ### Method void ``` -------------------------------- ### Set Scene and Camera Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Configures the scene and camera for rendering. Must be re-invoked if the camera, scene geometry, or materials change. This is a relatively expensive operation; prefer update functions when possible. ```js setScene( scene : Scene, camera : Camera ) : void ``` -------------------------------- ### Reset Rendering Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Restarts the rendering process from the beginning. Clears previous samples and begins new ones. ```js reset() : void ``` -------------------------------- ### .tiles Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Sets the number of tiles for rendering on the x and y axes, which can improve responsiveness for high-resolution targets. ```APIDOC ## .tiles ### Description Number of tiles on x and y to render to. Can be used to improve the responsiveness of a page while still rendering a high resolution target. ### Parameters - **tiles** (Vector2) - Default: ( 3, 3 ) ``` -------------------------------- ### PhysicalCamera.fStop Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Configures the f-stop value of the camera, which implicitly updates the `bokehSize` field. ```APIDOC ## PhysicalCamera.fStop ### Description The fstop value of the camera. If this is changed then the `bokehSize` field is implicitly updated. ### Parameters - **fStop** (Number) - Default: 1.4 ``` -------------------------------- ### Configure Render Tiles Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Define the number of tiles on the x and y axes for rendering. This can improve page responsiveness during high-resolution rendering. ```js tiles = ( 3, 3 ) : Vector2 ``` -------------------------------- ### Process Lego Model Names and Populate MODEL_LIST Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/lego.html Iterates through an array of model names, cleans them by removing prefixes and extensions, and populates a MODEL_LIST object. If a cleaned name is not already in MODEL_LIST, it's added with default properties. This is useful for dynamically loading and configuring 3D models. ```javascript const modelNames = [ 'Ice Station Odyssey.mpd', '70814 - Emmets Constructo-Mech.mpd', '70816 - Bennys Spaceship Spa\_kOdSy6E.mpd', '7131-1 - Anakin\'s Podracer.mpd', '7150-1 - TIE Fighter & Y-wing.mpd', '7181 - TIE Interceptor - UCS.mpd', '7191 - X-wing Fighter - UCS.mpd', '7326-1 - Rise of the Sphinx.mpd', '7327-1 - Scorpion Pyramid.mpd', '7410 - Jungle River.mpd', '75053-1 - The Ghost.mpd', '75060 - Slave I.mpd', '75144 - Snowspeeder.mpd', '7784 - The Batmobile Ult\_V1hXfMw.mpd', '928-1 - Galaxy Explorer.mpd', '9476-1 - The Orc Forge.mpd', // From Eurobricks forum post. // Commented items do not load or are uninteresting // '10029 - Lunar Lander.mpd', // '6919 - Planetary Prowler.mpd', // '21109 - Exo Suit.mpd', // '75827 - GHOSTBUSTERS HQ .mpd', // '1788 - Treasure Chest.mpd', // '6264 - Forbidden Cove.mpd', // '6246 - Crocodile Cage.mpd', // '6278 6292 - Enchanted Island.mpd', // '6256 - Island Catamaran.mpd' '6907 - Sonic Stinger.mpd', '10228 - HAUNTED HOUSE.mpd', '10252 - Volkswagen Beetle.mpd', '6969 - Celestial Stinger.mpd', '21103 - The DeLorean time machine.mpd', '6977 - Arachnoid Atar Base.mpd', '6905 - Biwing Blaster.mpd', ]; const MODEL_LIST = {}; modelNames.forEach( name => { const cleanedName = name.replace( /.+?\s-\s/, '' ).replace( /\.mpd$/, '' ); if ( ! ( cleanedName in MODEL_LIST ) ) { MODEL_LIST[ cleanedName ] = { opacityToTransmission: true, ior: 1.4, url: `https://raw.githubusercontent.com/gkjohnson/ldraw-parts-library/master/models/${ name }`, }; } } ); ``` -------------------------------- ### Configure Render Delay Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Set the delay in milliseconds before rendering samples after the path tracer is reset. Useful for controlling the timing of render updates. ```js renderDelay = 100 : Number ``` -------------------------------- ### .minSamples Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Sets the minimum number of samples to render before the scene is displayed on the canvas. ```APIDOC ## .minSamples ### Description How many samples to render before displaying to the canvas. ### Parameters - **minSamples** (Number) - Default: 5 ``` -------------------------------- ### Load 'Imaginary Friend Room' Model Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a GLTF model from a URL, including credit information. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/imaginary-friend-room/scene.glb', credit: 'Model by "Iman Aliakbar" on Sketchfab.', } ``` -------------------------------- ### DenoiseMaterial Source: https://context7.com/gkjohnson/three-gpu-pathtracer/llms.txt Applies a full-screen denoising shader based on the `glslSmartDeNoise` algorithm as a post-processing pass. It reduces noise in renders, includes tonemapping, and handles color space conversion. Denoising strength can be adjusted dynamically. ```APIDOC ## DenoiseMaterial A full-screen denoising shader material based on the `glslSmartDeNoise` algorithm. Apply it as a final post-process pass to reduce noise in under-sampled renders. Includes tonemapping and color space conversion. ```js import { DenoiseMaterial, WebGLPathTracer } from 'three-gpu-pathtracer'; import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js'; const pathTracer = new WebGLPathTracer( renderer ); await pathTracer.setSceneAsync( scene, camera ); // Create a full-screen denoising quad const denoiseMaterial = new DenoiseMaterial( { sigma: 5.0, // standard deviation — larger = more smoothing kSigma: 1.0, // radius multiplier: radius = kSigma * sigma threshold: 0.03, // edge sharpening threshold — higher = smoother edges } ); const denoiseQuad = new FullScreenQuad( denoiseMaterial ); function animate() { requestAnimationFrame( animate ); // Render a path tracing sample pathTracer.renderToCanvas = false; // we'll composite manually pathTracer.renderSample(); // Apply denoiser as final pass denoiseMaterial.map = pathTracer.target.texture; const autoClear = renderer.autoClear; renderer.autoClear = false; renderer.setRenderTarget( null ); denoiseQuad.render( renderer ); renderer.autoClear = autoClear; } animate(); // Adjust denoiser strength based on sample count // (less denoising needed as samples accumulate) if ( pathTracer.samples > 50 ) { denoiseMaterial.sigma = 1.5; denoiseMaterial.threshold = 0.01; } // Cleanup denoiseQuad.dispose(); denoiseMaterial.dispose(); ``` ``` -------------------------------- ### Configure Bounces Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Set the maximum number of light bounces for ray tracing. This affects the realism and computational cost of the render. ```js bounces = 10 : Number ``` -------------------------------- ### Denoise Material Uniforms Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Uniforms for the DenoiseMaterial, based on glslSmartDeNoise. Includes parameters for blur radius, sharpening threshold, and color space conversions. ```javascript { // sigma - sigma Standard Deviation // kSigma - sigma coefficient // kSigma * sigma = radius of the circular kernel sigma = 5.0 : Number, kSigma = 1.0 : Number, // edge sharpening threshold threshold = 0.03 : Number, } ``` -------------------------------- ### .updateLights Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Updates the lights utilized in path tracing. This must be called if lights are added, removed, or their properties are altered. ```APIDOC ## .updateLights ### Description Updates lights used in path tracing. Must be called if any lights are added or removed or properties change. ### Method void ``` -------------------------------- ### .updateEnvironment Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Updates lighting derived from the scene's environment and background settings. This must be called if any associated scene settings are modified. ```APIDOC ## .updateEnvironment ### Description Updates lighting from the scene environment and background properties. Must be called if any associated scene settings change on the set scene object. ### Method void ``` -------------------------------- ### Load 'Japanese Bridge Garden' Model Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/example/index.html Loads a GLTF model from a URL, including credit information. ```javascript { url: 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/japanese-bridge-garden/scene.glb', credit: 'Model by "kristenlee" on Sketchfab.', } ``` -------------------------------- ### .setScene Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Sets the scene and camera for rendering. This method must be called again if the camera, scene geometry, or materials are modified. ```APIDOC ## .setScene ### Description Sets the scene and camera to render. Must be called again when the camera object changes, the geometry in the scene changes, or new materials are assigned. While only changed data is updated it is still a relatively expensive function. Prefer to use the other "update" functions where possible. ### Parameters - **scene** (Scene) - Description: The scene object to render. - **camera** (Camera) - Description: The camera to render from. ``` -------------------------------- ### .target Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Read-only property providing access to the path traced render target, which may change with each `renderSample` call. ```APIDOC ## .target ### Description The path traced render target. This potentially changes every call to `renderSample`. ### Returns - **target** (WebGLRenderTarget) ``` -------------------------------- ### Set Scene Asynchronously Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Asynchronously sets the scene and camera for rendering. Requires `setBVHWorker` to be called first. Supports progress callbacks. ```js setSceneAsync( scene : Scene, camera : Camera, options = { onProgress = null : value => void, } : Object ) : void ``` -------------------------------- ### .lowResScale Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Defines the scaling factor for the low-resolution pass when `dynamicLowRes` is enabled. ```APIDOC ## .lowResScale ### Description The scale to render the low resolution pass at. ### Parameters - **lowResScale** (Number) - Default: 0.1 ``` -------------------------------- ### Enable Dynamic Low Resolution Rendering Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Enable or disable rendering an additional low-resolution version of the scene while the full-resolution render is in progress. The scale is determined by `lowResScale`. ```js dynamicLowRes = false : Boolean ``` -------------------------------- ### Configure Render Scale Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Set the scaling factor for the rendered path-traced image. This option is only effective if `synchronizeRenderSize` is enabled. ```js renderScale = 1 : Number ``` -------------------------------- ### PhysicalSpotLight.iesMap Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md The loaded IES texture describing directional light intensity. These can be loaded with the `IESLoader`. ```APIDOC ## PhysicalSpotLight.iesMap ### Description The loaded IES texture describing directional light intensity. These can be loaded with the `IESLoader`. ### Parameters - **iesMap** (Texture) - Optional - The IES texture. ### Default Value `null` ``` -------------------------------- ### .bounces Source: https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/README.md Configures the maximum number of light bounces to trace in the path tracing algorithm. ```APIDOC ## .bounces ### Description Max number of lights bounces to trace. ### Parameters - **bounces** (Number) - Default: 10 ```