postprocessing-3dlut-w-loader.html 14 KB

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