three-gpu-pathtracer 0.0.1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +678 -386
  3. package/build/index.module.js +3166 -1690
  4. package/build/index.module.js.map +1 -1
  5. package/build/index.umd.cjs +3176 -1692
  6. package/build/index.umd.cjs.map +1 -1
  7. package/package.json +60 -57
  8. package/src/core/DynamicPathTracingSceneGenerator.js +106 -0
  9. package/src/core/MaterialReducer.js +256 -256
  10. package/src/core/PathTracingRenderer.js +125 -28
  11. package/src/core/PathTracingSceneGenerator.js +52 -46
  12. package/src/core/PhysicalCamera.js +28 -0
  13. package/src/index.js +25 -21
  14. package/src/materials/AlphaDisplayMaterial.js +48 -0
  15. package/src/materials/AmbientOcclusionMaterial.js +197 -197
  16. package/src/materials/BlendMaterial.js +67 -0
  17. package/src/materials/LambertPathTracingMaterial.js +285 -285
  18. package/src/materials/MaterialBase.js +56 -56
  19. package/src/materials/PhysicalPathTracingMaterial.js +684 -370
  20. package/src/shader/shaderEnvMapSampling.js +67 -0
  21. package/src/shader/shaderGGXFunctions.js +108 -107
  22. package/src/shader/shaderMaterialSampling.js +345 -333
  23. package/src/shader/shaderStructs.js +131 -30
  24. package/src/shader/shaderUtils.js +246 -140
  25. package/src/uniforms/EquirectHdrInfoUniform.js +263 -0
  26. package/src/uniforms/MaterialsTexture.js +251 -0
  27. package/src/uniforms/PhysicalCameraUniform.js +36 -0
  28. package/src/uniforms/RenderTarget2DArray.js +93 -80
  29. package/src/utils/BlurredEnvMapGenerator.js +113 -0
  30. package/src/utils/GeometryPreparationUtils.js +194 -172
  31. package/src/utils/UVUnwrapper.js +101 -101
  32. package/src/workers/PathTracingSceneWorker.js +40 -0
  33. package/src/uniforms/EquirectPdfUniform.js +0 -132
  34. package/src/uniforms/MaterialStructArrayUniform.js +0 -18
  35. package/src/uniforms/MaterialStructUniform.js +0 -94
  36. package/src/viewers/PathTracingViewer.js +0 -259
package/README.md CHANGED
@@ -1,386 +1,678 @@
1
- # three-gpu-pathtracer
2
-
3
- [![lgtm code quality](https://img.shields.io/lgtm/grade/javascript/g/gkjohnson/three-gpu-pathtracer.svg?style=flat-square&label=code-quality)](https://lgtm.com/projects/g/gkjohnson/three-gpu-pathtracer/)
4
- [![build](https://img.shields.io/github/workflow/status/gkjohnson/three-gpu-pathtracer/Node.js%20CI?style=flat-square&label=build)](https://github.com/gkjohnson/three-gpu-pathtracer/actions)
5
-
6
- ![](https://user-images.githubusercontent.com/734200/162287477-96696b18-890b-4c1b-8a73-d662e577cc48.png)
7
-
8
- Path tracing project using [three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh) to accelerate high quality, physically based rendering on the GPU. Features include support for GGX surface model, material information, textures, normal maps, emission, environment maps, tiled rendering, and more!
9
-
10
- _More features and capabilities in progress!_
11
-
12
- # Examples
13
-
14
- [PBR demo here](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/index.html)!
15
-
16
- [Lego demo here](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/lego.html)!
17
-
18
- [Material demo here](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/materialBall.html)!
19
-
20
- [Transmission preset demo here](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/materialBall.html#transmission)!
21
-
22
- [Ambient Occlusion Material demo here](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/aoRender.html)!
23
-
24
- # Use
25
-
26
- ```js
27
- import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
28
- import {
29
- PathTracingSceneGenerator,
30
- PathTracingRenderer,
31
- PhysicalPathTracingMaterial,
32
- } from 'three-gpu-pathtracer';
33
-
34
- // init scene, renderer, camera, controls, etc
35
-
36
- // initialize the path tracing material and renderer
37
- const ptMaterial = new PhysicalPathTracingMaterial();
38
- const ptRenderer = new PathTracingRenderer( renderer );
39
- ptRenderer.camera = camera;
40
- ptRenderer.material = ptMaterial;
41
-
42
- // init quad for rendering to the canvas
43
- const fsQuad = new FullScreenQuad( new THREE.MeshBasicMaterial( {
44
- map: ptRenderer.target.texture,
45
- } ) );
46
-
47
- // initialize the scene and update the material properties with the bvh, materials, etc
48
- const generator = new PathTracingSceneGenerator();
49
- const { bvh, textures, materials } = await generator.generate( scene );
50
-
51
- // update bvh and geometry attribute textures
52
- ptMaterial.bvh.updateFrom( bvh );
53
- ptMaterial.normalAttribute.updateFrom( geometry.attributes.normal );
54
- ptMaterial.tangentAttribute.updateFrom( geometry.attributes.tangent );
55
- ptMaterial.uvAttribute.updateFrom( geometry.attributes.uv );
56
-
57
- // update materials and texture arrays
58
- ptMaterial.materialIndexAttribute.updateFrom( geometry.attributes.materialIndex );
59
- ptMaterial.textures.setTextures( renderer, 2048, 2048, textures );
60
- ptMaterial.materials.updateFrom( materials, textures );
61
- ptMaterial.setDefine( 'MATERIAL_LENGTH', materials.length );
62
-
63
- // set the environment map
64
- const texture = await new RGBELoader().loadAsync( envMapUrl );
65
- const pmremGenerator = new THREE.PMREMGenerator( renderer );
66
- pmremGenerator.compileCubemapShader();
67
-
68
- const envMap = pmremGenerator.fromEquirectangular( texture );
69
- ptRenderer.material.environmentMap = envMap.texture;
70
-
71
- animate();
72
-
73
- // ...
74
-
75
- function animate() {
76
-
77
- // if the camera position changes call "ptRenderer.reset()"
78
-
79
- // update the camera and render one sample
80
- camera.updateMatrixWorld();
81
- ptRenderer.update();
82
-
83
- // copy the current state of the path tracer to canvas to display
84
- renderer.autoClear = false;
85
- fsQuad.material.map = ptRenderer.target.texture;
86
- fsQuad.render( renderer );
87
- renderer.autoClear = true;
88
-
89
- }
90
- ```
91
-
92
- # Exports
93
-
94
- ## PathTracingRenderer
95
-
96
- Utility class for tracking and rendering a path traced scene to a render target.
97
-
98
- ### .samples
99
-
100
- ```js
101
- readonly samples : Number
102
- ```
103
-
104
- Number of samples per pixel that have been rendered to the target.
105
-
106
- ### .target
107
-
108
- ```js
109
- readonly target : WebGLRenderTarget
110
- ```
111
-
112
- The target being rendered to. The size of the target is updated with `setSize` and is initialized to a FloatType texture.
113
-
114
- ### .camera
115
-
116
- ```js
117
- camera = null : Camera
118
- ```
119
-
120
- The camera to render with. The view offset of the camera will be updated every sample to enable anti aliasing.
121
-
122
- ### .material
123
-
124
- ```js
125
- material = null : ShaderMaterial
126
- ```
127
-
128
- The Path Tracing material to render. This is expected to be a full screen quad material that respects the "opacity" field for every pixel so samples can be accumulated over time. The material is also expected to have `cameraWorldMatrix` and `invProjectionMatrix` fields of type `Matrix4`.
129
-
130
- ### .tiles
131
-
132
- ```js
133
- tiles = ( 1, 1 ) : Vector2
134
- ```
135
-
136
- 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.
137
-
138
- ### .stableNoise
139
-
140
- ```js
141
- stableNoise = false
142
- ```
143
-
144
- Whether to reset the random seed to `0` when restarting the render. If true then a consistent random sample pattern will appear when moving the camera, for example.
145
-
146
- ### constructor
147
-
148
- ```js
149
- constructor( renderer : WebGLRenderer )
150
- ```
151
-
152
- ### .setSize
153
-
154
- ```js
155
- setSize( size : Vector2 ) : void
156
- ```
157
-
158
- Sets the size of the target to render to.
159
-
160
- ### .update
161
-
162
- ```js
163
- update()
164
- ```
165
-
166
- Renders a single sample to the target.
167
-
168
- ### .reset
169
-
170
- ```js
171
- reset() : void
172
- ```
173
-
174
- Resets and restarts the render from scratch.
175
-
176
- ## PathTracingSceneGenerator
177
-
178
- Utility class for generating the set of data required for initializing the path tracing material with a bvh, geometry, materials, and textures.
179
-
180
- ### .generate
181
-
182
- ```js
183
- async generate( scene : Object3D ) : {
184
- bvh : MeshBVH,
185
- materials : Array<Material>,
186
- textures : Array<Texture>
187
- }
188
- ```
189
-
190
- Merges the geometry in the given scene with an additional "materialIndex" attribute that references the associated material array. Also produces a set of textures referenced by the scene materials.
191
-
192
- ## MaterialBase
193
-
194
- _extends THREE.ShaderMaterial_
195
-
196
- Convenience base class that adds additional functions and implicitly adds object definitions for all uniforms of the shader to the object.
197
-
198
- ### .setDefine
199
-
200
- ```js
201
- setDefine( name : string, value = undefined : any ) : void
202
- ```
203
-
204
- Sets the define of the given name to the provided value. If the value is set to null or undefined then it is deleted from the defines of the material. If the define changed from the previous value then `Material.needsUpdate` is set to `true`.
205
-
206
- ## PhysicalPathTracingMaterial
207
-
208
- _extends MaterialBase_
209
-
210
- **Uniforms**
211
-
212
- ```js
213
- {
214
- // Geometry and BVH information,
215
- bvh: MeshBVHUniformStruct,
216
- normalAttribute: FloatVertexAttributeTexture,
217
- tangentAttribute: FloatVertexAttributeTexture,
218
- uvAttribute: FloatVertexAttributeTexture,
219
- materialIndexAttribute: UIntVertexAttributeTexture,
220
- materials: MaterialStructArrayUniform,
221
- textures: RenderTarget2DArray,
222
-
223
- // PMREM-processed Environment Map,
224
- environmentMap: Texture,
225
- environmentRotaton: Matrix3,
226
-
227
- // Environment Map information,
228
- environmentBlur: Number,
229
- environmentIntensity: Number,
230
-
231
- // Factor for alleviating bright pixels from rays that hit diffuse surfaces then
232
- // specular surfaces. Setting this higher alleviates fireflies but will remove some
233
- // specular caustics.
234
- filterGlossyFactor: Number,
235
-
236
- // The colors to use for the gradient env lighting when no environment map is provided.
237
- gradientTop: Color,
238
- gradientBottom: Color,
239
-
240
- // The colors to use for the gradient background when enabled.
241
- bgGradientTop: Color,
242
- bgGradientBottom: Color,
243
- }
244
- ```
245
-
246
- **Defines**
247
-
248
- ```js
249
- {
250
- // The number of ray bounces to test. Higher is better quality but slower performance.
251
- BOUNCES = 3 : Number,
252
-
253
- // The number of transparent pixels to allow on top of existing bounces for object transparency.
254
- TRANSPARENT_TRAVERSALS = 5 : Number,
255
-
256
- // Whether to use the "bg" gradient fields to sample for the backround
257
- GRADIENT_BG = 0 : Number
258
-
259
- // The number of materials provided in the "materials" uniform.
260
- MATERIAL_LENGTH : Number,
261
-
262
-
263
- }
264
- ```
265
-
266
- ## RenderTarget2DArray
267
-
268
- _extends WebGLArrayRenderTarget_
269
-
270
- A convenience extension from `WebGLArrayRenderTarget` that affords easily creating a uniform texture array from an array of textures.
271
-
272
- ### .setTextures
273
-
274
- ```js
275
- setTextures(
276
- renderer : WebGLRenderer,
277
- width : Number,
278
- height : Number,
279
- textures : Array<Texture>
280
- ) : void
281
- ```
282
-
283
- Takes the rendering context to updateh the target for, the target dimensions of the texture array, and the array of textures to render into the 2D texture array. Every texture is stretched to the dimensions of the texture array at the same index they are provided in.
284
-
285
- ## MaterialStructArrayUniform
286
-
287
- _extends Array_
288
-
289
- Array of `MaterialStructUniform` definitions for use as a Shader uniform.
290
-
291
- ### .updateFrom
292
-
293
- ```js
294
- updateFrom( materials : Array<Material>, textures : Array<Texture> ) : void
295
- ```
296
-
297
- Updates the value of the uniform to align with the provided set of materials and textures.
298
-
299
- ## MaterialStructUniform
300
-
301
- Struct definiton for representing material information as a uniform. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderStructs.js) for full struct definition information.
302
-
303
- ### .updateFrom
304
-
305
- ```js
306
- updateFrame( material : Material, textures : Array<Texture> ) : void
307
- ```
308
-
309
- Updates the uniform with the information from the passed material. Texture fields are set to the index of the texture in the provided textures array.
310
-
311
- ## Functions
312
-
313
- ### mergeMeshes
314
-
315
- ```js
316
- mergeMeshes( meshes : Array<Mesh> ) : {
317
- materials : Array<Material>,
318
- textures : Array<Textures>,
319
- geometry : BufferGeometry
320
- }
321
- ```
322
-
323
- Merges the set of meshes into a single geometry with a `materialIndex` vertex attribute included on the geometry identifying the associated material in the returned `materials` array.
324
-
325
- ## Shader Chunks
326
-
327
- **shaderMaterialSampling**
328
-
329
- Set of functions for performing material scatter and PDF sampling. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderMaterialSampling.js) for full list of functions.
330
-
331
- **shaderStructs**
332
-
333
- Material struct definition for use with uniforms. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderStructs.js) for full list of functions.
334
-
335
- **shaderUtils**
336
-
337
- Set of randomness and other light transmport utilities for use in a shader. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderUtils.js) for full list of functions.
338
-
339
- # Caveats
340
-
341
- - All textures must use the same wrap and interpolation flags.
342
-
343
- # Screenshots
344
-
345
- ![](./docs/interior-scene-cropped.png)
346
-
347
- <p align="center">
348
- <i>"Interior Scene" model by <a href="https://sketchfab.com/3d-models/interior-scene-45ddbbc4c2dc4f8ca9ed99da9a78326a">Allay Design</a></i>
349
- </p>
350
-
351
- ![](https://user-images.githubusercontent.com/734200/161820794-df0da371-ee5c-4368-9e7b-5e7daf6cf3c7.png)
352
-
353
- <p align="center">
354
- <i>Perseverance Rover model by <a href="https://mars.nasa.gov/resources/25042/mars-perseverance-rover-3d-model/">NASA / JPL-Caltech</a></i>
355
- </p>
356
-
357
- ![](https://user-images.githubusercontent.com/734200/161877900-566652e4-c799-4940-bccb-0c8f4cea5387.png)
358
-
359
- <p align="center">
360
- <i>Gelatinous Cube model by <a href="https://sketchfab.com/3d-models/gelatinous-cube-e08385238f4d4b59b012233a9fbdca21">glenatron</a></i>
361
- </p>
362
-
363
- ![](https://user-images.githubusercontent.com/734200/161822206-c27bf594-d648-4735-868e-4baf4e414802.png)
364
-
365
- ![](https://user-images.githubusercontent.com/734200/161822214-eace4297-03c4-4adc-b472-efe29a862685.png)
366
-
367
- <p align="center">
368
- <i>Lego models courtesy of the <a href="https://omr.ldraw.org/">LDraw Official Model Repository</a></i>
369
- </p>
370
-
371
- ![](https://user-images.githubusercontent.com/734200/161877196-7ae2769e-7e54-4694-9ca8-e8f5219d1c2d.png)
372
-
373
- <p align="center">
374
- <i>Octopus Tea model by <a href="https://sketchfab.com/3d-models/cartoon-octopus-takes-a-tea-bath-107260cf0fd24202a67eb037a6c760a5
375
- ">AzTiZ</a></i>
376
- </p>
377
-
378
- ### Resources
379
-
380
- [Raytracing in One Weekend Book](https://raytracing.github.io/)
381
-
382
- [PBR Book](https://pbr-book.org/)
383
-
384
- [knightcrawler25/GLSL-PathTracer](https://github.com/knightcrawler25/GLSL-PathTracer/)
385
-
386
-
1
+ # three-gpu-pathtracer
2
+
3
+ [![npm version](https://img.shields.io/npm/v/three-gpu-pathtracer.svg?style=flat-square)](https://www.npmjs.com/package/three-gpu-pathtracer)
4
+ [![lgtm code quality](https://img.shields.io/lgtm/grade/javascript/g/gkjohnson/three-gpu-pathtracer.svg?style=flat-square&label=code-quality)](https://lgtm.com/projects/g/gkjohnson/three-gpu-pathtracer/)
5
+ [![build](https://img.shields.io/github/workflow/status/gkjohnson/three-gpu-pathtracer/Node.js%20CI?style=flat-square&label=build)](https://github.com/gkjohnson/three-gpu-pathtracer/actions)
6
+ [![github](https://flat.badgen.net/badge/icon/github?icon=github&label)](https://github.com/gkjohnson/three-gpu-pathtracer/)
7
+ [![twitter](https://flat.badgen.net/twitter/follow/garrettkjohnson)](https://twitter.com/garrettkjohnson)
8
+ [![sponsors](https://img.shields.io/github/sponsors/gkjohnson?style=flat-square&color=1da1f2)](https://github.com/sponsors/gkjohnson/)
9
+
10
+ ![](https://user-images.githubusercontent.com/734200/162287477-96696b18-890b-4c1b-8a73-d662e577cc48.png)
11
+
12
+ Path tracing project using [three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh) and WebGL 2 to accelerate high quality, physically based rendering on the GPU. Features include support for GGX surface model, material information, textures, normal maps, emission, environment maps, tiled rendering, and more!
13
+
14
+ _More features and capabilities in progress!_
15
+
16
+ # Examples
17
+
18
+ **Beauty Demos**
19
+
20
+ [Physically Based Materials](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/index.html)
21
+
22
+ [Lego Models](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/lego.html)
23
+
24
+ [Interior Scene](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/interior.html)
25
+
26
+ [Depth of Field](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/depthOfField.html)
27
+
28
+ **Features**
29
+
30
+ [Skinned Geometry Support](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/skinnedMesh.html)
31
+
32
+ [Morph Target Support](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/skinnedMesh.html#morphtarget)
33
+
34
+ **Test Scenes**
35
+
36
+ [Material Test Orb](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/materialBall.html)
37
+
38
+ [Transmission Preset Orb](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/materialBall.html#transmission)
39
+
40
+ **Light Baking**
41
+
42
+ [Ambient Occlusion Material](https://gkjohnson.github.io/three-gpu-pathtracer/example/bundle/aoRender.html)
43
+
44
+ # Use
45
+
46
+ **Basic Renderer**
47
+
48
+ ```js
49
+ import * as THREE from 'three';
50
+ import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
51
+ import {
52
+ PathTracingSceneGenerator,
53
+ PathTracingRenderer,
54
+ PhysicalPathTracingMaterial,
55
+ } from 'three-gpu-pathtracer';
56
+
57
+ // init scene, renderer, camera, controls, etc
58
+
59
+ // initialize the path tracing material and renderer
60
+ const ptMaterial = new PhysicalPathTracingMaterial();
61
+ const ptRenderer = new PathTracingRenderer( renderer );
62
+ ptRenderer.setSize( window.innerWidth, window.innerHeight );
63
+ ptRenderer.camera = camera;
64
+ ptRenderer.material = ptMaterial;
65
+
66
+ // if rendering transparent background
67
+ ptRenderer.alpha = true;
68
+
69
+ // init quad for rendering to the canvas
70
+ const fsQuad = new FullScreenQuad( new THREE.MeshBasicMaterial( {
71
+ map: ptRenderer.target.texture,
72
+
73
+ // if rendering transparent background
74
+ blending: THREE.CustomBlending,
75
+ } ) );
76
+
77
+ // ensure scene matrices are up to date
78
+ scene.updateMatrixWorld();
79
+
80
+ // initialize the scene and update the material properties with the bvh, materials, etc
81
+ const generator = new PathTracingSceneGenerator();
82
+ const { bvh, textures, materials } = generator.generate( scene );
83
+
84
+ // update bvh and geometry attribute textures
85
+ ptMaterial.bvh.updateFrom( bvh );
86
+ ptMaterial.normalAttribute.updateFrom( geometry.attributes.normal );
87
+ ptMaterial.tangentAttribute.updateFrom( geometry.attributes.tangent );
88
+ ptMaterial.uvAttribute.updateFrom( geometry.attributes.uv );
89
+
90
+ // update materials and texture arrays
91
+ ptMaterial.materialIndexAttribute.updateFrom( geometry.attributes.materialIndex );
92
+ ptMaterial.textures.setTextures( renderer, 2048, 2048, textures );
93
+ ptMaterial.materials.updateFrom( materials, textures );
94
+
95
+ // set the environment map
96
+ const texture = await new RGBELoader().loadAsync( envMapUrl );
97
+ ptRenderer.material.envMapInfo.updateFrom( texture );
98
+
99
+ animate();
100
+
101
+ // ...
102
+
103
+ function animate() {
104
+
105
+ // if the camera position changes call "ptRenderer.reset()"
106
+
107
+ // update the camera and render one sample
108
+ camera.updateMatrixWorld();
109
+ ptRenderer.update();
110
+
111
+ // if using alpha = true then the target texture will change every frame
112
+ // so we must retrieve it before render.
113
+ fsQuad.material.map = ptRenderer.target.texture;
114
+
115
+ // copy the current state of the path tracer to canvas to display
116
+ fsQuad.render( renderer );
117
+
118
+ }
119
+ ```
120
+
121
+ **Blurred Environment Map**
122
+
123
+ Using a pre blurred envioronment map can help improve frame convergence time at the cost of sharp environment reflections. If performance is concern then multiple importance sampling can be disabled and blurred environment map used.
124
+
125
+ ```js
126
+ import { BlurredEnvMapGenerator } from 'three-gpu-pathtracer';
127
+
128
+ // ...
129
+
130
+ const envMap = await new RGBELoader().loadAsync( envMapUrl );
131
+ const generator = new BlurredEnvMapGenerator( renderer );
132
+ const blurredEnvMap = generator.generate( envMap, 0.35 );
133
+
134
+ // render!
135
+
136
+ ```
137
+
138
+ ## Dynamic Scenes
139
+
140
+ Using the dynamic scene generator the same, frequently updated scene can be converted into a single reusable geometry multiple times and BVH refit which greatly improves subsequent scene updates. See `DynamicPathTracingSceneGenerator` docs for more info.
141
+
142
+ ```js
143
+ import { DynamicPathTracingSceneGenerator } from 'three-gpu-pathtracer';
144
+
145
+ // ... initialize scene etc
146
+
147
+ const generator = new DynamicPathTracingSceneGenerator( scene );
148
+ const { bvh, textures, materials } = generator.generate( scene );
149
+
150
+ // ... update path tracer and render
151
+ ```
152
+
153
+ ## Asynchronous Scene Generation
154
+
155
+ _NOTE WebWorker syntax is inconsistently supported across bundlers and sometimes not supported at all so the PathTracingSceneWorker class is not exported from the package root. If needed the code from src/worker can be copied and modified to accomodate a particular build process._
156
+
157
+ ```js
158
+ import { PathTracingSceneWorker } from 'three-gpu-pathtracer/src/workers/PathTracingSceneWorker.js';
159
+
160
+ // ...
161
+
162
+ // initialize the scene and update the material properties with the bvh, materials, etc
163
+ const generator = new PathTracingSceneWorker();
164
+ const { bvh, textures, materials } = await generator.generate( scene );
165
+
166
+ // ...
167
+ ```
168
+
169
+ # Exports
170
+
171
+ ## PathTracingRenderer
172
+
173
+ Utility class for tracking and rendering a path traced scene to a render target.
174
+
175
+ ### .samples
176
+
177
+ ```js
178
+ readonly samples : Number
179
+ ```
180
+
181
+ Number of samples per pixel that have been rendered to the target.
182
+
183
+ ### .target
184
+
185
+ ```js
186
+ readonly target : WebGLRenderTarget
187
+ ```
188
+
189
+ The target being rendered to. The size of the target is updated with `setSize` and is initialized to a FloatType texture.
190
+
191
+ ### .camera
192
+
193
+ ```js
194
+ camera = null : Camera
195
+ ```
196
+
197
+ The camera to render with. The view offset of the camera will be updated every sample to enable anti aliasing.
198
+
199
+ ### .material
200
+
201
+ ```js
202
+ material = null : ShaderMaterial
203
+ ```
204
+
205
+ The Path Tracing material to render. This is expected to be a full screen quad material that respects the "opacity" field for every pixel so samples can be accumulated over time. The material is also expected to have `cameraWorldMatrix` and `invProjectionMatrix` fields of type `Matrix4`.
206
+
207
+ ### .tiles
208
+
209
+ ```js
210
+ tiles = ( 1, 1 ) : Vector2
211
+ ```
212
+
213
+ 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.
214
+
215
+ ### .stableNoise
216
+
217
+ ```js
218
+ stableNoise = false : Boolean
219
+ ```
220
+
221
+ Whether to reset the random seed to `0` when restarting the render. If true then a consistent random sample pattern will appear when moving the camera, for example.
222
+
223
+ ### .alpha
224
+
225
+ ```js
226
+ alpha = false : Boolean
227
+ ```
228
+
229
+ Whether to support rendering scenes with transparent backgrounds. When transparent backgrounds are used two extra render targets are used, custom blending is performed, and PathTracingRenderer.target will change on every completed sample.
230
+
231
+ ### constructor
232
+
233
+ ```js
234
+ constructor( renderer : WebGLRenderer )
235
+ ```
236
+
237
+ ### .setSize
238
+
239
+ ```js
240
+ setSize( size : Vector2 ) : void
241
+ ```
242
+
243
+ Sets the size of the target to render to.
244
+
245
+ ### .update
246
+
247
+ ```js
248
+ update()
249
+ ```
250
+
251
+ Renders a single sample to the target.
252
+
253
+ ### .reset
254
+
255
+ ```js
256
+ reset() : void
257
+ ```
258
+
259
+ Resets and restarts the render from scratch.
260
+
261
+ ## PathTracingSceneGenerator
262
+
263
+ Utility class for generating the set of data required for initializing the path tracing material with a bvh, geometry, materials, and textures.
264
+
265
+ ### .generate
266
+
267
+ ```js
268
+ generate( scene : Object3D, options = {} : Object ) : {
269
+ bvh : MeshBVH,
270
+ materials : Array<Material>,
271
+ textures : Array<Texture>
272
+ }
273
+ ```
274
+
275
+ Merges the geometry in the given scene with an additional "materialIndex" attribute that references the associated material array. Also produces a set of textures referenced by the scene materials.
276
+
277
+ ## PathTracingSceneWorker
278
+
279
+ _extends PathTracingSceneGenerator_
280
+
281
+ See note in [Asyncronous Generation](#asynchronous-generation) use snippet.
282
+
283
+ ### .generate
284
+
285
+ ```js
286
+ async generate( scene : Object3D, options = {} : Object ) : {
287
+ bvh : MeshBVH,
288
+ materials : Array<Material>,
289
+ textures : Array<Texture>
290
+ }
291
+ ```
292
+
293
+ ### .dispose
294
+
295
+ ```js
296
+ dispose() : void
297
+ ```
298
+
299
+ ## PhysicalCamera
300
+
301
+ _extends THREE.PerspectiveCamera_
302
+
303
+ An extension of the three.js PerspectiveCamera with some other parameters associated with depth of field. These parameters otherwise do not affect the camera behavior are are for convenience of use with the PhysicalCameraUniform and pathtracer.
304
+
305
+ ### .focusDistance
306
+
307
+ ```js
308
+ focusDistance = 25 : Number
309
+ ```
310
+
311
+ The distance from the camera in meters that everything is is perfect focus.
312
+
313
+ ### .fStop
314
+
315
+ ```js
316
+ fStop = 1.4 : Number
317
+ ```
318
+
319
+ The fstop value of the camera. If this is changed then the `bokehSize` field is implicitly updated.
320
+
321
+ ### .bokehSize
322
+
323
+ ```js
324
+ bokehSize : Number
325
+ ```
326
+
327
+ The bokeh size as derived from the fStop and focal length in millimeters. If this is set then the fStop is implicitly updated.
328
+
329
+ ### .apertureBlades
330
+
331
+ ```js
332
+ apertureBlades = 0 : Number
333
+ ```
334
+
335
+ The number of sides / blades on the aperture.
336
+
337
+ ### .apertureRotation
338
+
339
+ ```js
340
+ apertureRotation = 0 : Number
341
+ ```
342
+
343
+ The rotation of the aperture shape in radians.
344
+
345
+ ### .anamorphicRatio
346
+
347
+ ```js
348
+ anamorphicRatio = 1 : Number
349
+ ```
350
+
351
+ The anamorphic ratio of the lens. A higher value will stretch the bokeh effect horizontally.
352
+
353
+ ## DynamicPathTracingSceneGenerator
354
+
355
+ A variation of the path tracing scene generator intended for quickly regenerating a scene BVH representation that updates frequently. Ie those with animated objects or animated skinned geometry.
356
+
357
+ In order to quickly update a dynamic scene the same BVH is reused across updates by refitting rather than regenerating. This is significantly faster but also results in a less optimal BVH after significant changes.
358
+
359
+ If geometry or materials are added or removed from the scene then `reset` must be called.
360
+
361
+ ### constructor
362
+
363
+ ```js
364
+ constructor( scene : Object3D )
365
+ ```
366
+
367
+ Takes the scene to convert.
368
+
369
+ ### .generate
370
+
371
+ ```js
372
+ generate() : {
373
+ bvh : MeshBVH,
374
+ materials : Array<Material>,
375
+ textures : Array<Texture>
376
+ }
377
+ ```
378
+
379
+ Generates and refits the bvh to the current scene state. The same bvh, materials, and textures objects are returns after the initial call until `reset` is called.
380
+
381
+ ### .reset
382
+
383
+ ```js
384
+ reset() : void
385
+ ```
386
+
387
+ Resets the generator so a new BVH is generated. This must be called when geometry, objects, or materials are added or removed from the scene.
388
+
389
+ ## BlurredEnvMapGenerator
390
+
391
+ Utility for generating a PMREM blurred environment map that can be used with the path tracer.
392
+
393
+ ### constructor
394
+
395
+ ```js
396
+ constructor( renderer : WebGLRenderer )
397
+ ```
398
+
399
+ ### .generate
400
+
401
+ ```js
402
+ generate( texture : Texture, blur : Number ) : DataTexture
403
+ ```
404
+
405
+ Takes a texture to blur and the amount to blur it. Returns a new `DataTexture` that has been PMREM blurred environment map that can have distribution data generated for importance sampling.
406
+
407
+ ### .dispose
408
+
409
+ ```js
410
+ dispose() : void
411
+ ```
412
+
413
+ Disposes of the temporary files and textures for generation.
414
+
415
+ ## MaterialBase
416
+
417
+ _extends THREE.ShaderMaterial_
418
+
419
+ Convenience base class that adds additional functions and implicitly adds object definitions for all uniforms of the shader to the object.
420
+
421
+ ### .setDefine
422
+
423
+ ```js
424
+ setDefine( name : string, value = undefined : any ) : void
425
+ ```
426
+
427
+ Sets the define of the given name to the provided value. If the value is set to null or undefined then it is deleted from the defines of the material. If the define changed from the previous value then `Material.needsUpdate` is set to `true`.
428
+
429
+ ## PhysicalPathTracingMaterial
430
+
431
+ _extends MaterialBase_
432
+
433
+ **Uniforms**
434
+
435
+ ```js
436
+ {
437
+ // The number of ray bounces to test. Higher is better quality but slower performance.
438
+ bounces = 3 : Number,
439
+
440
+ // The physical camera parameters to use
441
+ physicalCamera : PhysicalCameraUniform,
442
+
443
+ // Geometry and BVH information
444
+ bvh: MeshBVHUniformStruct,
445
+ normalAttribute: FloatVertexAttributeTexture,
446
+ tangentAttribute: FloatVertexAttributeTexture,
447
+ uvAttribute: FloatVertexAttributeTexture,
448
+ materialIndexAttribute: UIntVertexAttributeTexture,
449
+ materials: MaterialsTexture,
450
+ textures: RenderTarget2DArray,
451
+
452
+ // Environment Map information
453
+ envMapInfo: EquirectHdrInfoUniform,
454
+ environmentRotation: Matrix3,
455
+ environmentIntensity = 1: Number,
456
+
457
+ // background blur
458
+ backgroundBlur = 0: Number,
459
+
460
+ // Factor for alleviating bright pixels from rays that hit diffuse surfaces then
461
+ // specular surfaces. Setting this higher alleviates fireflies but will remove some
462
+ // specular caustics.
463
+ filterGlossyFactor = 0: Number,
464
+
465
+ // The colors to use for the gradient background when enabled.
466
+ bgGradientTop: Color,
467
+ bgGradientBottom: Color,
468
+
469
+ // The transparency to render the background with. Note that the "alpha" option
470
+ // must be set to true on PathTracingRenderer for this field to work properly.
471
+ backgroundAlpha: 1.0,
472
+ }
473
+ ```
474
+
475
+ **Defines**
476
+
477
+ ```js
478
+ {
479
+
480
+ // Whether to use multiple importance sampling to help the image converge more quickly
481
+ FEATURE_MIS = 1 : Number,
482
+
483
+ // Whether to use the "bg" gradient fields to sample for the background
484
+ FEATURE_GRADIENT_BG = 0 : Number
485
+
486
+ // The number of transparent pixels to allow on top of existing bounces for object transparency.
487
+ TRANSPARENT_TRAVERSALS = 5 : Number,
488
+
489
+
490
+ }
491
+ ```
492
+
493
+ ## RenderTarget2DArray
494
+
495
+ _extends WebGLArrayRenderTarget_
496
+
497
+ A convenience extension from `WebGLArrayRenderTarget` that affords easily creating a uniform texture array from an array of textures.
498
+
499
+ ### .setTextures
500
+
501
+ ```js
502
+ setTextures(
503
+ renderer : WebGLRenderer,
504
+ width : Number,
505
+ height : Number,
506
+ textures : Array<Texture>
507
+ ) : void
508
+ ```
509
+
510
+ Takes the rendering context to updateh the target for, the target dimensions of the texture array, and the array of textures to render into the 2D texture array. Every texture is stretched to the dimensions of the texture array at the same index they are provided in.
511
+
512
+ ## PhysicalCameraUniform
513
+
514
+ Uniform for storing the camera parameters for use with the shader.
515
+
516
+ ### .updateFrom
517
+
518
+ ```js
519
+ updateFrom( camera : PerspectiveCamera | PhysicalCamera ) : void
520
+ ```
521
+
522
+ Copies all fields from the passed PhysicalCamera if available otherwise the defaults are used.
523
+
524
+ ## MaterialsTexture
525
+
526
+ _extends DataTexture_
527
+
528
+ Helper texture uniform for encoding materials as texture data.
529
+
530
+ ### .setSide
531
+
532
+ ```js
533
+ setSide( index : Number, side : FrontSide | BackSide | DoubleSide ) : void
534
+ ```
535
+
536
+ Sets the side to render for the given material.
537
+
538
+ ### .setMatte
539
+
540
+ ```js
541
+ setMatte( index : Number, matte : Boolean ) : void
542
+ ```
543
+
544
+ Sets whether or not the material of the given index is matte or not. When "true" the background is rendered in place of the material.
545
+
546
+ ### .setCastShadow
547
+
548
+ ```js
549
+ setCastShadow( index : Number, enabled : Boolean ) : void
550
+ ```
551
+
552
+ Sets whether or not the material of the given index will cast shadows. When "false" materials will not cast shadows on diffuse surfaces but will still be reflected. This is a good setting for lighting enclosed interiors with environment lighting.
553
+
554
+ ### .updateFrom
555
+
556
+ ```js
557
+ updateFrom( materials : Array<Material>, textures : Array<Texture> ) : void
558
+ ```
559
+
560
+ Updates the size and values of the texture to align with the provided set of materials and textures.
561
+
562
+ The "matte" and "side" values must be updated explicitly.
563
+
564
+ ## EquirectHdrInfoUniform
565
+
566
+ Stores the environment map contents along with the intensity distribution information to support multiple importance sampling.
567
+
568
+ ### .updateFrom
569
+
570
+ ```js
571
+ updateFrom( environmentMap : Texture ) : void
572
+ ```
573
+
574
+ Takes an environment map to process into something usable by the path tracer. Is expected to be a DataTexture so the data can be read.
575
+
576
+ ## Functions
577
+
578
+ ### mergeMeshes
579
+
580
+ ```js
581
+ mergeMeshes( meshes : Array<Mesh> ) : {
582
+ materials : Array<Material>,
583
+ textures : Array<Textures>,
584
+ geometry : BufferGeometry
585
+ }
586
+ ```
587
+
588
+ Merges the set of meshes into a single geometry with a `materialIndex` vertex attribute included on the geometry identifying the associated material in the returned `materials` array.
589
+
590
+ ## Shader Chunks
591
+
592
+ **shaderMaterialSampling**
593
+
594
+ Set of functions for performing material scatter and PDF sampling. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderMaterialSampling.js) for full list of functions.
595
+
596
+ **shaderStructs**
597
+
598
+ Material struct definition for use with uniforms. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderStructs.js) for full list of functions.
599
+
600
+ **shaderUtils**
601
+
602
+ Set of randomness and other light transmport utilities for use in a shader. See the [implementation](https://github.com/gkjohnson/three-gpu-pathtracer/blob/main/src/shader/shaderUtils.js) for full list of functions.
603
+
604
+ # Gotchas
605
+
606
+ - The project requires use of WebGL2.
607
+ - All textures must use the same wrap and interpolation flags.
608
+
609
+ # Screenshots
610
+
611
+ ![](https://user-images.githubusercontent.com/734200/162584469-68e6df38-92da-4a13-b352-ca0bdea14548.png)
612
+
613
+ <p align="center">
614
+ <i>Sample materials</i>
615
+ </p>
616
+
617
+ ![](https://user-images.githubusercontent.com/734200/163835927-be75d2c0-f27b-4e4b-a3eb-2371043fa5e1.png)
618
+
619
+ ![](https://user-images.githubusercontent.com/734200/163839431-ed75e64d-9ae4-4423-afca-55162a44873e.png)
620
+
621
+ <p align="center">
622
+ <i>"SD Macross City Standoff Diorama" scene by <a href="https://sketchfab.com/3d-models/sd-macross-city-standoff-diorama-b154220f7e7441799d6be2f7ff9658c7">tipatat</a></i>
623
+ </p>
624
+
625
+ ![](./docs/interior-scene-cropped.png)
626
+
627
+ <p align="center">
628
+ <i>"Interior Scene" model by <a href="https://sketchfab.com/3d-models/interior-scene-45ddbbc4c2dc4f8ca9ed99da9a78326a">Allay Design</a></i>
629
+ </p>
630
+
631
+ ![](https://user-images.githubusercontent.com/734200/161820794-df0da371-ee5c-4368-9e7b-5e7daf6cf3c7.png)
632
+
633
+ ![](https://user-images.githubusercontent.com/734200/162550315-3cdabf40-3dea-4d7d-bcfc-eb543eea2d93.png)
634
+
635
+ <p align="center">
636
+ <i>Perseverance Rover, Ingenuity Helicopter models by <a href="https://mars.nasa.gov/resources/25042/mars-perseverance-rover-3d-model/">NASA / JPL-Caltech</a></i>
637
+ </p>
638
+
639
+ ![](https://user-images.githubusercontent.com/734200/161877900-566652e4-c799-4940-bccb-0c8f4cea5387.png)
640
+
641
+ <p align="center">
642
+ <i>Gelatinous Cube model by <a href="https://sketchfab.com/3d-models/gelatinous-cube-e08385238f4d4b59b012233a9fbdca21">glenatron</a></i>
643
+ </p>
644
+
645
+ ![](https://user-images.githubusercontent.com/734200/161822206-c27bf594-d648-4735-868e-4baf4e414802.png)
646
+
647
+ ![](https://user-images.githubusercontent.com/734200/161822214-eace4297-03c4-4adc-b472-efe29a862685.png)
648
+
649
+ <p align="center">
650
+ <i>Lego models courtesy of the <a href="https://omr.ldraw.org/">LDraw Official Model Repository</a></i>
651
+ </p>
652
+
653
+ ![](https://user-images.githubusercontent.com/734200/161877196-7ae2769e-7e54-4694-9ca8-e8f5219d1c2d.png)
654
+
655
+ <p align="center">
656
+ <i>Octopus Tea model by <a href="https://sketchfab.com/3d-models/cartoon-octopus-takes-a-tea-bath-107260cf0fd24202a67eb037a6c760a5
657
+ ">AzTiZ</a></i>
658
+ </p>
659
+
660
+ ![](https://user-images.githubusercontent.com/734200/173212652-de6a83e5-dd2c-49b5-8ed7-484ff8969b5b.png)
661
+ <p align="center">
662
+ <i>Botanists Study model by <a href="https://sketchfab.com/3d-models/the-botanists-study-8b7b5743b1c848ed8ea58f5518c44e7e">riikkakilpelainen</a></i>
663
+ </p>
664
+
665
+ ![](https://user-images.githubusercontent.com/734200/173170459-849b9343-efe3-4635-8719-346511472965.png)
666
+ <p align="center">
667
+ <i>Japanese Bridge Garden model by <a href="https://sketchfab.com/3d-models/japanese-bridge-garden-d122e17593eb4012913cde927486d15a">kristenlee</a></i>
668
+ </p>
669
+
670
+ ### Resources
671
+
672
+ [Raytracing in One Weekend Book](https://raytracing.github.io/)
673
+
674
+ [PBR Book](https://pbr-book.org/)
675
+
676
+ [knightcrawler25/GLSL-PathTracer](https://github.com/knightcrawler25/GLSL-PathTracer/)
677
+
678
+