webgl_renderer_pathtracer.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - three-gpu-pathtracer</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. color: #444;
  11. background-color: white;
  12. }
  13. a {
  14. color: #fb8c00;
  15. }
  16. .checkerboard {
  17. background-image:
  18. linear-gradient(45deg, #ddd 25%, transparent 25%),
  19. linear-gradient(-45deg, #ddd 25%, transparent 25%),
  20. linear-gradient(45deg, transparent 75%, #ddd 75%),
  21. linear-gradient(-45deg, transparent 75%, #ddd 75%);
  22. background-size: 20px 20px;
  23. background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  24. }
  25. .lil-gui .gui-render {
  26. line-height: var(--widget-height);
  27. padding: var(--padding);
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div id="info">
  33. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> pathtracer - <a href="https://github.com/gkjohnson/three-gpu-pathtracer" target="_blank" rel="noopener">three-gpu-pathtracer</a><br/>
  34. See <a href="https://github.com/gkjohnson/three-gpu-pathtracer" target="_blank" rel="noopener">main project repository</a> for more information and examples on high fidelity path tracing.
  35. </div>
  36. <!-- Import maps polyfill -->
  37. <!-- Remove this when import maps will be widely supported -->
  38. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  39. <script type="importmap">
  40. {
  41. "imports": {
  42. "three": "../build/three.module.js",
  43. "three/addons/": "./jsm/",
  44. "three/examples/": "./",
  45. "three-gpu-pathtracer": "https://unpkg.com/[email protected]/build/index.module.js",
  46. "three-mesh-bvh": "https://unpkg.com/three-mesh-bvh@^0.5.21/build/index.module.js"
  47. }
  48. }
  49. </script>
  50. <script type="module">
  51. import * as THREE from 'three';
  52. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  53. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  54. import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
  55. import { LDrawLoader } from 'three/addons/loaders/LDrawLoader.js';
  56. import { LDrawUtils } from 'three/addons/utils/LDrawUtils.js';
  57. import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
  58. import { PhysicalPathTracingMaterial, PathTracingRenderer, MaterialReducer, BlurredEnvMapGenerator, PathTracingSceneGenerator, GradientEquirectTexture } from 'three-gpu-pathtracer';
  59. let progressBarDiv, samplesEl;
  60. let camera, scene, renderer, controls, gui;
  61. let pathTracer, sceneInfo, fsQuad, floor;
  62. let delaySamples = 0;
  63. const params = {
  64. enable: true,
  65. toneMapping: true,
  66. pause: false,
  67. tiles: 3,
  68. transparentBackground: false,
  69. resolutionScale: 1,
  70. download: () => {
  71. const link = document.createElement( 'a' );
  72. link.download = 'pathtraced-render.png';
  73. link.href = renderer.domElement.toDataURL().replace( 'image/png', 'image/octet-stream' );
  74. link.click();
  75. },
  76. roughness: 0.15,
  77. metalness: 0.9,
  78. };
  79. init();
  80. render();
  81. function init() {
  82. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
  83. camera.position.set( 150, 200, 250 );
  84. // initialize the renderer
  85. renderer = new THREE.WebGLRenderer( { antialias: true, preserveDrawingBuffer: true, premultipliedAlpha: false } );
  86. renderer.setPixelRatio( window.devicePixelRatio );
  87. renderer.setSize( window.innerWidth, window.innerHeight );
  88. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  89. renderer.setClearColor( 0xdddddd );
  90. document.body.appendChild( renderer.domElement );
  91. // initialize the pathtracer
  92. pathTracer = new PathTracingRenderer( renderer );
  93. pathTracer.alpha = true;
  94. pathTracer.tiles.set( params.tiles, params.tiles );
  95. pathTracer.material = new PhysicalPathTracingMaterial();
  96. pathTracer.material.setDefine( 'FEATURE_MIS', 1 );
  97. const gradientMap = new GradientEquirectTexture();
  98. gradientMap.topColor.set( 0xeeeeee );
  99. gradientMap.bottomColor.set( 0xeaeaea );
  100. gradientMap.update();
  101. pathTracer.material.backgroundMap = gradientMap;
  102. pathTracer.camera = camera;
  103. fsQuad = new FullScreenQuad( new THREE.MeshBasicMaterial( {
  104. map: pathTracer.target.texture,
  105. blending: THREE.CustomBlending
  106. } ) );
  107. // scene
  108. scene = new THREE.Scene();
  109. controls = new OrbitControls( camera, renderer.domElement );
  110. controls.addEventListener( 'change', () => {
  111. delaySamples = 5;
  112. pathTracer.reset();
  113. } );
  114. window.addEventListener( 'resize', onWindowResize );
  115. onWindowResize();
  116. progressBarDiv = document.createElement( 'div' );
  117. progressBarDiv.innerText = 'Loading...';
  118. progressBarDiv.style.fontSize = '3em';
  119. progressBarDiv.style.color = '#888';
  120. progressBarDiv.style.display = 'block';
  121. progressBarDiv.style.position = 'absolute';
  122. progressBarDiv.style.top = '50%';
  123. progressBarDiv.style.width = '100%';
  124. progressBarDiv.style.textAlign = 'center';
  125. // load materials and then the model
  126. createGUI();
  127. loadModel();
  128. }
  129. async function loadModel() {
  130. progressBarDiv.innerText = 'Loading...';
  131. let model = null;
  132. let envMap = null;
  133. updateProgressBar( 0 );
  134. showProgressBar();
  135. // only smooth when not rendering with flat colors to improve processing time
  136. const ldrawPromise =
  137. new LDrawLoader()
  138. .setPath( 'models/ldraw/officialLibrary/' )
  139. .loadAsync( 'models/7140-1-X-wingFighter.mpd_Packed.mpd', onProgress )
  140. .then( function ( legoGroup ) {
  141. legoGroup = LDrawUtils.mergeObject( legoGroup );
  142. legoGroup.rotation.x = Math.PI;
  143. model = new THREE.Group();
  144. model.add( legoGroup );
  145. // Convert from LDraw coordinates: rotate 180 degrees around OX
  146. model.updateMatrixWorld();
  147. } )
  148. .catch( onError );
  149. const envMapPromise =
  150. new RGBELoader()
  151. .setPath( 'textures/equirectangular/' )
  152. .loadAsync( 'royal_esplanade_1k.hdr' )
  153. .then( tex => {
  154. const envMapGenerator = new BlurredEnvMapGenerator( renderer );
  155. const blurredEnvMap = envMapGenerator.generate( tex, 0 );
  156. scene.environment = blurredEnvMap;
  157. envMap = blurredEnvMap;
  158. } );
  159. await Promise.all( [ envMapPromise, ldrawPromise ] );
  160. hideProgressBar();
  161. document.body.classList.add( 'checkerboard' );
  162. // Adjust camera
  163. const bbox = new THREE.Box3().setFromObject( model );
  164. const size = bbox.getSize( new THREE.Vector3() );
  165. const radius = Math.max( size.x, Math.max( size.y, size.z ) ) * 0.4;
  166. controls.target0.copy( bbox.getCenter( new THREE.Vector3() ) );
  167. controls.position0.set( 2.3, 1, 2 ).multiplyScalar( radius ).add( controls.target0 );
  168. controls.reset();
  169. // add floor
  170. floor = new THREE.Mesh(
  171. new THREE.PlaneGeometry(),
  172. new THREE.MeshStandardMaterial( {
  173. side: THREE.DoubleSide,
  174. roughness: 0.01,
  175. metalness: 1,
  176. map: generateRadialFloorTexture( 1024 ),
  177. transparent: true,
  178. } ),
  179. );
  180. floor.scale.setScalar( 2500 );
  181. floor.rotation.x = - Math.PI / 2;
  182. floor.position.y = bbox.min.y;
  183. model.add( floor );
  184. model.updateMatrixWorld();
  185. // de-duplicate and reduce the number of materials used in place
  186. const reducer = new MaterialReducer();
  187. reducer.process( model );
  188. // reset the progress bar to display bvh generation
  189. progressBarDiv.innerText = 'Generating BVH...';
  190. updateProgressBar( 0 );
  191. const generator = new PathTracingSceneGenerator();
  192. const result = generator.generate( model );
  193. // add the model to the scene
  194. sceneInfo = result;
  195. sceneInfo.scene.traverse( c => {
  196. if ( c.isLineSegments ) {
  197. c.visible = false;
  198. }
  199. } );
  200. scene.add( sceneInfo.scene );
  201. // update the material
  202. const { bvh, textures, materials } = result;
  203. const geometry = bvh.geometry;
  204. const material = pathTracer.material;
  205. material.bvh.updateFrom( bvh );
  206. material.attributesArray.updateFrom(
  207. geometry.attributes.normal,
  208. geometry.attributes.tangent,
  209. geometry.attributes.uv,
  210. geometry.attributes.color,
  211. );
  212. material.materialIndexAttribute.updateFrom( geometry.attributes.materialIndex );
  213. material.textures.setTextures( renderer, 2048, 2048, textures );
  214. material.materials.updateFrom( materials, textures );
  215. pathTracer.material.envMapInfo.updateFrom( envMap );
  216. pathTracer.reset();
  217. }
  218. function onWindowResize() {
  219. const w = window.innerWidth;
  220. const h = window.innerHeight;
  221. const scale = params.resolutionScale;
  222. const dpr = window.devicePixelRatio;
  223. pathTracer.setSize( w * scale * dpr, h * scale * dpr );
  224. pathTracer.reset();
  225. renderer.setSize( w, h );
  226. renderer.setPixelRatio( window.devicePixelRatio * scale );
  227. const aspect = w / h;
  228. camera.aspect = aspect;
  229. camera.updateProjectionMatrix();
  230. }
  231. function createGUI() {
  232. if ( gui ) {
  233. gui.destroy();
  234. }
  235. gui = new GUI();
  236. gui.add( params, 'enable' );
  237. gui.add( params, 'pause' );
  238. gui.add( params, 'toneMapping' );
  239. gui.add( params, 'transparentBackground' ).onChange( v => {
  240. pathTracer.material.backgroundAlpha = v ? 0 : 1;
  241. renderer.setClearAlpha( v ? 0 : 1 );
  242. pathTracer.reset();
  243. } );
  244. gui.add( params, 'resolutionScale', 0.1, 1.0 ).onChange( onWindowResize );
  245. gui.add( params, 'tiles', 1, 3, 1 ).onChange( v => {
  246. pathTracer.tiles.set( v, v );
  247. } );
  248. gui.add( params, 'roughness', 0, 1 ).name( 'floor roughness' ).onChange( () => {
  249. pathTracer.reset();
  250. } );
  251. gui.add( params, 'metalness', 0, 1 ).name( 'floor metalness' ).onChange( () => {
  252. pathTracer.reset();
  253. } );
  254. gui.add( params, 'download' ).name( 'download image' );
  255. const renderFolder = gui.addFolder( 'Render' );
  256. samplesEl = document.createElement( 'div' );
  257. samplesEl.classList.add( 'gui-render' );
  258. samplesEl.innerText = 'samples: 0';
  259. renderFolder.$children.appendChild( samplesEl );
  260. renderFolder.open();
  261. }
  262. //
  263. function render() {
  264. requestAnimationFrame( render );
  265. if ( ! sceneInfo ) {
  266. return;
  267. }
  268. renderer.toneMapping = params.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
  269. if ( pathTracer.samples < 1.0 || ! params.enable ) {
  270. renderer.render( scene, camera );
  271. }
  272. if ( params.enable && delaySamples === 0 ) {
  273. const samples = Math.floor( pathTracer.samples );
  274. samplesEl.innerText = `samples: ${ samples }`;
  275. floor.material.roughness = params.roughness;
  276. floor.material.metalness = params.metalness;
  277. pathTracer.material.materials.updateFrom( sceneInfo.materials, sceneInfo.textures );
  278. pathTracer.material.filterGlossyFactor = 0.5;
  279. pathTracer.material.physicalCamera.updateFrom( camera );
  280. camera.updateMatrixWorld();
  281. if ( ! params.pause || pathTracer.samples < 1 ) {
  282. pathTracer.update();
  283. }
  284. renderer.autoClear = false;
  285. fsQuad.render( renderer );
  286. renderer.autoClear = true;
  287. } else if ( delaySamples > 0 ) {
  288. delaySamples --;
  289. }
  290. samplesEl.innerText = `samples: ${ Math.floor( pathTracer.samples ) }`;
  291. }
  292. function onProgress( xhr ) {
  293. if ( xhr.lengthComputable ) {
  294. updateProgressBar( xhr.loaded / xhr.total );
  295. console.log( Math.round( xhr.loaded / xhr.total * 100, 2 ) + '% downloaded' );
  296. }
  297. }
  298. function onError( error ) {
  299. const message = 'Error loading model';
  300. progressBarDiv.innerText = message;
  301. console.log( message );
  302. console.error( error );
  303. }
  304. function showProgressBar() {
  305. document.body.appendChild( progressBarDiv );
  306. }
  307. function hideProgressBar() {
  308. document.body.removeChild( progressBarDiv );
  309. }
  310. function updateProgressBar( fraction ) {
  311. progressBarDiv.innerText = 'Loading... ' + Math.round( fraction * 100, 2 ) + '%';
  312. }
  313. function generateRadialFloorTexture( dim ) {
  314. const data = new Uint8Array( dim * dim * 4 );
  315. for ( let x = 0; x < dim; x ++ ) {
  316. for ( let y = 0; y < dim; y ++ ) {
  317. const xNorm = x / ( dim - 1 );
  318. const yNorm = y / ( dim - 1 );
  319. const xCent = 2.0 * ( xNorm - 0.5 );
  320. const yCent = 2.0 * ( yNorm - 0.5 );
  321. let a = Math.max( Math.min( 1.0 - Math.sqrt( xCent ** 2 + yCent ** 2 ), 1.0 ), 0.0 );
  322. a = a ** 1.5;
  323. a = a * 1.5;
  324. a = Math.min( a, 1.0 );
  325. const i = y * dim + x;
  326. data[ i * 4 + 0 ] = 255;
  327. data[ i * 4 + 1 ] = 255;
  328. data[ i * 4 + 2 ] = 255;
  329. data[ i * 4 + 3 ] = a * 255;
  330. }
  331. }
  332. const tex = new THREE.DataTexture( data, dim, dim );
  333. tex.format = THREE.RGBAFormat;
  334. tex.type = THREE.UnsignedByteType;
  335. tex.minFilter = THREE.LinearFilter;
  336. tex.magFilter = THREE.LinearFilter;
  337. tex.wrapS = THREE.RepeatWrapping;
  338. tex.wrapT = THREE.RepeatWrapping;
  339. tex.needsUpdate = true;
  340. return tex;
  341. }
  342. </script>
  343. <!-- LDraw.org CC BY 2.0 Parts Library attribution -->
  344. <div style="display: block; position: absolute; bottom: 8px; left: 8px; width: 160px; padding: 10px; background-color: #F3F7F8;">
  345. <center>
  346. <a href="http://www.ldraw.org"><img style="width: 145px" src="models/ldraw/ldraw_org_logo/Stamp145.png"></a>
  347. <br />
  348. <a href="http://www.ldraw.org/">This software uses the LDraw Parts Library</a>
  349. </center>
  350. </div>
  351. </body>
  352. </html>