threejs-lesson-utils.js 7.2 KB

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