postprocessing-3dlut.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. <!-- Import maps polyfill -->
  23. <!-- Remove this when import maps will be widely supported -->
  24. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  25. <script type="importmap">
  26. {
  27. "imports": {
  28. "three": "../../build/three.module.js",
  29. "three/addons/": "../../examples/jsm/"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  37. import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
  38. import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
  39. import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
  40. import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
  41. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  42. function main() {
  43. const canvas = document.querySelector( '#c' );
  44. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  45. const fov = 45;
  46. const aspect = 2; // the canvas default
  47. const near = 0.1;
  48. const far = 100;
  49. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  50. camera.position.set( 0, 10, 20 );
  51. const controls = new OrbitControls( camera, canvas );
  52. controls.target.set( 0, 5, 0 );
  53. controls.update();
  54. const lutTextures = [
  55. { name: 'identity', size: 2, filter: true, },
  56. { name: 'identity no filter', size: 2, filter: false, },
  57. { name: 'custom', url: 'resources/images/lut/3dlut-red-only-s16.png' },
  58. { name: 'monochrome', url: 'resources/images/lut/monochrome-s8.png' },
  59. { name: 'sepia', url: 'resources/images/lut/sepia-s8.png' },
  60. { name: 'saturated', url: 'resources/images/lut/saturated-s8.png', },
  61. { name: 'posterize', url: 'resources/images/lut/posterize-s8n.png', },
  62. { name: 'posterize-3-rgb', url: 'resources/images/lut/posterize-3-rgb-s8n.png', },
  63. { name: 'posterize-3-lab', url: 'resources/images/lut/posterize-3-lab-s8n.png', },
  64. { name: 'posterize-4-lab', url: 'resources/images/lut/posterize-4-lab-s8n.png', },
  65. { name: 'posterize-more', url: 'resources/images/lut/posterize-more-s8n.png', },
  66. { name: 'inverse', url: 'resources/images/lut/inverse-s8.png', },
  67. { name: 'color negative', url: 'resources/images/lut/color-negative-s8.png', },
  68. { name: 'high contrast', url: 'resources/images/lut/high-contrast-bw-s8.png', },
  69. { name: 'funky contrast', url: 'resources/images/lut/funky-contrast-s8.png', },
  70. { name: 'nightvision', url: 'resources/images/lut/nightvision-s8.png', },
  71. { name: 'thermal', url: 'resources/images/lut/thermal-s8.png', },
  72. { name: 'b/w', url: 'resources/images/lut/black-white-s8n.png', },
  73. { name: 'hue +60', url: 'resources/images/lut/hue-plus-60-s8.png', },
  74. { name: 'hue +180', url: 'resources/images/lut/hue-plus-180-s8.png', },
  75. { name: 'hue -60', url: 'resources/images/lut/hue-minus-60-s8.png', },
  76. { name: 'red to cyan', url: 'resources/images/lut/red-to-cyan-s8.png' },
  77. { name: 'blues', url: 'resources/images/lut/blues-s8.png' },
  78. { name: 'infrared', url: 'resources/images/lut/infrared-s8.png' },
  79. { name: 'radioactive', url: 'resources/images/lut/radioactive-s8.png' },
  80. { name: 'goolgey', url: 'resources/images/lut/googley-s8.png' },
  81. { name: 'bgy', url: 'resources/images/lut/bgy-s8.png' },
  82. ];
  83. const makeIdentityLutTexture = function () {
  84. const identityLUT = new Uint8Array( [
  85. 0, 0, 0, 255, // black
  86. 255, 0, 0, 255, // red
  87. 0, 0, 255, 255, // blue
  88. 255, 0, 255, 255, // magenta
  89. 0, 255, 0, 255, // green
  90. 255, 255, 0, 255, // yellow
  91. 0, 255, 255, 255, // cyan
  92. 255, 255, 255, 255, // white
  93. ] );
  94. return function ( filter ) {
  95. const texture = new THREE.DataTexture( identityLUT, 4, 2 );
  96. texture.minFilter = texture.magFilter = filter ? THREE.LinearFilter : THREE.NearestFilter;
  97. texture.needsUpdate = true;
  98. texture.flipY = false;
  99. return texture;
  100. };
  101. }();
  102. const makeLUTTexture = function () {
  103. const imgLoader = new THREE.ImageLoader();
  104. const ctx = document.createElement( 'canvas' ).getContext( '2d' );
  105. return function ( info ) {
  106. const lutSize = info.size;
  107. const width = lutSize * lutSize;
  108. const height = lutSize;
  109. const texture = new THREE.DataTexture( new Uint8Array( width * height ), width, height );
  110. texture.minFilter = texture.magFilter = info.filter ? THREE.LinearFilter : THREE.NearestFilter;
  111. texture.flipY = false;
  112. if ( info.url ) {
  113. imgLoader.load( info.url, function ( image ) {
  114. ctx.canvas.width = width;
  115. ctx.canvas.height = height;
  116. ctx.drawImage( image, 0, 0 );
  117. const imageData = ctx.getImageData( 0, 0, width, height );
  118. texture.image.data = new Uint8Array( imageData.data.buffer );
  119. texture.image.width = width;
  120. texture.image.height = height;
  121. texture.needsUpdate = true;
  122. } );
  123. }
  124. return texture;
  125. };
  126. }();
  127. lutTextures.forEach( ( info ) => {
  128. // if not size set get it from the filename
  129. if ( ! info.size ) {
  130. // assumes filename ends in '-s<num>[n]'
  131. // where <num> is the size of the 3DLUT cube
  132. // and [n] means 'no filtering' or 'nearest'
  133. //
  134. // examples:
  135. // 'foo-s16.png' = size:16, filter: true
  136. // 'bar-s8n.png' = size:8, filter: false
  137. const m = /-s(\d+)(n*)\.[^.]+$/.exec( info.url );
  138. if ( m ) {
  139. info.size = parseInt( m[ 1 ] );
  140. info.filter = info.filter === undefined ? m[ 2 ] !== 'n' : info.filter;
  141. }
  142. info.texture = makeLUTTexture( info );
  143. } else {
  144. info.texture = makeIdentityLutTexture( info.filter );
  145. }
  146. } );
  147. const lutNameIndexMap = {};
  148. lutTextures.forEach( ( info, ndx ) => {
  149. lutNameIndexMap[ info.name ] = ndx;
  150. } );
  151. const lutSettings = {
  152. lut: lutNameIndexMap.custom,
  153. };
  154. const gui = new GUI( { width: 300 } );
  155. gui.add( lutSettings, 'lut', lutNameIndexMap );
  156. const scene = new THREE.Scene();
  157. const sceneBG = new THREE.Scene();
  158. const cameraBG = new THREE.OrthographicCamera( - 1, 1, 1, - 1, - 1, 1 );
  159. let bgMesh;
  160. let bgTexture;
  161. {
  162. const loader = new THREE.TextureLoader();
  163. bgTexture = loader.load( 'resources/images/beach.jpg' );
  164. bgTexture.colorSpace = THREE.SRGBColorSpace;
  165. const planeGeo = new THREE.PlaneGeometry( 2, 2 );
  166. const planeMat = new THREE.MeshBasicMaterial( {
  167. map: bgTexture,
  168. depthTest: false,
  169. } );
  170. bgMesh = new THREE.Mesh( planeGeo, planeMat );
  171. sceneBG.add( bgMesh );
  172. }
  173. function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {
  174. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  175. const halfFovY = THREE.MathUtils.degToRad( camera.fov * .5 );
  176. const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
  177. // compute a unit vector that points in the direction the camera is now
  178. // in the xz plane from the center of the box
  179. const direction = ( new THREE.Vector3() )
  180. .subVectors( camera.position, boxCenter )
  181. .multiply( new THREE.Vector3( 1, 0, 1 ) )
  182. .normalize();
  183. // move the camera to a position distance units way from the center
  184. // in whatever direction the camera was from the center already
  185. camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );
  186. // pick some near and far values for the frustum that
  187. // will contain the box.
  188. camera.near = boxSize / 100;
  189. camera.far = boxSize * 100;
  190. camera.updateProjectionMatrix();
  191. // point the camera to look at the center of the box
  192. camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );
  193. }
  194. {
  195. const gltfLoader = new GLTFLoader();
  196. gltfLoader.load( 'resources/models/3dbustchallange_submission/scene.gltf', ( gltf ) => {
  197. const root = gltf.scene;
  198. scene.add( root );
  199. // fix materials from r114
  200. root.traverse( ( { material } ) => {
  201. if ( material ) {
  202. material.depthWrite = true;
  203. }
  204. } );
  205. root.updateMatrixWorld();
  206. // compute the box that contains all the stuff
  207. // from root and below
  208. const box = new THREE.Box3().setFromObject( root );
  209. const boxSize = box.getSize( new THREE.Vector3() ).length();
  210. const boxCenter = box.getCenter( new THREE.Vector3() );
  211. frameArea( boxSize * 0.4, boxSize, boxCenter, camera );
  212. // update the Trackball controls to handle the new size
  213. controls.maxDistance = boxSize * 10;
  214. controls.target.copy( boxCenter );
  215. controls.update();
  216. } );
  217. }
  218. const lutShader = {
  219. uniforms: {
  220. tDiffuse: { value: null },
  221. lutMap: { value: null },
  222. lutMapSize: { value: 1, },
  223. },
  224. vertexShader: `
  225. varying vec2 vUv;
  226. void main() {
  227. vUv = uv;
  228. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  229. }
  230. `,
  231. fragmentShader: `
  232. #include <common>
  233. #define FILTER_LUT true
  234. uniform sampler2D tDiffuse;
  235. uniform sampler2D lutMap;
  236. uniform float lutMapSize;
  237. varying vec2 vUv;
  238. vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
  239. float sliceSize = 1.0 / size; // space of 1 slice
  240. float slicePixelSize = sliceSize / size; // space of 1 pixel
  241. float width = size - 1.0;
  242. float sliceInnerSize = slicePixelSize * width; // space of size pixels
  243. float zSlice0 = floor( texCoord.z * width);
  244. float zSlice1 = min( zSlice0 + 1.0, width);
  245. float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
  246. float yRange = (texCoord.y * width + 0.5) / size;
  247. float s0 = xOffset + (zSlice0 * sliceSize);
  248. #ifdef FILTER_LUT
  249. float s1 = xOffset + (zSlice1 * sliceSize);
  250. vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
  251. vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
  252. float zOffset = mod(texCoord.z * width, 1.0);
  253. return mix(slice0Color, slice1Color, zOffset);
  254. #else
  255. return texture2D(tex, vec2( s0, yRange));
  256. #endif
  257. }
  258. void main() {
  259. vec4 originalColor = texture2D(tDiffuse, vUv);
  260. gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
  261. }
  262. `,
  263. };
  264. const lutNearestShader = {
  265. uniforms: { ...lutShader.uniforms },
  266. vertexShader: lutShader.vertexShader,
  267. fragmentShader: lutShader.fragmentShader.replace( '#define FILTER_LUT', '//' ),
  268. };
  269. const effectLUT = new ShaderPass( lutShader );
  270. const effectLUTNearest = new ShaderPass( lutNearestShader );
  271. const renderModel = new RenderPass( scene, camera );
  272. renderModel.clear = false; // so we don't clear out the background
  273. const renderBG = new RenderPass( sceneBG, cameraBG );
  274. const outputPass = new OutputPass();
  275. const composer = new EffectComposer( renderer );
  276. composer.addPass( renderBG );
  277. composer.addPass( renderModel );
  278. composer.addPass( effectLUT );
  279. composer.addPass( effectLUTNearest );
  280. composer.addPass( outputPass );
  281. function resizeRendererToDisplaySize( renderer ) {
  282. const canvas = renderer.domElement;
  283. const width = canvas.clientWidth * window.devicePixelRatio | 0;
  284. const height = canvas.clientHeight * window.devicePixelRatio | 0;
  285. const needResize = canvas.width !== width || canvas.height !== height;
  286. if ( needResize ) {
  287. renderer.setSize( width, height, false );
  288. }
  289. return needResize;
  290. }
  291. let then = 0;
  292. function render( now ) {
  293. now *= 0.001; // convert to seconds
  294. const delta = now - then;
  295. then = now;
  296. if ( resizeRendererToDisplaySize( renderer ) ) {
  297. const canvas = renderer.domElement;
  298. const canvasAspect = canvas.clientWidth / canvas.clientHeight;
  299. camera.aspect = canvasAspect;
  300. camera.updateProjectionMatrix();
  301. composer.setSize( canvas.width, canvas.height );
  302. // scale the background plane to keep the image's
  303. // aspect correct.
  304. // Note the image may not have loaded yet.
  305. const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
  306. const aspect = imageAspect / canvasAspect;
  307. bgMesh.scale.x = aspect > 1 ? aspect : 1;
  308. bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;
  309. }
  310. const lutInfo = lutTextures[ lutSettings.lut ];
  311. const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
  312. effectLUT.enabled = lutInfo.filter;
  313. effectLUTNearest.enabled = ! lutInfo.filter;
  314. const lutTexture = lutInfo.texture;
  315. effect.uniforms.lutMap.value = lutTexture;
  316. effect.uniforms.lutMapSize.value = lutInfo.size;
  317. composer.render( delta );
  318. requestAnimationFrame( render );
  319. }
  320. requestAnimationFrame( render );
  321. }
  322. main();
  323. </script>
  324. </html>