threejs-lesson-utils.js 6.8 KB

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