threejs-lesson-utils.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. 'use strict';
  2. window.threejsLessonUtils = {
  3. init() {
  4. if (this.renderer) {
  5. return;
  6. }
  7. const canvas = document.querySelector('#c');
  8. const renderer = new THREE.WebGLRenderer({
  9. canvas: canvas,
  10. alpha: true,
  11. powerPreference: 'low-power',
  12. });
  13. this.pixelRatio = Math.max(2, window.devicePixelRatio);
  14. this.renderer = renderer;
  15. this.renderFuncs = [];
  16. const resizeRendererToDisplaySize = (renderer) => {
  17. const canvas = renderer.domElement;
  18. const width = canvas.clientWidth * this.pixelRatio;
  19. const height = canvas.clientHeight * this.pixelRatio;
  20. const needResize = canvas.width !== width || canvas.height !== height;
  21. if (needResize) {
  22. renderer.setSize(width, height, false);
  23. }
  24. return needResize;
  25. };
  26. // Three r93 needs to render at least once for some reason.
  27. const scene = new THREE.Scene();
  28. const camera = new THREE.Camera();
  29. const render = (time) => {
  30. time *= 0.001;
  31. resizeRendererToDisplaySize(renderer);
  32. renderer.setScissorTest(false);
  33. // Three r93 needs to render at least once for some reason.
  34. renderer.render(scene, camera);
  35. renderer.setScissorTest(true);
  36. // maybe there is another way. Originally I used `position: fixed`
  37. // but the problem is if we can't render as fast as the browser
  38. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  39. // horrible but iOS would often been 1/2 a second or worse.
  40. // By doing it this way the canvas will scroll which means the
  41. // worse that happens is part of the shapes scrolling on don't
  42. // get drawn for a few frames but the shapes that are on the screen
  43. // scroll perfectly.
  44. //
  45. // I'm using `transform` on the voodoo that it doesn't affect
  46. // layout as much as `top` since AFAIK setting `top` is in
  47. // the flow but `transform` is not though thinking about it
  48. // the given we're `position: absolute` maybe there's no difference?
  49. const transform = `translateY(${window.scrollY}px)`;
  50. renderer.domElement.style.transform = transform;
  51. this.renderFuncs.forEach((fn) => {
  52. fn(renderer, time);
  53. });
  54. requestAnimationFrame(render);
  55. };
  56. requestAnimationFrame(render);
  57. },
  58. addDiagrams(diagrams) {
  59. [...document.querySelectorAll('[data-diagram]')].forEach((elem) => {
  60. const name = elem.dataset.diagram;
  61. const info = diagrams[name];
  62. if (!info) {
  63. throw new Error(`no diagram: ${name}`);
  64. }
  65. this.addDiagram(elem, info);
  66. });
  67. },
  68. addDiagram(elem, info) {
  69. this.init();
  70. const scene = new THREE.Scene();
  71. let targetFOVDeg = 60;
  72. const aspect = 1;
  73. const near = 0.1;
  74. const far = 50;
  75. let camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, near, far);
  76. camera.position.z = 15;
  77. scene.add(camera);
  78. const root = new THREE.Object3D();
  79. scene.add(root);
  80. const renderInfo = {
  81. pixelRatio: this.pixelRatio,
  82. camera,
  83. scene,
  84. root,
  85. renderer: this.renderer,
  86. elem,
  87. };
  88. const obj3D = info.create({scene, camera, renderInfo});
  89. const promise = (obj3D instanceof Promise) ? obj3D : Promise.resolve(obj3D);
  90. const updateFunctions = [];
  91. const resizeFunctions = [];
  92. const settings = {
  93. lights: true,
  94. trackball: true,
  95. // resize(renderInfo) {
  96. // },
  97. // update(time, renderInfo) {
  98. // },
  99. render(renderInfo) {
  100. renderInfo.renderer.render(renderInfo.scene, renderInfo.camera);
  101. },
  102. };
  103. promise.then((result) => {
  104. const info = result instanceof THREE.Object3D ? {
  105. obj3D: result,
  106. } : result;
  107. if (info.obj3D) {
  108. root.add(info.obj3D);
  109. }
  110. if (info.update) {
  111. updateFunctions.push(info.update);
  112. }
  113. if (info.resize) {
  114. resizeFunctions.push(info.resize);
  115. }
  116. if (info.camera) {
  117. camera = info.camera;
  118. renderInfo.camera = camera;
  119. }
  120. Object.assign(settings, info);
  121. targetFOVDeg = camera.fov;
  122. if (settings.trackball !== false) {
  123. const controls = new THREE.TrackballControls(camera, elem);
  124. controls.noZoom = true;
  125. controls.noPan = true;
  126. resizeFunctions.push(controls.handleResize.bind(controls));
  127. updateFunctions.push(controls.update.bind(controls));
  128. }
  129. // add the lights as children of the camera.
  130. // this is because TrackbacllControls move the camera.
  131. // We really want to rotate the object itself but there's no
  132. // controls for that so we fake it by putting all the lights
  133. // on the camera so they move with it.
  134. if (settings.lights !== false) {
  135. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  136. const light = new THREE.DirectionalLight(0xffffff, 1);
  137. light.position.set(-1, 2, 4 - 15);
  138. camera.add(light);
  139. }
  140. });
  141. let oldWidth = -1;
  142. let oldHeight = -1;
  143. const render = (renderer, time) => {
  144. root.rotation.x = time * .1;
  145. root.rotation.y = time * .11;
  146. const rect = elem.getBoundingClientRect();
  147. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  148. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  149. return;
  150. }
  151. renderInfo.width = (rect.right - rect.left) * this.pixelRatio;
  152. renderInfo.height = (rect.bottom - rect.top) * this.pixelRatio;
  153. renderInfo.left = rect.left * this.pixelRatio;
  154. renderInfo.top = rect.top * this.pixelRatio;
  155. if (renderInfo.width !== oldWidth || renderInfo.height !== oldHeight) {
  156. oldWidth = renderInfo.width;
  157. oldHeight = renderInfo.height;
  158. resizeFunctions.forEach(fn => fn(renderInfo));
  159. }
  160. updateFunctions.forEach(fn => fn(time, renderInfo));
  161. const aspect = renderInfo.width / renderInfo.height;
  162. const fovDeg = aspect >= 1
  163. ? targetFOVDeg
  164. : THREE.Math.radToDeg(2 * Math.atan(Math.tan(THREE.Math.degToRad(targetFOVDeg) * .5) / aspect));
  165. camera.fov = fovDeg;
  166. camera.aspect = aspect;
  167. camera.updateProjectionMatrix();
  168. renderer.setViewport(renderInfo.left, renderInfo.top, renderInfo.width, renderInfo.height);
  169. renderer.setScissor(renderInfo.left, renderInfo.top, renderInfo.width, renderInfo.height);
  170. settings.render(renderInfo);
  171. };
  172. this.renderFuncs.push(render);
  173. },
  174. };