threejs-lesson-utils.js 6.6 KB

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