threejs-primitives.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. 'use strict';
  2. function main() {
  3. const primitives = {
  4. BoxBufferGeometry: {
  5. create() {
  6. const width = 8;
  7. const height = 8;
  8. const depth = 8;
  9. return new THREE.BoxBufferGeometry(width, height, depth);
  10. },
  11. },
  12. CircleBufferGeometry: {
  13. create() {
  14. const radius = 7;
  15. const segments = 24;
  16. return new THREE.CircleBufferGeometry(radius, segments);
  17. },
  18. },
  19. ConeBufferGeometry: {
  20. create() {
  21. const radius = 6;
  22. const height = 8;
  23. const segments = 16;
  24. return new THREE.ConeBufferGeometry(radius, height, segments);
  25. },
  26. },
  27. CylinderBufferGeometry: {
  28. create() {
  29. const radiusTop = 4;
  30. const radiusBottom = 4;
  31. const height = 8;
  32. const radialSegments = 12;
  33. return new THREE.CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments);
  34. },
  35. },
  36. DodecahedronBufferGeometry: {
  37. create() {
  38. const radius = 7;
  39. return new THREE.DodecahedronBufferGeometry(radius);
  40. },
  41. },
  42. ExtrudeBufferGeometry: {
  43. create() {
  44. const shape = new THREE.Shape();
  45. const x = -2.5;
  46. const y = -5;
  47. shape.moveTo(x + 2.5, y + 2.5);
  48. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  49. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  50. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  51. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  52. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  53. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  54. const extrudeSettings = {
  55. steps: 2,
  56. depth: 2,
  57. bevelEnabled: true,
  58. bevelThickness: 1,
  59. bevelSize: 1,
  60. bevelSegments: 2,
  61. };
  62. return new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  63. },
  64. },
  65. IcosahedronBufferGeometry: {
  66. create() {
  67. const radius = 7;
  68. return new THREE.IcosahedronBufferGeometry(radius);
  69. },
  70. },
  71. LatheBufferGeometry: {
  72. create() {
  73. const points = [];
  74. for (let i = 0; i < 10; ++i) {
  75. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  76. }
  77. return new THREE.LatheBufferGeometry(points);
  78. },
  79. },
  80. OctahedronBufferGeometry: {
  81. create() {
  82. const radius = 7;
  83. return new THREE.OctahedronBufferGeometry(radius);
  84. },
  85. },
  86. ParametricBufferGeometry: {
  87. create() {
  88. /*
  89. from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  90. The MIT License
  91. Copyright © 2010-2018 three.js authors
  92. Permission is hereby granted, free of charge, to any person obtaining a copy
  93. of this software and associated documentation files (the "Software"), to deal
  94. in the Software without restriction, including without limitation the rights
  95. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  96. copies of the Software, and to permit persons to whom the Software is
  97. furnished to do so, subject to the following conditions:
  98. The above copyright notice and this permission notice shall be included in
  99. all copies or substantial portions of the Software.
  100. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  101. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  102. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  103. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  105. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  106. THE SOFTWARE.
  107. */
  108. function klein(v, u, target) {
  109. u *= Math.PI;
  110. v *= 2 * Math.PI;
  111. u = u * 2;
  112. let x;
  113. let y;
  114. let z;
  115. if (u < Math.PI) {
  116. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(u) * Math.cos(v);
  117. z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v);
  118. } else {
  119. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(v + Math.PI);
  120. z = -8 * Math.sin(u);
  121. }
  122. y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v);
  123. target.set(x, y, z).multiplyScalar(0.75);
  124. }
  125. const slices = 25;
  126. const stacks = 25;
  127. return new THREE.ParametricBufferGeometry(klein, slices, stacks);
  128. },
  129. },
  130. PlaneBufferGeometry: {
  131. create() {
  132. const width = 9;
  133. const height = 9;
  134. const widthSegments = 2;
  135. const heightSegments = 2;
  136. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  137. },
  138. },
  139. PolyhedronBufferGeometry: {
  140. create() {
  141. const verticesOfCube = [
  142. -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1,
  143. -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,
  144. ];
  145. const indicesOfFaces = [
  146. 2, 1, 0, 0, 3, 2,
  147. 0, 4, 7, 7, 3, 0,
  148. 0, 1, 5, 5, 4, 0,
  149. 1, 2, 6, 6, 5, 1,
  150. 2, 3, 7, 7, 6, 2,
  151. 4, 5, 6, 6, 7, 4,
  152. ];
  153. const radius = 7;
  154. const detail = 2;
  155. return new THREE.PolyhedronBufferGeometry(verticesOfCube, indicesOfFaces, radius, detail);
  156. },
  157. },
  158. RingBufferGeometry: {
  159. create() {
  160. const innerRadius = 2;
  161. const outerRadius = 7;
  162. const segments = 18;
  163. return new THREE.RingBufferGeometry(innerRadius, outerRadius, segments);
  164. },
  165. },
  166. ShapeBufferGeometry: {
  167. create() {
  168. const shape = new THREE.Shape();
  169. const x = -2.5;
  170. const y = -5;
  171. shape.moveTo(x + 2.5, y + 2.5);
  172. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  173. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  174. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  175. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  176. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  177. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  178. return new THREE.ShapeBufferGeometry(shape);
  179. },
  180. },
  181. SphereBufferGeometry: {
  182. create() {
  183. const radius = 7;
  184. const widthSegments = 12;
  185. const heightSegments = 8;
  186. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  187. },
  188. },
  189. TetrahedronBufferGeometry: {
  190. create() {
  191. const radius = 7;
  192. return new THREE.TetrahedronBufferGeometry(radius);
  193. },
  194. },
  195. TextBufferGeometry: {
  196. create() {
  197. return new Promise((resolve) => {
  198. const loader = new THREE.FontLoader();
  199. loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
  200. resolve(new THREE.TextBufferGeometry('three.js', {
  201. font: font,
  202. size: 3.0,
  203. height: .2,
  204. curveSegments: 12,
  205. bevelEnabled: true,
  206. bevelThickness: 0.15,
  207. bevelSize: .3,
  208. bevelSegments: 5,
  209. }));
  210. });
  211. });
  212. },
  213. },
  214. TorusBufferGeometry: {
  215. create() {
  216. const radius = 5;
  217. const tubeRadius = 2;
  218. const radialSegments = 8;
  219. const tubularSegments = 24;
  220. return new THREE.TorusBufferGeometry(radius, tubeRadius, radialSegments, tubularSegments);
  221. },
  222. },
  223. TorusKnotBufferGeometry: {
  224. create() {
  225. const radius = 3.5;
  226. const tube = 1.5;
  227. const radialSegments = 8;
  228. const tubularSegments = 64;
  229. const p = 2;
  230. const q = 3;
  231. return new THREE.TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q);
  232. },
  233. },
  234. TubeBufferGeometry: {
  235. create() {
  236. class CustomSinCurve extends THREE.Curve {
  237. constructor(scale) {
  238. super();
  239. this.scale = scale;
  240. }
  241. getPoint(t) {
  242. const tx = t * 3 - 1.5;
  243. const ty = Math.sin(2 * Math.PI * t);
  244. const tz = 0;
  245. return new THREE.Vector3(tx, ty, tz).multiplyScalar(this.scale);
  246. }
  247. }
  248. const path = new CustomSinCurve(4);
  249. const tubularSegments = 20;
  250. const radius = 1;
  251. const radialSegments = 8;
  252. const closed = false;
  253. return new THREE.TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed);
  254. },
  255. },
  256. EdgesGeometry: {
  257. create() {
  258. const width = 8;
  259. const height = 8;
  260. const depth = 8;
  261. return {
  262. lineGeometry: new THREE.EdgesGeometry(new THREE.BoxBufferGeometry(width, height, depth)),
  263. };
  264. },
  265. nonBuffer: false,
  266. },
  267. WireframeGeometry: {
  268. create() {
  269. const width = 8;
  270. const height = 8;
  271. const depth = 8;
  272. return {
  273. lineGeometry: new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(width, height, depth)),
  274. };
  275. },
  276. nonBuffer: false,
  277. },
  278. SphereBufferGeometryLow: {
  279. create() {
  280. const radius = 7;
  281. const widthSegments = 5;
  282. const heightSegments = 3;
  283. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  284. },
  285. },
  286. SphereBufferGeometryMedium: {
  287. create() {
  288. const radius = 7;
  289. const widthSegments = 24;
  290. const heightSegments = 10;
  291. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  292. },
  293. },
  294. SphereBufferGeometryHigh: {
  295. create() {
  296. const radius = 7;
  297. const widthSegments = 50;
  298. const heightSegments = 50;
  299. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  300. },
  301. },
  302. SphereBufferGeometryLowSmooth: {
  303. create() {
  304. const radius = 7;
  305. const widthSegments = 5;
  306. const heightSegments = 3;
  307. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  308. },
  309. showLines: false,
  310. flatShading: false,
  311. },
  312. SphereBufferGeometryMediumSmooth: {
  313. create() {
  314. const radius = 7;
  315. const widthSegments = 24;
  316. const heightSegments = 10;
  317. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  318. },
  319. showLines: false,
  320. flatShading: false,
  321. },
  322. SphereBufferGeometryHighSmooth: {
  323. create() {
  324. const radius = 7;
  325. const widthSegments = 50;
  326. const heightSegments = 50;
  327. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  328. },
  329. showLines: false,
  330. flatShading: false,
  331. },
  332. PlaneBufferGeometryLow: {
  333. create() {
  334. const width = 9;
  335. const height = 9;
  336. const widthSegments = 1;
  337. const heightSegments = 1;
  338. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  339. },
  340. },
  341. PlaneBufferGeometryHigh: {
  342. create() {
  343. const width = 9;
  344. const height = 9;
  345. const widthSegments = 10;
  346. const heightSegments = 10;
  347. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  348. },
  349. },
  350. };
  351. const canvas = document.querySelector('#c');
  352. const renderer = new THREE.WebGLRenderer({canvas: canvas, alpha: true});
  353. function addLink(parent, name) {
  354. const a = document.createElement('a');
  355. a.href = `https://threejs.org/docs/#api/geometries/${name}`;
  356. const code = document.createElement('code');
  357. code.textContent = name;
  358. a.appendChild(code);
  359. parent.appendChild(a);
  360. return a;
  361. }
  362. function addElem(parent, type, className, text) {
  363. const elem = document.createElement(type);
  364. elem.className = className;
  365. if (text) {
  366. elem.textContent = text;
  367. }
  368. parent.appendChild(elem);
  369. return elem;
  370. }
  371. function addDiv(parent, className) {
  372. return addElem(parent, 'div', className);
  373. }
  374. document.querySelectorAll('[data-primitive]').forEach(createPrimitiveDOM);
  375. document.querySelectorAll('[data-primitive-diagram]').forEach(createPrimitiveDiagram);
  376. function createPrimitiveDOM(base) {
  377. const name = base.dataset.primitive;
  378. const info = primitives[name];
  379. if (!info) {
  380. throw new Error(`no primitive ${name}`);
  381. }
  382. const text = base.innerHTML;
  383. base.innerHTML = '';
  384. const elem = addDiv(base, 'shape');
  385. const right = addDiv(base, 'desc');
  386. addLink(right, name);
  387. if (info.nonBuffer !== false) {
  388. addElem(right, 'span', '', ', ');
  389. addLink(right, name.replace('Buffer', ''));
  390. }
  391. addDiv(right, '.note').innerHTML = text;
  392. createPrimitive(elem, info);
  393. }
  394. function createPrimitiveDiagram(base) {
  395. const name = base.dataset.primitiveDiagram;
  396. const info = primitives[name];
  397. if (!info) {
  398. throw new Error(`no primitive ${name}`);
  399. }
  400. createPrimitive(base, info);
  401. }
  402. function createPrimitive(elem, info) {
  403. const geometry = info.create();
  404. const promise = (geometry instanceof Promise) ? geometry : Promise.resolve(geometry);
  405. const scene = new THREE.Scene();
  406. const root = new THREE.Object3D();
  407. scene.add(root);
  408. scene.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444));
  409. const light = new THREE.DirectionalLight(0xffffff, 1);
  410. light.position.set(-1, 2, 4);
  411. scene.add(light);
  412. const fov = 60;
  413. const aspect = 1;
  414. const zNear = 0.1;
  415. const zFar = 50;
  416. const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar);
  417. camera.position.z = 15;
  418. const controls = new THREE.OrbitControls(camera, elem);
  419. controls.enableZoom = false;
  420. controls.enablePan = false;
  421. promise.then((geometryInfo) => {
  422. if (geometryInfo instanceof THREE.BufferGeometry ||
  423. geometryInfo instanceof THREE.Geometry) {
  424. const geometry = geometryInfo;
  425. geometryInfo = {
  426. geometry,
  427. };
  428. }
  429. const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry;
  430. boxGeometry.computeBoundingBox();
  431. const centerOffset = new THREE.Vector3();
  432. boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
  433. if (geometryInfo.geometry) {
  434. const material = new THREE.MeshPhongMaterial({
  435. flatShading: info.flatShading === false ? false : true,
  436. side: THREE.DoubleSide,
  437. });
  438. material.color.setHSL(Math.random(), .5, .5);
  439. const mesh = new THREE.Mesh(geometryInfo.geometry, material);
  440. mesh.position.copy(centerOffset);
  441. root.add(mesh);
  442. }
  443. if (info.showLines !== false) {
  444. const lineMesh = new THREE.LineSegments(
  445. geometryInfo.lineGeometry || geometryInfo.geometry,
  446. new THREE.LineBasicMaterial({
  447. color: geometryInfo.geometry ? 0xffffff : 0x000000,
  448. transparent: true,
  449. opacity: 0.5,
  450. }));
  451. lineMesh.position.copy(centerOffset);
  452. root.add(lineMesh);
  453. }
  454. });
  455. Object.assign(info, {
  456. scene,
  457. root,
  458. elem,
  459. camera,
  460. });
  461. }
  462. const pixelRatio = 2; // even on low-res we want hi-res rendering
  463. function resizeRendererToDisplaySize(renderer) {
  464. const canvas = renderer.domElement;
  465. const width = canvas.clientWidth * pixelRatio;
  466. const height = canvas.clientHeight * pixelRatio;
  467. const needResize = canvas.width !== width || canvas.height !== height;
  468. if (needResize) {
  469. renderer.setSize(width, height, false);
  470. }
  471. return needResize;
  472. }
  473. // Three r93 needs to render at least once for some reason.
  474. const scene = new THREE.Scene();
  475. const camera = new THREE.Camera();
  476. function render(time) {
  477. time *= 0.001;
  478. resizeRendererToDisplaySize(renderer);
  479. renderer.setScissorTest(false);
  480. // renderer.clear();
  481. // Three r93 needs to render at least once for some reason.
  482. renderer.render(scene, camera);
  483. renderer.setScissorTest(true);
  484. for (const info of Object.values(primitives)) {
  485. const {root, scene, camera, elem} = info;
  486. root.rotation.x = time * .1;
  487. root.rotation.y = time * .11;
  488. const rect = elem.getBoundingClientRect();
  489. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  490. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  491. continue;
  492. }
  493. const width = (rect.right - rect.left) * pixelRatio;
  494. const height = (rect.bottom - rect.top) * pixelRatio;
  495. const left = rect.left * pixelRatio;
  496. const top = rect.top * pixelRatio;
  497. const aspect = width / height;
  498. const targetFov = THREE.Math.degToRad(60);
  499. const fov = aspect >= 1
  500. ? targetFov
  501. : (2 * Math.atan(Math.tan(targetFov * .5) / aspect));
  502. camera.fov = THREE.Math.radToDeg(fov);
  503. camera.aspect = aspect;
  504. camera.updateProjectionMatrix();
  505. renderer.setViewport(left, top, width, height);
  506. renderer.setScissor(left, top, width, height);
  507. renderer.render(scene, camera);
  508. }
  509. requestAnimationFrame(render);
  510. }
  511. requestAnimationFrame(render);
  512. }
  513. main();