threejs-lesson-utils.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import * as THREE from 'three';
  2. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  3. export const threejsLessonUtils = {
  4. _afterPrettifyFuncs: [],
  5. init(options = {threejsOptions:{}}) {
  6. if (this.renderer) {
  7. return;
  8. }
  9. const canvas = document.createElement('canvas');
  10. canvas.id = 'c';
  11. document.body.appendChild(canvas);
  12. const renderer = new THREE.WebGLRenderer({
  13. canvas,
  14. alpha: true,
  15. powerPreference: 'low-power',
  16. ...options.threejsOptions,
  17. });
  18. this.pixelRatio = window.devicePixelRatio;
  19. this.renderer = renderer;
  20. this.elemToRenderFuncMap = new Map();
  21. const resizeRendererToDisplaySize = (renderer) => {
  22. const canvas = renderer.domElement;
  23. const width = canvas.clientWidth * this.pixelRatio | 0;
  24. const height = canvas.clientHeight * this.pixelRatio | 0;
  25. const needResize = canvas.width !== width || canvas.height !== height;
  26. if (needResize) {
  27. renderer.setSize(width, height, false);
  28. }
  29. return needResize;
  30. };
  31. const clearColor = new THREE.Color('#000');
  32. let needsUpdate = true;
  33. let rafRequestId;
  34. let rafRunning;
  35. const render = (time) => {
  36. rafRequestId = undefined;
  37. time *= 0.001;
  38. const resized = resizeRendererToDisplaySize(renderer);
  39. // only update if we drew last time
  40. // so the browser will not recomposite the page
  41. // of nothing is being drawn.
  42. if (needsUpdate) {
  43. needsUpdate = false;
  44. renderer.setScissorTest(false);
  45. renderer.setClearColor(clearColor, 0);
  46. renderer.clear(true, true);
  47. renderer.setScissorTest(true);
  48. }
  49. this.elementsOnScreen.forEach(elem => {
  50. const fn = this.elemToRenderFuncMap.get(elem);
  51. const wasRendered = fn(renderer, time, resized);
  52. needsUpdate = needsUpdate || wasRendered;
  53. });
  54. if (needsUpdate) {
  55. // maybe there is another way. Originally I used `position: fixed`
  56. // but the problem is if we can't render as fast as the browser
  57. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  58. // horrible but iOS would often been 1/2 a second or worse.
  59. // By doing it this way the canvas will scroll which means the
  60. // worse that happens is part of the shapes scrolling on don't
  61. // get drawn for a few frames but the shapes that are on the screen
  62. // scroll perfectly.
  63. //
  64. // I'm using `transform` on the voodoo that it doesn't affect
  65. // layout as much as `top` since AFAIK setting `top` is in
  66. // the flow but `transform` is not though thinking about it
  67. // the given we're `position: absolute` maybe there's no difference?
  68. const transform = `translateY(${window.scrollY}px)`;
  69. renderer.domElement.style.transform = transform;
  70. }
  71. if (rafRunning) {
  72. startRAFLoop();
  73. }
  74. };
  75. function startRAFLoop() {
  76. rafRunning = true;
  77. if (!rafRequestId) {
  78. rafRequestId = requestAnimationFrame(render);
  79. }
  80. }
  81. this.elementsOnScreen = new Set();
  82. this.intersectionObserver = new IntersectionObserver((entries) => {
  83. entries.forEach(entry => {
  84. if (entry.isIntersecting) {
  85. this.elementsOnScreen.add(entry.target);
  86. } else {
  87. this.elementsOnScreen.delete(entry.target);
  88. }
  89. // Each entry describes an intersection change for one observed
  90. // target element:
  91. // entry.boundingClientRect
  92. // entry.intersectionRatio
  93. // entry.intersectionRect
  94. // entry.isIntersecting
  95. // entry.rootBounds
  96. // entry.target
  97. // entry.time
  98. });
  99. if (this.elementsOnScreen.size > 0) {
  100. startRAFLoop();
  101. } else {
  102. rafRunning = false;
  103. }
  104. });
  105. },
  106. addDiagrams(diagrams) {
  107. [...document.querySelectorAll('[data-diagram]')].forEach((elem) => {
  108. const name = elem.dataset.diagram;
  109. const info = diagrams[name];
  110. if (!info) {
  111. throw new Error(`no diagram: ${name}`);
  112. }
  113. this.addDiagram(elem, info);
  114. });
  115. },
  116. addDiagram(elem, info) {
  117. this.init();
  118. const scene = new THREE.Scene();
  119. let targetFOVDeg = 60;
  120. const aspect = 1;
  121. const near = 0.1;
  122. const far = 50;
  123. let camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, near, far);
  124. camera.position.z = 15;
  125. scene.add(camera);
  126. const root = new THREE.Object3D();
  127. scene.add(root);
  128. const renderInfo = {
  129. pixelRatio: this.pixelRatio,
  130. camera,
  131. scene,
  132. root,
  133. renderer: this.renderer,
  134. elem,
  135. };
  136. const obj3D = info.create({scene, camera, renderInfo});
  137. const promise = (obj3D instanceof Promise) ? obj3D : Promise.resolve(obj3D);
  138. const updateFunctions = [];
  139. const resizeFunctions = [];
  140. const settings = {
  141. lights: true,
  142. trackball: true,
  143. // resize(renderInfo) {
  144. // },
  145. // update(time, renderInfo) {
  146. // },
  147. render(renderInfo) {
  148. renderInfo.renderer.render(renderInfo.scene, renderInfo.camera);
  149. },
  150. };
  151. promise.then((result) => {
  152. const info = result instanceof THREE.Object3D ? {
  153. obj3D: result,
  154. } : result;
  155. if (info.obj3D) {
  156. root.add(info.obj3D);
  157. }
  158. if (info.update) {
  159. updateFunctions.push(info.update);
  160. }
  161. if (info.resize) {
  162. resizeFunctions.push(info.resize);
  163. }
  164. if (info.camera) {
  165. camera = info.camera;
  166. renderInfo.camera = camera;
  167. }
  168. Object.assign(settings, info);
  169. targetFOVDeg = camera.fov;
  170. if (settings.trackball !== false) {
  171. const controls = new OrbitControls(camera, elem);
  172. controls.rotateSpeed = 1 / 6;
  173. controls.enableZoom = false;
  174. controls.enablePan = false;
  175. elem.removeAttribute('tabIndex');
  176. //resizeFunctions.push(controls.handleResize.bind(controls));
  177. updateFunctions.push(controls.update.bind(controls));
  178. }
  179. // add the lights as children of the camera.
  180. // this is because TrackballControls move the camera.
  181. // We really want to rotate the object itself but there's no
  182. // controls for that so we fake it by putting all the lights
  183. // on the camera so they move with it.
  184. if (settings.lights !== false) {
  185. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  186. const light = new THREE.DirectionalLight(0xffffff, 1);
  187. light.position.set(-1, 2, 4 - 15);
  188. camera.add(light);
  189. }
  190. });
  191. let oldWidth = -1;
  192. let oldHeight = -1;
  193. const render = (renderer, time) => {
  194. root.rotation.x = time * .1;
  195. root.rotation.y = time * .11;
  196. const rect = elem.getBoundingClientRect();
  197. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  198. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  199. return false;
  200. }
  201. renderInfo.width = rect.width * this.pixelRatio;
  202. renderInfo.height = rect.height * this.pixelRatio;
  203. renderInfo.left = rect.left * this.pixelRatio;
  204. renderInfo.bottom = (renderer.domElement.clientHeight - rect.bottom) * this.pixelRatio;
  205. if (renderInfo.width !== oldWidth || renderInfo.height !== oldHeight) {
  206. oldWidth = renderInfo.width;
  207. oldHeight = renderInfo.height;
  208. resizeFunctions.forEach(fn => fn(renderInfo));
  209. }
  210. updateFunctions.forEach(fn => fn(time, renderInfo));
  211. const aspect = renderInfo.width / renderInfo.height;
  212. const fovDeg = aspect >= 1
  213. ? targetFOVDeg
  214. : THREE.MathUtils.radToDeg(2 * Math.atan(Math.tan(THREE.MathUtils.degToRad(targetFOVDeg) * .5) / aspect));
  215. camera.fov = fovDeg;
  216. camera.aspect = aspect;
  217. camera.updateProjectionMatrix();
  218. renderer.setViewport(renderInfo.left, renderInfo.bottom, renderInfo.width, renderInfo.height);
  219. renderer.setScissor(renderInfo.left, renderInfo.bottom, renderInfo.width, renderInfo.height);
  220. settings.render(renderInfo);
  221. return true;
  222. };
  223. this.intersectionObserver.observe(elem);
  224. this.elemToRenderFuncMap.set(elem, render);
  225. },
  226. onAfterPrettify(fn) {
  227. this._afterPrettifyFuncs.push(fn);
  228. },
  229. afterPrettify() {
  230. this._afterPrettifyFuncs.forEach((fn) => {
  231. fn();
  232. });
  233. },
  234. };
  235. window.threejsLessonUtils = threejsLessonUtils;