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

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