postprocessing-3dlut-identity.html 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Three.js - postprocessing - 3DLUT</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. <style>
  8. html, body {
  9. margin: 0;
  10. height: 100%;
  11. }
  12. #c {
  13. width: 100%;
  14. height: 100%;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script type="importmap">
  23. {
  24. "imports": {
  25. "three": "../../build/three.module.js",
  26. "three/addons/": "../../examples/jsm/"
  27. }
  28. }
  29. </script>
  30. <script type="module">
  31. import * as THREE from 'three';
  32. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  33. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  34. import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
  35. import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
  36. import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
  37. import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
  38. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  39. function main() {
  40. const canvas = document.querySelector( '#c' );
  41. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  42. const fov = 45;
  43. const aspect = 2; // the canvas default
  44. const near = 0.1;
  45. const far = 100;
  46. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  47. camera.position.set( 0, 10, 20 );
  48. const controls = new OrbitControls( camera, canvas );
  49. controls.target.set( 0, 5, 0 );
  50. controls.update();
  51. const makeIdentityLutTexture = function () {
  52. const identityLUT = new Uint8Array( [
  53. 0, 0, 0, 255, // black
  54. 255, 0, 0, 255, // red
  55. 0, 0, 255, 255, // blue
  56. 255, 0, 255, 255, // magenta
  57. 0, 255, 0, 255, // green
  58. 255, 255, 0, 255, // yellow
  59. 0, 255, 255, 255, // cyan
  60. 255, 255, 255, 255, // white
  61. ] );
  62. return function ( filter ) {
  63. const texture = new THREE.DataTexture( identityLUT, 4, 2 );
  64. texture.minFilter = filter;
  65. texture.magFilter = filter;
  66. texture.needsUpdate = true;
  67. texture.flipY = false;
  68. return texture;
  69. };
  70. }();
  71. const lutTextures = [
  72. {
  73. name: 'identity',
  74. size: 2,
  75. filter: true,
  76. texture: makeIdentityLutTexture( THREE.LinearFilter ),
  77. },
  78. {
  79. name: 'identity not filtered',
  80. size: 2,
  81. filter: false,
  82. texture: makeIdentityLutTexture( THREE.NearestFilter ),
  83. },
  84. ];
  85. const lutNameIndexMap = {};
  86. lutTextures.forEach( ( info, ndx ) => {
  87. lutNameIndexMap[ info.name ] = ndx;
  88. } );
  89. const lutSettings = {
  90. lut: lutNameIndexMap.identity,
  91. };
  92. const gui = new GUI( { width: 300 } );
  93. gui.add( lutSettings, 'lut', lutNameIndexMap );
  94. const scene = new THREE.Scene();
  95. const sceneBG = new THREE.Scene();
  96. const cameraBG = new THREE.OrthographicCamera( - 1, 1, 1, - 1, - 1, 1 );
  97. let bgMesh;
  98. let bgTexture;
  99. {
  100. const loader = new THREE.TextureLoader();
  101. bgTexture = loader.load( 'resources/images/beach.jpg' );
  102. bgTexture.colorSpace = THREE.SRGBColorSpace;
  103. const planeGeo = new THREE.PlaneGeometry( 2, 2 );
  104. const planeMat = new THREE.MeshBasicMaterial( {
  105. map: bgTexture,
  106. depthTest: false,
  107. } );
  108. bgMesh = new THREE.Mesh( planeGeo, planeMat );
  109. sceneBG.add( bgMesh );
  110. }
  111. function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {
  112. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  113. const halfFovY = THREE.MathUtils.degToRad( camera.fov * .5 );
  114. const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
  115. // compute a unit vector that points in the direction the camera is now
  116. // in the xz plane from the center of the box
  117. const direction = ( new THREE.Vector3() )
  118. .subVectors( camera.position, boxCenter )
  119. .multiply( new THREE.Vector3( 1, 0, 1 ) )
  120. .normalize();
  121. // move the camera to a position distance units way from the center
  122. // in whatever direction the camera was from the center already
  123. camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );
  124. // pick some near and far values for the frustum that
  125. // will contain the box.
  126. camera.near = boxSize / 100;
  127. camera.far = boxSize * 100;
  128. camera.updateProjectionMatrix();
  129. // point the camera to look at the center of the box
  130. camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );
  131. }
  132. {
  133. const gltfLoader = new GLTFLoader();
  134. gltfLoader.load( 'resources/models/3dbustchallange_submission/scene.gltf', ( gltf ) => {
  135. const root = gltf.scene;
  136. scene.add( root );
  137. // fix materials from r114
  138. root.traverse( ( { material } ) => {
  139. if ( material ) {
  140. material.depthWrite = true;
  141. }
  142. } );
  143. root.updateMatrixWorld();
  144. // compute the box that contains all the stuff
  145. // from root and below
  146. const box = new THREE.Box3().setFromObject( root );
  147. const boxSize = box.getSize( new THREE.Vector3() ).length();
  148. const boxCenter = box.getCenter( new THREE.Vector3() );
  149. frameArea( boxSize * 0.4, boxSize, boxCenter, camera );
  150. // update the Trackball controls to handle the new size
  151. controls.maxDistance = boxSize * 10;
  152. controls.target.copy( boxCenter );
  153. controls.update();
  154. } );
  155. }
  156. const lutShader = {
  157. uniforms: {
  158. tDiffuse: { value: null }, // the previous pass's result
  159. lutMap: { value: null },
  160. lutMapSize: { value: 1, },
  161. },
  162. vertexShader: `
  163. varying vec2 vUv;
  164. void main() {
  165. vUv = uv;
  166. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  167. }
  168. `,
  169. fragmentShader: `
  170. #include <common>
  171. #define FILTER_LUT true
  172. uniform sampler2D tDiffuse;
  173. uniform sampler2D lutMap;
  174. uniform float lutMapSize;
  175. varying vec2 vUv;
  176. vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
  177. float sliceSize = 1.0 / size; // space of 1 slice
  178. float slicePixelSize = sliceSize / size; // space of 1 pixel
  179. float width = size - 1.0;
  180. float sliceInnerSize = slicePixelSize * width; // space of size pixels
  181. float zSlice0 = floor( texCoord.z * width);
  182. float zSlice1 = min( zSlice0 + 1.0, width);
  183. float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
  184. float yRange = (texCoord.y * width + 0.5) / size;
  185. float s0 = xOffset + (zSlice0 * sliceSize);
  186. #ifdef FILTER_LUT
  187. float s1 = xOffset + (zSlice1 * sliceSize);
  188. vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
  189. vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
  190. float zOffset = mod(texCoord.z * width, 1.0);
  191. return mix(slice0Color, slice1Color, zOffset);
  192. #else
  193. return texture2D(tex, vec2( s0, yRange));
  194. #endif
  195. }
  196. void main() {
  197. vec4 originalColor = texture2D(tDiffuse, vUv);
  198. gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
  199. }
  200. `,
  201. };
  202. const lutNearestShader = {
  203. uniforms: { ...lutShader.uniforms },
  204. vertexShader: lutShader.vertexShader,
  205. fragmentShader: lutShader.fragmentShader.replace( '#define FILTER_LUT', '//' ),
  206. };
  207. const effectLUT = new ShaderPass( lutShader );
  208. const effectLUTNearest = new ShaderPass( lutNearestShader );
  209. const renderModel = new RenderPass( scene, camera );
  210. renderModel.clear = false; // so we don't clear out the background
  211. const renderBG = new RenderPass( sceneBG, cameraBG );
  212. const outputPass = new OutputPass();
  213. const composer = new EffectComposer( renderer );
  214. composer.addPass( renderBG );
  215. composer.addPass( renderModel );
  216. composer.addPass( effectLUT );
  217. composer.addPass( effectLUTNearest );
  218. composer.addPass( outputPass );
  219. function resizeRendererToDisplaySize( renderer ) {
  220. const canvas = renderer.domElement;
  221. const width = canvas.clientWidth * window.devicePixelRatio | 0;
  222. const height = canvas.clientHeight * window.devicePixelRatio | 0;
  223. const needResize = canvas.width !== width || canvas.height !== height;
  224. if ( needResize ) {
  225. renderer.setSize( width, height, false );
  226. }
  227. return needResize;
  228. }
  229. let then = 0;
  230. function render( now ) {
  231. now *= 0.001; // convert to seconds
  232. const delta = now - then;
  233. then = now;
  234. if ( resizeRendererToDisplaySize( renderer ) ) {
  235. const canvas = renderer.domElement;
  236. const canvasAspect = canvas.clientWidth / canvas.clientHeight;
  237. camera.aspect = canvasAspect;
  238. camera.updateProjectionMatrix();
  239. composer.setSize( canvas.width, canvas.height );
  240. // scale the background plane to keep the image's
  241. // aspect correct.
  242. // Note the image may not have loaded yet.
  243. const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
  244. const aspect = imageAspect / canvasAspect;
  245. bgMesh.scale.x = aspect > 1 ? aspect : 1;
  246. bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;
  247. }
  248. const lutInfo = lutTextures[ lutSettings.lut ];
  249. const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
  250. effectLUT.enabled = lutInfo.filter;
  251. effectLUTNearest.enabled = ! lutInfo.filter;
  252. const lutTexture = lutInfo.texture;
  253. effect.uniforms.lutMap.value = lutTexture;
  254. effect.uniforms.lutMapSize.value = lutInfo.size;
  255. composer.render( delta );
  256. requestAnimationFrame( render );
  257. }
  258. requestAnimationFrame( render );
  259. }
  260. main();
  261. </script>
  262. </html>