webgl_renderer_pathtracer.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. <meta property="og:title" content="three.js webgl - three-gpu-pathtracer">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_renderer_pathtracer.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_renderer_pathtracer.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. <style>
  13. body {
  14. color: #444;
  15. background-color: white;
  16. }
  17. a {
  18. color: #fb8c00;
  19. }
  20. .checkerboard {
  21. background-image:
  22. linear-gradient(45deg, #ddd 25%, transparent 25%),
  23. linear-gradient(-45deg, #ddd 25%, transparent 25%),
  24. linear-gradient(45deg, transparent 75%, #ddd 75%),
  25. linear-gradient(-45deg, transparent 75%, #ddd 75%);
  26. background-size: 20px 20px;
  27. background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  28. }
  29. .lil-gui .gui-render {
  30. line-height: var(--widget-height);
  31. padding: var(--padding);
  32. }
  33. </style>
  34. </head>
  35. <body>
  36. <div id="info">
  37. <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/>
  38. 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.
  39. </div>
  40. <script type="importmap">
  41. {
  42. "imports": {
  43. "three": "../build/three.module.js",
  44. "three/addons/": "./jsm/",
  45. "three/examples/": "./",
  46. "three-gpu-pathtracer": "https://cdn.jsdelivr.net/npm/three-gpu-pathtracer@0.0.24/build/index.module.js",
  47. "three-mesh-bvh": "https://cdn.jsdelivr.net/npm/three-mesh-bvh@0.9.10/build/index.module.js"
  48. }
  49. }
  50. </script>
  51. <script type="module">
  52. import * as THREE from 'three';
  53. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  54. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  55. import { UltraHDRLoader } from 'three/addons/loaders/UltraHDRLoader.js';
  56. import { LDrawLoader } from 'three/addons/loaders/LDrawLoader.js';
  57. import { LDrawUtils } from 'three/addons/utils/LDrawUtils.js';
  58. import { LDrawConditionalLineMaterial } from 'three/addons/materials/LDrawConditionalLineMaterial.js';
  59. import { WebGLPathTracer, BlurredEnvMapGenerator, GradientEquirectTexture } from 'three-gpu-pathtracer';
  60. let progressBarDiv, samplesEl;
  61. let camera, scene, renderer, controls, gui;
  62. let pathTracer, floor, gradientMap;
  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. function init() {
  81. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
  82. camera.position.set( 150, 200, 250 );
  83. // initialize the renderer
  84. renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true, preserveDrawingBuffer: true } );
  85. renderer.setPixelRatio( window.devicePixelRatio );
  86. renderer.setSize( window.innerWidth, window.innerHeight );
  87. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  88. document.body.appendChild( renderer.domElement );
  89. gradientMap = new GradientEquirectTexture();
  90. gradientMap.topColor.set( 0xeeeeee );
  91. gradientMap.bottomColor.set( 0xeaeaea );
  92. gradientMap.update();
  93. // initialize the pathtracer
  94. pathTracer = new WebGLPathTracer( renderer );
  95. pathTracer.filterGlossyFactor = 1;
  96. pathTracer.minSamples = 3;
  97. pathTracer.renderScale = params.resolutionScale;
  98. pathTracer.tiles.set( params.tiles, params.tiles );
  99. // scene
  100. scene = new THREE.Scene();
  101. scene.background = gradientMap;
  102. controls = new OrbitControls( camera, renderer.domElement );
  103. controls.addEventListener( 'change', () => {
  104. pathTracer.updateCamera();
  105. } );
  106. window.addEventListener( 'resize', onWindowResize );
  107. onWindowResize();
  108. progressBarDiv = document.createElement( 'div' );
  109. progressBarDiv.innerText = 'Loading...';
  110. progressBarDiv.style.fontSize = '3em';
  111. progressBarDiv.style.color = '#888';
  112. progressBarDiv.style.display = 'block';
  113. progressBarDiv.style.position = 'absolute';
  114. progressBarDiv.style.top = '50%';
  115. progressBarDiv.style.width = '100%';
  116. progressBarDiv.style.textAlign = 'center';
  117. // load materials and then the model
  118. createGUI();
  119. loadModel();
  120. }
  121. async function loadModel() {
  122. progressBarDiv.innerText = 'Loading...';
  123. let model = null;
  124. let environment = null;
  125. updateProgressBar( 0 );
  126. showProgressBar();
  127. // only smooth when not rendering with flat colors to improve processing time
  128. const ldrawPromise =
  129. new LDrawLoader()
  130. .setConditionalLineMaterial( LDrawConditionalLineMaterial )
  131. .setPath( 'models/ldraw/officialLibrary/' )
  132. .loadAsync( 'models/7140-1-X-wingFighter.mpd_Packed.mpd', onProgress )
  133. .then( function ( legoGroup ) {
  134. // Convert from LDraw coordinates: rotate 180 degrees around OX
  135. legoGroup = LDrawUtils.mergeObject( legoGroup );
  136. legoGroup.rotation.x = Math.PI;
  137. legoGroup.updateMatrixWorld();
  138. model = legoGroup;
  139. legoGroup.traverse( c => {
  140. // hide the line segments
  141. if ( c.isLineSegments ) {
  142. c.visible = false;
  143. }
  144. // adjust the materials to use transmission, be a bit shinier
  145. if ( c.material ) {
  146. c.material.roughness *= 0.25;
  147. if ( c.material.opacity < 1.0 ) {
  148. const oldMaterial = c.material;
  149. const newMaterial = new THREE.MeshPhysicalMaterial();
  150. newMaterial.opacity = 1.0;
  151. newMaterial.transmission = 1.0;
  152. newMaterial.thickness = 1.0;
  153. newMaterial.ior = 1.4;
  154. newMaterial.roughness = oldMaterial.roughness;
  155. newMaterial.metalness = 0.0;
  156. const hsl = {};
  157. oldMaterial.color.getHSL( hsl );
  158. hsl.l = Math.max( hsl.l, 0.35 );
  159. newMaterial.color.setHSL( hsl.h, hsl.s, hsl.l );
  160. c.material = newMaterial;
  161. }
  162. }
  163. } );
  164. } )
  165. .catch( onError );
  166. const envMapPromise =
  167. new UltraHDRLoader()
  168. .setPath( 'textures/equirectangular/' )
  169. .loadAsync( 'royal_esplanade_2k.hdr.jpg' )
  170. .then( tex => {
  171. const envMapGenerator = new BlurredEnvMapGenerator( renderer );
  172. const blurredEnvMap = envMapGenerator.generate( tex, 0 );
  173. environment = blurredEnvMap;
  174. } )
  175. .catch( onError );
  176. await Promise.all( [ envMapPromise, ldrawPromise ] );
  177. hideProgressBar();
  178. document.body.classList.add( 'checkerboard' );
  179. // set environment map
  180. scene.environment = environment;
  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 the model
  189. scene.add( model );
  190. // add floor
  191. floor = new THREE.Mesh(
  192. new THREE.PlaneGeometry(),
  193. new THREE.MeshStandardMaterial( {
  194. side: THREE.DoubleSide,
  195. roughness: params.roughness,
  196. metalness: params.metalness,
  197. map: generateRadialFloorTexture( 1024 ),
  198. transparent: true,
  199. } ),
  200. );
  201. floor.scale.setScalar( 2500 );
  202. floor.rotation.x = - Math.PI / 2;
  203. floor.position.y = bbox.min.y;
  204. scene.add( floor );
  205. // reset the progress bar to display bvh generation
  206. progressBarDiv.innerText = 'Generating BVH...';
  207. updateProgressBar( 0 );
  208. pathTracer.setScene( scene, camera );
  209. renderer.setAnimationLoop( animate );
  210. }
  211. function onWindowResize() {
  212. const w = window.innerWidth;
  213. const h = window.innerHeight;
  214. const dpr = window.devicePixelRatio;
  215. renderer.setSize( w, h );
  216. renderer.setPixelRatio( dpr );
  217. const aspect = w / h;
  218. camera.aspect = aspect;
  219. camera.updateProjectionMatrix();
  220. pathTracer.updateCamera();
  221. }
  222. function createGUI() {
  223. if ( gui ) {
  224. gui.destroy();
  225. }
  226. gui = new GUI();
  227. gui.add( params, 'enable' );
  228. gui.add( params, 'pause' );
  229. gui.add( params, 'toneMapping' );
  230. gui.add( params, 'transparentBackground' ).onChange( v => {
  231. scene.background = v ? null : gradientMap;
  232. pathTracer.updateEnvironment();
  233. } );
  234. gui.add( params, 'resolutionScale', 0.1, 1.0, 0.1 ).onChange( v => {
  235. pathTracer.renderScale = v;
  236. pathTracer.reset();
  237. } );
  238. gui.add( params, 'tiles', 1, 6, 1 ).onChange( v => {
  239. pathTracer.tiles.set( v, v );
  240. } );
  241. gui.add( params, 'roughness', 0, 1 ).name( 'floor roughness' ).onChange( v => {
  242. floor.material.roughness = v;
  243. pathTracer.updateMaterials();
  244. } );
  245. gui.add( params, 'metalness', 0, 1 ).name( 'floor metalness' ).onChange( v => {
  246. floor.material.metalness = v;
  247. pathTracer.updateMaterials();
  248. } );
  249. gui.add( params, 'download' ).name( 'download image' );
  250. const renderFolder = gui.addFolder( 'Render' );
  251. samplesEl = document.createElement( 'div' );
  252. samplesEl.classList.add( 'gui-render' );
  253. samplesEl.innerText = 'samples: 0';
  254. renderFolder.$children.appendChild( samplesEl );
  255. renderFolder.open();
  256. }
  257. //
  258. function animate() {
  259. renderer.toneMapping = params.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
  260. const samples = Math.floor( pathTracer.samples );
  261. samplesEl.innerText = `samples: ${ samples }`;
  262. pathTracer.enablePathTracing = params.enable;
  263. pathTracer.pausePathTracing = params.pause;
  264. pathTracer.renderSample();
  265. samplesEl.innerText = `samples: ${ Math.floor( pathTracer.samples ) }`;
  266. }
  267. function onProgress( xhr ) {
  268. if ( xhr.lengthComputable ) {
  269. updateProgressBar( xhr.loaded / xhr.total );
  270. console.log( Math.round( xhr.loaded / xhr.total * 100 ) + '% downloaded' );
  271. }
  272. }
  273. function onError( error ) {
  274. const message = 'Error loading model';
  275. progressBarDiv.innerText = message;
  276. console.log( message );
  277. console.error( error );
  278. }
  279. function showProgressBar() {
  280. document.body.appendChild( progressBarDiv );
  281. }
  282. function hideProgressBar() {
  283. document.body.removeChild( progressBarDiv );
  284. }
  285. function updateProgressBar( fraction ) {
  286. progressBarDiv.innerText = 'Loading... ' + Math.round( fraction * 100 ) + '%';
  287. }
  288. function generateRadialFloorTexture( dim ) {
  289. const data = new Uint8Array( dim * dim * 4 );
  290. for ( let x = 0; x < dim; x ++ ) {
  291. for ( let y = 0; y < dim; y ++ ) {
  292. const xNorm = x / ( dim - 1 );
  293. const yNorm = y / ( dim - 1 );
  294. const xCent = 2.0 * ( xNorm - 0.5 );
  295. const yCent = 2.0 * ( yNorm - 0.5 );
  296. let a = Math.max( Math.min( 1.0 - Math.sqrt( xCent ** 2 + yCent ** 2 ), 1.0 ), 0.0 );
  297. a = a ** 1.5;
  298. a = a * 1.5;
  299. a = Math.min( a, 1.0 );
  300. const i = y * dim + x;
  301. data[ i * 4 + 0 ] = 255;
  302. data[ i * 4 + 1 ] = 255;
  303. data[ i * 4 + 2 ] = 255;
  304. data[ i * 4 + 3 ] = a * 255;
  305. }
  306. }
  307. const tex = new THREE.DataTexture( data, dim, dim );
  308. tex.format = THREE.RGBAFormat;
  309. tex.type = THREE.UnsignedByteType;
  310. tex.minFilter = THREE.LinearFilter;
  311. tex.magFilter = THREE.LinearFilter;
  312. tex.wrapS = THREE.RepeatWrapping;
  313. tex.wrapT = THREE.RepeatWrapping;
  314. tex.needsUpdate = true;
  315. return tex;
  316. }
  317. </script>
  318. <!-- LDraw.org CC BY 2.0 Parts Library attribution -->
  319. <div style="display: block; position: absolute; bottom: 8px; left: 8px; width: 160px; padding: 10px; background-color: #F3F7F8;">
  320. <center>
  321. <a href="http://www.ldraw.org"><img style="width: 145px" src="models/ldraw/ldraw_org_logo/Stamp145.png"></a>
  322. <br />
  323. <a href="http://www.ldraw.org/">This software uses the LDraw Parts Library</a>
  324. </center>
  325. </div>
  326. </body>
  327. </html>
粤ICP备19079148号