threejs-primitives.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. import * as THREE from '../../resources/threejs/r115/build/three.module.js';
  2. import {threejsLessonUtils} from './threejs-lesson-utils.js';
  3. {
  4. const darkColors = {
  5. lines: '#DDD',
  6. };
  7. const lightColors = {
  8. lines: '#000',
  9. };
  10. const darkMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  11. const isDarkMode = darkMatcher.matches;
  12. const colors = isDarkMode ? darkColors : lightColors;
  13. const fontLoader = new THREE.FontLoader();
  14. const fontPromise = new Promise((resolve) => {
  15. fontLoader.load('/threejs/resources/threejs/fonts/helvetiker_regular.typeface.json', resolve);
  16. });
  17. const diagrams = {
  18. BoxBufferGeometry: {
  19. ui: {
  20. width: { type: 'range', min: 1, max: 10, precision: 1, },
  21. height: { type: 'range', min: 1, max: 10, precision: 1, },
  22. depth: { type: 'range', min: 1, max: 10, precision: 1, },
  23. widthSegments: { type: 'range', min: 1, max: 10, },
  24. heightSegments: { type: 'range', min: 1, max: 10, },
  25. depthSegments: { type: 'range', min: 1, max: 10, },
  26. },
  27. create(width = 8, height = 8, depth = 8) {
  28. return new THREE.BoxBufferGeometry(width, height, depth);
  29. },
  30. create2(width = 8, height = 8, depth = 8, widthSegments = 4, heightSegments = 4, depthSegments = 4) {
  31. return new THREE.BoxBufferGeometry(
  32. width, height, depth,
  33. widthSegments, heightSegments, depthSegments);
  34. },
  35. },
  36. CircleBufferGeometry: {
  37. ui: {
  38. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  39. segments: { type: 'range', min: 1, max: 50, },
  40. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  41. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  42. },
  43. create(radius = 7, segments = 24) {
  44. return new THREE.CircleBufferGeometry(radius, segments);
  45. },
  46. create2(radius = 7, segments = 24, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  47. return new THREE.CircleBufferGeometry(
  48. radius, segments, thetaStart, thetaLength);
  49. },
  50. },
  51. ConeBufferGeometry: {
  52. ui: {
  53. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  54. height: { type: 'range', min: 1, max: 10, precision: 1, },
  55. radialSegments: { type: 'range', min: 1, max: 50, },
  56. heightSegments: { type: 'range', min: 1, max: 10, },
  57. openEnded: { type: 'bool', },
  58. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  59. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  60. },
  61. create(radius = 6, height = 8, radialSegments = 16) {
  62. return new THREE.ConeBufferGeometry(radius, height, radialSegments);
  63. },
  64. create2(radius = 6, height = 8, radialSegments = 16, heightSegments = 2, openEnded = true, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  65. return new THREE.ConeBufferGeometry(
  66. radius, height,
  67. radialSegments, heightSegments,
  68. openEnded,
  69. thetaStart, thetaLength);
  70. },
  71. },
  72. CylinderBufferGeometry: {
  73. ui: {
  74. radiusTop: { type: 'range', min: 0, max: 10, precision: 1, },
  75. radiusBottom: { type: 'range', min: 0, max: 10, precision: 1, },
  76. height: { type: 'range', min: 1, max: 10, precision: 1, },
  77. radialSegments: { type: 'range', min: 1, max: 50, },
  78. heightSegments: { type: 'range', min: 1, max: 10, },
  79. openEnded: { type: 'bool', },
  80. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  81. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  82. },
  83. create(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12) {
  84. return new THREE.CylinderBufferGeometry(
  85. radiusTop, radiusBottom, height, radialSegments);
  86. },
  87. create2(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12, heightSegments = 2, openEnded = false, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  88. return new THREE.CylinderBufferGeometry(
  89. radiusTop, radiusBottom, height,
  90. radialSegments, heightSegments,
  91. openEnded,
  92. thetaStart, thetaLength);
  93. },
  94. },
  95. DodecahedronBufferGeometry: {
  96. ui: {
  97. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  98. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  99. },
  100. create(radius = 7) {
  101. return new THREE.DodecahedronBufferGeometry(radius);
  102. },
  103. create2(radius = 7, detail = 2) {
  104. return new THREE.DodecahedronBufferGeometry(radius, detail);
  105. },
  106. },
  107. ExtrudeBufferGeometry: {
  108. ui: {
  109. steps: { type: 'range', min: 1, max: 10, },
  110. depth: { type: 'range', min: 1, max: 20, precision: 1, },
  111. bevelEnabled: { type: 'bool', },
  112. bevelThickness: { type: 'range', min: 0.1, max: 3, },
  113. bevelSize: { type: 'range', min: 0.1, max:3, },
  114. bevelSegments: { type: 'range', min: 0, max: 8, },
  115. },
  116. addConstCode: false,
  117. create(steps = 2, depth = 2, bevelEnabled = true, bevelThickness = 1, bevelSize = 1, bevelSegments = 2) {
  118. const shape = new THREE.Shape();
  119. const x = -2.5;
  120. const y = -5;
  121. shape.moveTo(x + 2.5, y + 2.5);
  122. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  123. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  124. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  125. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  126. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  127. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  128. const extrudeSettings = {
  129. steps,
  130. depth,
  131. bevelEnabled,
  132. bevelThickness,
  133. bevelSize,
  134. bevelSegments,
  135. };
  136. const geometry = new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  137. return geometry;
  138. },
  139. src: `
  140. const shape = new THREE.Shape();
  141. const x = -2.5;
  142. const y = -5;
  143. shape.moveTo(x + 2.5, y + 2.5);
  144. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  145. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  146. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  147. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  148. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  149. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  150. const extrudeSettings = {
  151. steps: 2, // ui: steps
  152. depth: 2, // ui: depth
  153. bevelEnabled: true, // ui: bevelEnabled
  154. bevelThickness: 1, // ui: bevelThickness
  155. bevelSize: 1, // ui: bevelSize
  156. bevelSegments: 2, // ui: bevelSegments
  157. };
  158. const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  159. `,
  160. },
  161. IcosahedronBufferGeometry: {
  162. ui: {
  163. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  164. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  165. },
  166. create(radius = 7) {
  167. return new THREE.IcosahedronBufferGeometry(radius);
  168. },
  169. create2(radius = 7, detail = 2) {
  170. return new THREE.IcosahedronBufferGeometry(radius, detail);
  171. },
  172. },
  173. LatheBufferGeometry: {
  174. ui: {
  175. segments: { type: 'range', min: 1, max: 50, },
  176. phiStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  177. phiLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  178. },
  179. create() {
  180. const points = [];
  181. for (let i = 0; i < 10; ++i) {
  182. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  183. }
  184. return new THREE.LatheBufferGeometry(points);
  185. },
  186. create2(segments = 12, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5) {
  187. const points = [];
  188. for (let i = 0; i < 10; ++i) {
  189. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  190. }
  191. return new THREE.LatheBufferGeometry(
  192. points, segments, phiStart, phiLength);
  193. },
  194. },
  195. OctahedronBufferGeometry: {
  196. ui: {
  197. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  198. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  199. },
  200. create(radius = 7) {
  201. return new THREE.OctahedronBufferGeometry(radius);
  202. },
  203. create2(radius = 7, detail = 2) {
  204. return new THREE.OctahedronBufferGeometry(radius, detail);
  205. },
  206. },
  207. ParametricBufferGeometry: {
  208. ui: {
  209. stacks: { type: 'range', min: 1, max: 50, },
  210. slices: { type: 'range', min: 1, max: 50, },
  211. },
  212. /*
  213. from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  214. The MIT License
  215. Copyright © 2010-2018 three.js authors
  216. Permission is hereby granted, free of charge, to any person obtaining a copy
  217. of this software and associated documentation files (the "Software"), to deal
  218. in the Software without restriction, including without limitation the rights
  219. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  220. copies of the Software, and to permit persons to whom the Software is
  221. furnished to do so, subject to the following conditions:
  222. The above copyright notice and this permission notice shall be included in
  223. all copies or substantial portions of the Software.
  224. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  225. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  226. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  227. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  228. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  229. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  230. THE SOFTWARE.
  231. */
  232. create(slices = 25, stacks = 25) {
  233. // from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  234. function klein(v, u, target) {
  235. u *= Math.PI;
  236. v *= 2 * Math.PI;
  237. u = u * 2;
  238. let x;
  239. let z;
  240. if (u < Math.PI) {
  241. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(u) * Math.cos(v);
  242. z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v);
  243. } else {
  244. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(v + Math.PI);
  245. z = -8 * Math.sin(u);
  246. }
  247. const y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v);
  248. target.set(x, y, z).multiplyScalar(0.75);
  249. }
  250. return new THREE.ParametricBufferGeometry(
  251. klein, slices, stacks);
  252. },
  253. },
  254. PlaneBufferGeometry: {
  255. ui: {
  256. width: { type: 'range', min: 1, max: 10, precision: 1, },
  257. height: { type: 'range', min: 1, max: 10, precision: 1, },
  258. widthSegments: { type: 'range', min: 1, max: 10, },
  259. heightSegments: { type: 'range', min: 1, max: 10, },
  260. },
  261. create(width = 9, height = 9) {
  262. return new THREE.PlaneBufferGeometry(width, height);
  263. },
  264. create2(width = 9, height = 9, widthSegments = 2, heightSegments = 2) {
  265. return new THREE.PlaneBufferGeometry(
  266. width, height,
  267. widthSegments, heightSegments);
  268. },
  269. },
  270. PolyhedronBufferGeometry: {
  271. ui: {
  272. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  273. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  274. },
  275. create(radius = 7, detail = 2) {
  276. const verticesOfCube = [
  277. -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1,
  278. -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,
  279. ];
  280. const indicesOfFaces = [
  281. 2, 1, 0, 0, 3, 2,
  282. 0, 4, 7, 7, 3, 0,
  283. 0, 1, 5, 5, 4, 0,
  284. 1, 2, 6, 6, 5, 1,
  285. 2, 3, 7, 7, 6, 2,
  286. 4, 5, 6, 6, 7, 4,
  287. ];
  288. return new THREE.PolyhedronBufferGeometry(
  289. verticesOfCube, indicesOfFaces, radius, detail);
  290. },
  291. },
  292. RingBufferGeometry: {
  293. ui: {
  294. innerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  295. outerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  296. thetaSegments: { type: 'range', min: 1, max: 30, },
  297. phiSegments: { type: 'range', min: 1, max: 10, },
  298. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  299. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  300. },
  301. create(innerRadius = 2, outerRadius = 7, thetaSegments = 18) {
  302. return new THREE.RingBufferGeometry(
  303. innerRadius, outerRadius, thetaSegments);
  304. },
  305. create2(innerRadius = 2, outerRadius = 7, thetaSegments = 18, phiSegments = 2, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  306. return new THREE.RingBufferGeometry(
  307. innerRadius, outerRadius,
  308. thetaSegments, phiSegments,
  309. thetaStart, thetaLength);
  310. },
  311. },
  312. ShapeBufferGeometry: {
  313. ui: {
  314. curveSegments: { type: 'range', min: 1, max: 30, },
  315. },
  316. create() {
  317. const shape = new THREE.Shape();
  318. const x = -2.5;
  319. const y = -5;
  320. shape.moveTo(x + 2.5, y + 2.5);
  321. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  322. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  323. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  324. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  325. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  326. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  327. return new THREE.ShapeBufferGeometry(shape);
  328. },
  329. create2(curveSegments = 5) {
  330. const shape = new THREE.Shape();
  331. const x = -2.5;
  332. const y = -5;
  333. shape.moveTo(x + 2.5, y + 2.5);
  334. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  335. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  336. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  337. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  338. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  339. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  340. return new THREE.ShapeBufferGeometry(shape, curveSegments);
  341. },
  342. },
  343. SphereBufferGeometry: {
  344. ui: {
  345. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  346. widthSegments: { type: 'range', min: 1, max: 30, },
  347. heightSegments: { type: 'range', min: 1, max: 30, },
  348. phiStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  349. phiLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  350. thetaStart: { type: 'range', min: 0, max: 1, mult: Math.PI },
  351. thetaLength: { type: 'range', min: 0, max: 1, mult: Math.PI },
  352. },
  353. create(radius = 7, widthSegments = 12, heightSegments = 8) {
  354. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  355. },
  356. create2(radius = 7, widthSegments = 12, heightSegments = 8, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 0.5) {
  357. return new THREE.SphereBufferGeometry(
  358. radius,
  359. widthSegments, heightSegments,
  360. phiStart, phiLength,
  361. thetaStart, thetaLength);
  362. },
  363. },
  364. TetrahedronBufferGeometry: {
  365. ui: {
  366. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  367. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  368. },
  369. create(radius = 7) {
  370. return new THREE.TetrahedronBufferGeometry(radius);
  371. },
  372. create2(radius = 7, detail = 2) {
  373. return new THREE.TetrahedronBufferGeometry(radius, detail);
  374. },
  375. },
  376. TextBufferGeometry: {
  377. ui: {
  378. text: { type: 'text', maxLength: 30, },
  379. size: { type: 'range', min: 1, max: 10, precision: 1, },
  380. height: { type: 'range', min: 1, max: 10, precision: 1, },
  381. curveSegments: { type: 'range', min: 1, max: 20, },
  382. // font', fonts ).onChange( generateGeometry );
  383. // weight', weights ).onChange( generateGeometry );
  384. bevelEnabled: { type: 'bool', },
  385. bevelThickness: { type: 'range', min: 0.1, max: 3, },
  386. bevelSize: { type: 'range', min: 0.1, max:3, },
  387. bevelSegments: { type: 'range', min: 0, max: 8, },
  388. },
  389. addConstCode: false,
  390. create(text = 'three.js', size = 3, height = 0.2, curveSegments = 12, bevelEnabled = true, bevelThickness = 0.15, bevelSize = 0.3, bevelSegments = 5) {
  391. return new Promise((resolve) => {
  392. fontPromise.then((font) => {
  393. resolve(new THREE.TextBufferGeometry(text, {
  394. font: font,
  395. size,
  396. height,
  397. curveSegments,
  398. bevelEnabled,
  399. bevelThickness,
  400. bevelSize,
  401. bevelSegments,
  402. }));
  403. });
  404. });
  405. },
  406. src: `
  407. const loader = new THREE.FontLoader();
  408. loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
  409. const text = 'three.js'; // ui: text
  410. const geometry = new THREE.TextBufferGeometry(text, {
  411. font: font,
  412. size: 3, // ui: size
  413. height: 0.2, // ui: height
  414. curveSegments: 12, // ui: curveSegments
  415. bevelEnabled: true, // ui: bevelEnabled
  416. bevelThickness: 0.15, // ui: bevelThickness
  417. bevelSize: 0.3, // ui: bevelSize
  418. bevelSegments: 5, // ui: bevelSegments
  419. });
  420. ...
  421. });
  422. `,
  423. },
  424. TorusBufferGeometry: {
  425. ui: {
  426. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  427. tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  428. radialSegments: { type: 'range', min: 1, max: 30, },
  429. tubularSegments: { type: 'range', min: 1, max: 100, },
  430. },
  431. create(radius = 5, tubeRadius = 2, radialSegments = 8, tubularSegments = 24) {
  432. return new THREE.TorusBufferGeometry(
  433. radius, tubeRadius,
  434. radialSegments, tubularSegments);
  435. },
  436. },
  437. TorusKnotBufferGeometry: {
  438. ui: {
  439. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  440. tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  441. radialSegments: { type: 'range', min: 1, max: 30, },
  442. tubularSegments: { type: 'range', min: 1, max: 100, },
  443. p: { type: 'range', min: 1, max: 20, },
  444. q: { type: 'range', min: 1, max: 20, },
  445. },
  446. create(radius = 3.5, tubeRadius = 1.5, radialSegments = 8, tubularSegments = 64, p = 2, q = 3) {
  447. return new THREE.TorusKnotBufferGeometry(
  448. radius, tubeRadius, tubularSegments, radialSegments, p, q);
  449. },
  450. },
  451. TubeBufferGeometry: {
  452. ui: {
  453. tubularSegments: { type: 'range', min: 1, max: 100, },
  454. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  455. radialSegments: { type: 'range', min: 1, max: 30, },
  456. closed: { type: 'bool', },
  457. },
  458. create(tubularSegments = 20, radius = 1, radialSegments = 8, closed = false) {
  459. class CustomSinCurve extends THREE.Curve {
  460. constructor(scale) {
  461. super();
  462. this.scale = scale;
  463. }
  464. getPoint(t) {
  465. const tx = t * 3 - 1.5;
  466. const ty = Math.sin(2 * Math.PI * t);
  467. const tz = 0;
  468. return new THREE.Vector3(tx, ty, tz).multiplyScalar(this.scale);
  469. }
  470. }
  471. const path = new CustomSinCurve(4);
  472. return new THREE.TubeBufferGeometry(
  473. path, tubularSegments, radius, radialSegments, closed);
  474. },
  475. },
  476. EdgesGeometry: {
  477. ui: {
  478. thresholdAngle: { type: 'range', min: 1, max: 180, },
  479. },
  480. create() {
  481. return {
  482. lineGeometry: new THREE.EdgesGeometry(
  483. new THREE.BoxBufferGeometry(8, 8, 8)),
  484. };
  485. },
  486. create2(thresholdAngle = 1) {
  487. return {
  488. lineGeometry: new THREE.EdgesGeometry(
  489. new THREE.SphereBufferGeometry(7, 6, 3), thresholdAngle),
  490. };
  491. },
  492. nonBuffer: false,
  493. addConstCode: false,
  494. src: `
  495. const size = 8;
  496. const widthSegments = 2;
  497. const heightSegments = 2;
  498. const depthSegments = 2;
  499. const boxGeometry = new THREE.BoxBufferGeometry(
  500. size, size, size,
  501. widthSegments, heightSegments, depthSegments);
  502. const geometry = new THREE.EdgesGeometry(boxGeometry);
  503. `,
  504. src2: `
  505. const radius = 7;
  506. const widthSegments = 6;
  507. const heightSegments = 3;
  508. const sphereGeometry = new THREE.SphereBufferGeometry(
  509. radius, widthSegments, heightSegments);
  510. const thresholdAngle = 1; // ui: thresholdAngle
  511. const geometry = new THREE.EdgesGeometry(sphereGeometry, thresholdAngle);
  512. `,
  513. },
  514. WireframeGeometry: {
  515. ui: {
  516. widthSegments: { type: 'range', min: 1, max: 10, },
  517. heightSegments: { type: 'range', min: 1, max: 10, },
  518. depthSegments: { type: 'range', min: 1, max: 10, },
  519. },
  520. create(widthSegments = 2, heightSegments = 2, depthSegments = 2) {
  521. const size = 8;
  522. return {
  523. lineGeometry: new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(
  524. size, size, size,
  525. widthSegments, heightSegments, depthSegments)),
  526. };
  527. },
  528. nonBuffer: false,
  529. addConstCode: false,
  530. src: `
  531. const size = 8;
  532. const widthSegments = 2; // ui: widthSegments
  533. const heightSegments = 2; // ui: heightSegments
  534. const depthSegments = 2; // ui: depthSegments
  535. const geometry = new THREE.WireframeGeometry(
  536. new THREE.BoxBufferGeometry(
  537. size, size, size,
  538. widthSegments, heightSegments, depthSegments));
  539. `,
  540. },
  541. Points: {
  542. create() {
  543. const radius = 7;
  544. const widthSegments = 12;
  545. const heightSegments = 8;
  546. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  547. const material = new THREE.PointsMaterial({
  548. color: 'red',
  549. size: 0.2,
  550. });
  551. const points = new THREE.Points(geometry, material);
  552. return {
  553. showLines: false,
  554. mesh: points,
  555. };
  556. },
  557. },
  558. PointsUniformSize: {
  559. create() {
  560. const radius = 7;
  561. const widthSegments = 12;
  562. const heightSegments = 8;
  563. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  564. const material = new THREE.PointsMaterial({
  565. color: 'red',
  566. size: 3 * window.devicePixelRatio,
  567. sizeAttenuation: false,
  568. });
  569. const points = new THREE.Points(geometry, material);
  570. return {
  571. showLines: false,
  572. mesh: points,
  573. };
  574. },
  575. },
  576. SphereBufferGeometryLow: {
  577. create(radius = 7, widthSegments = 5, heightSegments = 3) {
  578. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  579. },
  580. },
  581. SphereBufferGeometryMedium: {
  582. create(radius = 7, widthSegments = 24, heightSegments = 10) {
  583. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  584. },
  585. },
  586. SphereBufferGeometryHigh: {
  587. create(radius = 7, widthSegments = 50, heightSegments = 50) {
  588. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  589. },
  590. },
  591. SphereBufferGeometryLowSmooth: {
  592. create(radius = 7, widthSegments = 5, heightSegments = 3) {
  593. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  594. },
  595. showLines: false,
  596. flatShading: false,
  597. },
  598. SphereBufferGeometryMediumSmooth: {
  599. create(radius = 7, widthSegments = 24, heightSegments = 10) {
  600. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  601. },
  602. showLines: false,
  603. flatShading: false,
  604. },
  605. SphereBufferGeometryHighSmooth: {
  606. create(radius = 7, widthSegments = 50, heightSegments = 50) {
  607. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  608. },
  609. showLines: false,
  610. flatShading: false,
  611. },
  612. PlaneBufferGeometryLow: {
  613. create(width = 9, height = 9, widthSegments = 1, heightSegments = 1) {
  614. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  615. },
  616. },
  617. PlaneBufferGeometryHigh: {
  618. create(width = 9, height = 9, widthSegments = 10, heightSegments = 10) {
  619. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  620. },
  621. },
  622. };
  623. function addLink(parent, name) {
  624. const a = document.createElement('a');
  625. a.href = `https://threejs.org/docs/#api/geometries/${name}`;
  626. const code = document.createElement('code');
  627. code.textContent = name;
  628. a.appendChild(code);
  629. parent.appendChild(a);
  630. return a;
  631. }
  632. function addElem(parent, type, className, text) {
  633. const elem = document.createElement(type);
  634. elem.className = className;
  635. if (text) {
  636. elem.textContent = text;
  637. }
  638. parent.appendChild(elem);
  639. return elem;
  640. }
  641. function addDiv(parent, className) {
  642. return addElem(parent, 'div', className);
  643. }
  644. function createPrimitiveDOM(base) {
  645. const name = base.dataset.primitive;
  646. const info = diagrams[name];
  647. if (!info) {
  648. throw new Error(`no primitive ${name}`);
  649. }
  650. const text = base.innerHTML;
  651. base.innerHTML = '';
  652. const pair = addDiv(base, 'pair');
  653. const elem = addDiv(pair, 'shape');
  654. const right = addDiv(pair, 'desc');
  655. addLink(right, name);
  656. if (info.nonBuffer !== false) {
  657. addElem(right, 'span', '', ', ');
  658. addLink(right, name.replace('Buffer', ''));
  659. }
  660. addDiv(right, '.note').innerHTML = text;
  661. // I get that this is super brittle. I think I'd have to
  662. // work through a bunch more examples to come up with a better
  663. // structure. Also, I don't want to generate actual code and
  664. // use eval. (maybe a bad striction)
  665. function makeExample(elem, createFn, src) {
  666. const rawLines = createFn.toString().replace(/return (new THREE\.[a-zA-Z]+Geometry)/, 'const geometry = $1').split(/\n/);
  667. const createRE = /^ *(?:function *)*create\d*\((.*?)\)/;
  668. const indentRE = /^( *)[^ ]/;
  669. const m = indentRE.exec(rawLines[1]);
  670. const prefixLen = m[1].length;
  671. const m2 = createRE.exec(rawLines[0]);
  672. const argString = m2[1].trim();
  673. const trimmedLines = src
  674. ? src.split('\n').slice(1, -1)
  675. : rawLines.slice(1, rawLines.length - 1).map(line => line.substring(prefixLen));
  676. if (info.addConstCode !== false && argString) {
  677. const lines = argString.split(',').map((arg) => {
  678. return `const ${arg.trim()}; // ui: ${arg.trim().split(' ')[0]}`;
  679. });
  680. const lineNdx = trimmedLines.findIndex(l => l.indexOf('const geometry') >= 0);
  681. trimmedLines.splice(lineNdx < 0 ? 0 : lineNdx, 0, ...lines);
  682. }
  683. addElem(base, 'pre', 'prettyprint showmods', trimmedLines.join('\n'));
  684. createLiveImage(elem, Object.assign({}, info, {create: createFn}), name);
  685. }
  686. makeExample(elem, info.create, info.src);
  687. {
  688. let i = 2;
  689. for (;;) {
  690. const createFn = info[`create${i}`];
  691. if (!createFn) {
  692. break;
  693. }
  694. const shapeElem = addDiv(base, 'shape');
  695. makeExample(shapeElem, createFn, info[`src${i}`]);
  696. ++i;
  697. }
  698. }
  699. }
  700. function createDiagram(base) {
  701. const name = base.dataset.diagram;
  702. const info = diagrams[name];
  703. if (!info) {
  704. throw new Error(`no primitive ${name}`);
  705. }
  706. createLiveImage(base, info, name);
  707. }
  708. async function addGeometry(root, info, args = []) {
  709. const result = info.create(...args);
  710. const promise = (result instanceof Promise) ? result : Promise.resolve(result);
  711. let diagramInfo = await promise;
  712. if (diagramInfo instanceof THREE.BufferGeometry ||
  713. diagramInfo instanceof THREE.Geometry) {
  714. const geometry = diagramInfo;
  715. diagramInfo = {
  716. geometry,
  717. };
  718. }
  719. const geometry = diagramInfo.geometry || diagramInfo.lineGeometry || diagramInfo.mesh.geometry;
  720. geometry.computeBoundingBox();
  721. const centerOffset = new THREE.Vector3();
  722. geometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
  723. let mesh = diagramInfo.mesh;
  724. if (diagramInfo.geometry) {
  725. if (!info.material) {
  726. const material = new THREE.MeshPhongMaterial({
  727. flatShading: info.flatShading === false ? false : true,
  728. side: THREE.DoubleSide,
  729. });
  730. material.color.setHSL(Math.random(), .5, .5);
  731. info.material = material;
  732. }
  733. mesh = new THREE.Mesh(diagramInfo.geometry, info.material);
  734. }
  735. if (mesh) {
  736. mesh.position.copy(centerOffset);
  737. root.add(mesh);
  738. }
  739. if (info.showLines !== false) {
  740. const lineMesh = new THREE.LineSegments(
  741. diagramInfo.lineGeometry || diagramInfo.geometry,
  742. new THREE.LineBasicMaterial({
  743. color: diagramInfo.geometry ? 0xffffff : colors.lines,
  744. transparent: true,
  745. opacity: 0.5,
  746. }));
  747. lineMesh.position.copy(centerOffset);
  748. root.add(lineMesh);
  749. }
  750. }
  751. async function updateGeometry(root, info, params) {
  752. const oldChildren = root.children.slice();
  753. await addGeometry(root, info, Object.values(params));
  754. oldChildren.forEach((child) => {
  755. root.remove(child);
  756. child.geometry.dispose();
  757. });
  758. }
  759. const primitives = {};
  760. async function createLiveImage(elem, info, name) {
  761. const root = new THREE.Object3D();
  762. primitives[name] = primitives[name] || [];
  763. primitives[name].push({
  764. root,
  765. info,
  766. });
  767. await addGeometry(root, info);
  768. threejsLessonUtils.addDiagram(elem, {create: () => root});
  769. }
  770. function getValueElem(commentElem) {
  771. return commentElem.previousElementSibling &&
  772. commentElem.previousElementSibling.previousElementSibling &&
  773. commentElem.previousElementSibling.previousElementSibling.previousElementSibling;
  774. }
  775. threejsLessonUtils.onAfterPrettify(() => {
  776. document.querySelectorAll('[data-primitive]').forEach((base) => {
  777. const primitiveName = base.dataset.primitive;
  778. const infos = primitives[primitiveName];
  779. base.querySelectorAll('pre.prettyprint').forEach((shape, ndx) => {
  780. const {root, info} = infos[ndx];
  781. const params = {};
  782. [...shape.querySelectorAll('span.com')]
  783. .filter(span => span.textContent.indexOf('// ui:') >= 0)
  784. .forEach((span) => {
  785. const nameRE = /ui: ([a-zA-Z0-9_]+) *$/;
  786. const name = nameRE.exec(span.textContent)[1];
  787. span.textContent = '';
  788. if (!info.ui) {
  789. console.error(`no ui for ${primitiveName}:${ndx}`); // eslint-disable-line
  790. return;
  791. // throw new Error(`no ui for ${primitiveName}:${ndx}`);
  792. }
  793. const ui = info.ui[name];
  794. if (!ui) {
  795. throw new Error(`no ui for ${primitiveName}:${ndx} param: ${name}`);
  796. }
  797. const valueElem = getValueElem(span);
  798. if (!valueElem) {
  799. console.error(`no value element for ${primitiveName}:${ndx} param: ${name}`); // eslint-disable-line
  800. return;
  801. }
  802. const inputHolderHolder = document.createElement('div');
  803. inputHolderHolder.className = 'input';
  804. const inputHolder = document.createElement('div');
  805. span.appendChild(inputHolderHolder);
  806. inputHolderHolder.appendChild(inputHolder);
  807. switch (ui.type) {
  808. case 'range': {
  809. const valueRange = ui.max - ui.min;
  810. const input = document.createElement('input');
  811. const inputMax = 100;
  812. input.type = 'range';
  813. input.min = 0;
  814. input.max = inputMax;
  815. const value = parseFloat(valueElem.textContent);
  816. params[name] = value * (ui.mult || 1);
  817. input.value = (value - ui.min) / valueRange * inputMax;
  818. inputHolder.appendChild(input);
  819. const precision = ui.precision === undefined ? (valueRange > 4 ? 0 : 2) : ui.precision;
  820. const padding = ui.max.toFixed(precision).length;
  821. input.addEventListener('input', () => {
  822. let newValue = input.value * valueRange / inputMax + ui.min;
  823. if (precision === 0) {
  824. newValue = Math.round(newValue);
  825. }
  826. params[name] = newValue * (ui.mult || 1);
  827. valueElem.textContent = newValue.toFixed(precision).padStart(padding, ' ');
  828. updateGeometry(root, info, params);
  829. });
  830. break;
  831. }
  832. case 'bool': {
  833. const input = document.createElement('input');
  834. input.type = 'checkbox';
  835. params[name] = valueElem.textContent === 'true';
  836. input.checked = params[name];
  837. inputHolder.appendChild(input);
  838. input.addEventListener('change', () => {
  839. params[name] = input.checked;
  840. valueElem.textContent = params[name] ? 'true' : 'false';
  841. updateGeometry(root, info, params);
  842. });
  843. break;
  844. }
  845. case 'text': {
  846. const input = document.createElement('input');
  847. input.type = 'text';
  848. params[name] = valueElem.textContent.slice(1, -1);
  849. input.value = params[name];
  850. input.maxlength = ui.maxLength || 50;
  851. inputHolder.appendChild(input);
  852. input.addEventListener('input', () => {
  853. params[name] = input.value;
  854. valueElem.textContent = `'${input.value.replace(/'/g, '\'')}'`;
  855. updateGeometry(root, info, params);
  856. });
  857. break;
  858. }
  859. default:
  860. throw new Error(`unknown type for ${primitiveName}:${ndx} param: ${name}`);
  861. }
  862. });
  863. });
  864. });
  865. });
  866. document.querySelectorAll('[data-diagram]').forEach(createDiagram);
  867. document.querySelectorAll('[data-primitive]').forEach(createPrimitiveDOM);
  868. }