webgl_renderer_pathtracer.html 14 KB

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