@bitbybit-dev/create-app 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +47 -124
  2. package/dist/index.js +253 -21
  3. package/dist/index.js.map +1 -1
  4. package/dist/scaffold.d.ts +30 -0
  5. package/dist/scaffold.d.ts.map +1 -0
  6. package/dist/scaffold.js +107 -0
  7. package/dist/scaffold.js.map +1 -0
  8. package/package.json +4 -3
  9. package/src/index.test.ts +309 -8
  10. package/src/index.ts +285 -24
  11. package/src/scaffold.test.ts +177 -0
  12. package/src/scaffold.ts +99 -0
  13. package/templates/_agent/AGENTS.md +39 -0
  14. package/templates/_agent/CLAUDE.md +1 -0
  15. package/templates/_agent/_dot-cursor/mcp.json +5 -0
  16. package/templates/_agent/_dot-gitignore +7 -0
  17. package/templates/_agent/_dot-mcp.json +5 -0
  18. package/templates/_agent/_dot-vscode/mcp.json +5 -0
  19. package/templates/apps/drone-assembly/AGENTS.section.md +20 -0
  20. package/templates/apps/drone-assembly/README.md +35 -0
  21. package/templates/apps/drone-assembly/eslint.config.js +47 -0
  22. package/templates/apps/drone-assembly/index.html +17 -0
  23. package/templates/apps/drone-assembly/package.json +31 -0
  24. package/templates/apps/drone-assembly/public/favicon.ico +0 -0
  25. package/templates/apps/drone-assembly/public/logo.png +0 -0
  26. package/templates/apps/drone-assembly/scripts/smoke.ts +172 -0
  27. package/templates/apps/drone-assembly/src/assembly.ts +99 -0
  28. package/templates/apps/drone-assembly/src/exports.ts +10 -0
  29. package/templates/apps/drone-assembly/src/kernel.ts +14 -0
  30. package/templates/apps/drone-assembly/src/main.ts +298 -0
  31. package/templates/apps/drone-assembly/src/materials.ts +58 -0
  32. package/templates/apps/drone-assembly/src/model.ts +280 -0
  33. package/templates/apps/drone-assembly/src/parts.ts +343 -0
  34. package/templates/apps/drone-assembly/src/style.css +219 -0
  35. package/templates/apps/drone-assembly/src/ui.ts +180 -0
  36. package/templates/apps/drone-assembly/src/vite-env.d.ts +1 -0
  37. package/templates/apps/drone-assembly/tsconfig.json +29 -0
  38. package/templates/apps/laser-cut-box/AGENTS.section.md +17 -0
  39. package/templates/apps/laser-cut-box/README.md +34 -0
  40. package/templates/apps/laser-cut-box/eslint.config.js +47 -0
  41. package/templates/apps/laser-cut-box/index.html +17 -0
  42. package/templates/apps/laser-cut-box/package.json +30 -0
  43. package/templates/apps/laser-cut-box/public/favicon.ico +0 -0
  44. package/templates/apps/laser-cut-box/public/logo.png +0 -0
  45. package/templates/apps/laser-cut-box/scripts/smoke.ts +106 -0
  46. package/templates/apps/laser-cut-box/src/exports.ts +28 -0
  47. package/templates/apps/laser-cut-box/src/main.ts +176 -0
  48. package/templates/apps/laser-cut-box/src/model.ts +92 -0
  49. package/templates/apps/laser-cut-box/src/panels.ts +229 -0
  50. package/templates/apps/laser-cut-box/src/style.css +223 -0
  51. package/templates/apps/laser-cut-box/src/ui.ts +136 -0
  52. package/templates/apps/laser-cut-box/src/vite-env.d.ts +1 -0
  53. package/templates/apps/laser-cut-box/tsconfig.json +29 -0
  54. package/templates/apps/product-configurator/AGENTS.section.md +19 -0
  55. package/templates/apps/product-configurator/README.md +33 -0
  56. package/templates/apps/product-configurator/eslint.config.js +47 -0
  57. package/templates/apps/product-configurator/index.html +17 -0
  58. package/templates/apps/product-configurator/package.json +30 -0
  59. package/templates/apps/product-configurator/public/favicon.ico +0 -0
  60. package/templates/apps/product-configurator/public/logo.png +0 -0
  61. package/templates/apps/product-configurator/scripts/smoke.ts +69 -0
  62. package/templates/apps/product-configurator/src/catalog.ts +56 -0
  63. package/templates/apps/product-configurator/src/exports.ts +19 -0
  64. package/templates/apps/product-configurator/src/main.ts +134 -0
  65. package/templates/apps/product-configurator/src/model.ts +153 -0
  66. package/templates/apps/product-configurator/src/style.css +177 -0
  67. package/templates/apps/product-configurator/src/ui.ts +150 -0
  68. package/templates/apps/product-configurator/src/vite-env.d.ts +1 -0
  69. package/templates/apps/product-configurator/tsconfig.json +29 -0
  70. package/templates/apps/sheet-metal-unfold/AGENTS.section.md +26 -0
  71. package/templates/apps/sheet-metal-unfold/README.md +41 -0
  72. package/templates/apps/sheet-metal-unfold/backend/_dot-env.example +5 -0
  73. package/templates/apps/sheet-metal-unfold/backend/eslint.config.js +47 -0
  74. package/templates/apps/sheet-metal-unfold/backend/package.json +28 -0
  75. package/templates/apps/sheet-metal-unfold/backend/scripts/smoke.ts +52 -0
  76. package/templates/apps/sheet-metal-unfold/backend/src/app.ts +65 -0
  77. package/templates/apps/sheet-metal-unfold/backend/src/cloud.ts +42 -0
  78. package/templates/apps/sheet-metal-unfold/backend/src/index.ts +13 -0
  79. package/templates/apps/sheet-metal-unfold/backend/tsconfig.build.json +9 -0
  80. package/templates/apps/sheet-metal-unfold/backend/tsconfig.json +27 -0
  81. package/templates/apps/sheet-metal-unfold/frontend/eslint.config.js +47 -0
  82. package/templates/apps/sheet-metal-unfold/frontend/index.html +17 -0
  83. package/templates/apps/sheet-metal-unfold/frontend/package.json +30 -0
  84. package/templates/apps/sheet-metal-unfold/frontend/public/favicon.ico +0 -0
  85. package/templates/apps/sheet-metal-unfold/frontend/public/logo.png +0 -0
  86. package/templates/apps/sheet-metal-unfold/frontend/scripts/smoke.ts +84 -0
  87. package/templates/apps/sheet-metal-unfold/frontend/src/cloud-access.ts +37 -0
  88. package/templates/apps/sheet-metal-unfold/frontend/src/exports.ts +10 -0
  89. package/templates/apps/sheet-metal-unfold/frontend/src/flat.ts +71 -0
  90. package/templates/apps/sheet-metal-unfold/frontend/src/main.ts +193 -0
  91. package/templates/apps/sheet-metal-unfold/frontend/src/model.ts +166 -0
  92. package/templates/apps/sheet-metal-unfold/frontend/src/style.css +291 -0
  93. package/templates/apps/sheet-metal-unfold/frontend/src/ui.ts +150 -0
  94. package/templates/apps/sheet-metal-unfold/frontend/src/vite-env.d.ts +1 -0
  95. package/templates/apps/sheet-metal-unfold/frontend/tsconfig.json +29 -0
  96. package/templates/apps/sheet-metal-unfold/frontend/vite.config.ts +9 -0
  97. package/templates/apps/sheet-metal-unfold/package.json +18 -0
  98. package/templates/apps/step-to-gltf-cli/AGENTS.section.md +20 -0
  99. package/templates/apps/step-to-gltf-cli/README.md +34 -0
  100. package/templates/apps/step-to-gltf-cli/eslint.config.js +47 -0
  101. package/templates/apps/step-to-gltf-cli/package.json +26 -0
  102. package/templates/apps/step-to-gltf-cli/samples/bracket.step +2545 -0
  103. package/templates/apps/step-to-gltf-cli/scripts/smoke.ts +49 -0
  104. package/templates/apps/step-to-gltf-cli/src/cli.ts +106 -0
  105. package/templates/apps/step-to-gltf-cli/src/cloud.ts +34 -0
  106. package/templates/apps/step-to-gltf-cli/src/convert.ts +65 -0
  107. package/templates/apps/step-to-gltf-cli/src/kernel.ts +14 -0
  108. package/templates/apps/step-to-gltf-cli/tsconfig.json +27 -0
  109. package/templates/cloud/AGENTS.section.md +22 -0
  110. package/templates/cloud/backends/dotnet-rest/BitbybitClient.cs +22 -50
  111. package/templates/cloud/backends/dotnet-rest/Program.cs +1 -11
  112. package/templates/cloud/backends/dotnet-rest/dotnet-rest.csproj +4 -1
  113. package/templates/cloud/backends/hono-rest/eslint.config.js +47 -0
  114. package/templates/cloud/backends/hono-rest/package.json +11 -4
  115. package/templates/cloud/backends/hono-rest/src/bitbybit-client.ts +34 -45
  116. package/templates/cloud/backends/hono-rest/src/index.ts +1 -11
  117. package/templates/cloud/backends/hono-rest/tsconfig.json +19 -8
  118. package/templates/cloud/backends/hono-sdk/eslint.config.js +47 -0
  119. package/templates/cloud/backends/hono-sdk/package.json +12 -5
  120. package/templates/cloud/backends/hono-sdk/src/bitbybit-client.ts +6 -37
  121. package/templates/cloud/backends/hono-sdk/src/index.ts +1 -12
  122. package/templates/cloud/backends/hono-sdk/tsconfig.json +19 -8
  123. package/templates/cloud/backends/nodejs-rest/eslint.config.js +47 -0
  124. package/templates/cloud/backends/nodejs-rest/package.json +12 -5
  125. package/templates/cloud/backends/nodejs-rest/src/bitbybit-client.ts +6 -35
  126. package/templates/cloud/backends/nodejs-rest/src/index.ts +6 -16
  127. package/templates/cloud/backends/nodejs-rest/tsconfig.build.json +9 -0
  128. package/templates/cloud/backends/nodejs-rest/tsconfig.json +17 -7
  129. package/templates/cloud/backends/nodejs-sdk/eslint.config.js +47 -0
  130. package/templates/cloud/backends/nodejs-sdk/package.json +14 -7
  131. package/templates/cloud/backends/nodejs-sdk/src/bitbybit-client.ts +8 -33
  132. package/templates/cloud/backends/nodejs-sdk/src/index.ts +5 -16
  133. package/templates/cloud/backends/nodejs-sdk/tsconfig.build.json +9 -0
  134. package/templates/cloud/backends/nodejs-sdk/tsconfig.json +19 -9
  135. package/templates/cloud/frontend/eslint.config.js +50 -0
  136. package/templates/cloud/frontend/index.html +3 -1
  137. package/templates/cloud/frontend/package.json +13 -4
  138. package/templates/cloud/frontend/public/favicon.ico +0 -0
  139. package/templates/cloud/frontend/public/logo.png +0 -0
  140. package/templates/cloud/frontend/src/App.tsx +11 -9
  141. package/templates/cloud/frontend/src/api.ts +31 -0
  142. package/templates/cloud/frontend/src/components/ApiKeyWarning.tsx +28 -25
  143. package/templates/cloud/frontend/src/components/Header.tsx +4 -2
  144. package/templates/cloud/frontend/src/components/Tabs.tsx +4 -3
  145. package/templates/cloud/frontend/src/components/Viewer.tsx +57 -77
  146. package/templates/cloud/frontend/src/main.tsx +6 -1
  147. package/templates/cloud/frontend/src/panels/ModelsPanel.tsx +65 -73
  148. package/templates/cloud/frontend/src/panels/PipelinesPanel.tsx +82 -83
  149. package/templates/cloud/frontend/src/vite-env.d.ts +1 -0
  150. package/templates/cloud/frontend/tsconfig.json +19 -7
  151. package/templates/vite/babylonjs/typescript/AGENTS.section.md +13 -0
  152. package/templates/vite/babylonjs/typescript/eslint.config.js +47 -0
  153. package/templates/vite/babylonjs/typescript/index.html +4 -2
  154. package/templates/vite/babylonjs/typescript/package.json +14 -4
  155. package/templates/vite/babylonjs/typescript/public/favicon.ico +0 -0
  156. package/templates/vite/babylonjs/typescript/public/logo.png +0 -0
  157. package/templates/vite/babylonjs/typescript/scripts/smoke.ts +41 -0
  158. package/templates/vite/babylonjs/typescript/src/main.ts +8 -17
  159. package/templates/vite/babylonjs/typescript/src/model.ts +24 -0
  160. package/templates/vite/babylonjs/typescript/tsconfig.json +16 -12
  161. package/templates/vite/playcanvas/typescript/AGENTS.section.md +13 -0
  162. package/templates/vite/playcanvas/typescript/eslint.config.js +47 -0
  163. package/templates/vite/playcanvas/typescript/index.html +4 -2
  164. package/templates/vite/playcanvas/typescript/package.json +14 -4
  165. package/templates/vite/playcanvas/typescript/public/favicon.ico +0 -0
  166. package/templates/vite/playcanvas/typescript/public/logo.png +0 -0
  167. package/templates/vite/playcanvas/typescript/scripts/smoke.ts +41 -0
  168. package/templates/vite/playcanvas/typescript/src/main.ts +11 -22
  169. package/templates/vite/playcanvas/typescript/src/model.ts +24 -0
  170. package/templates/vite/playcanvas/typescript/tsconfig.json +16 -12
  171. package/templates/vite/threejs/typescript/AGENTS.section.md +13 -0
  172. package/templates/vite/threejs/typescript/eslint.config.js +47 -0
  173. package/templates/vite/threejs/typescript/index.html +4 -2
  174. package/templates/vite/threejs/typescript/package.json +16 -6
  175. package/templates/vite/threejs/typescript/public/favicon.ico +0 -0
  176. package/templates/vite/threejs/typescript/public/logo.png +0 -0
  177. package/templates/vite/threejs/typescript/scripts/smoke.ts +41 -0
  178. package/templates/vite/threejs/typescript/src/main.ts +11 -22
  179. package/templates/vite/threejs/typescript/src/model.ts +24 -0
  180. package/templates/vite/threejs/typescript/tsconfig.json +16 -12
  181. package/templates/vite/babylonjs/typescript/public/vite.svg +0 -1
  182. package/templates/vite/playcanvas/typescript/public/vite.svg +0 -1
  183. package/templates/vite/threejs/typescript/public/vite.svg +0 -1
  184. /package/templates/cloud/backends/dotnet-rest/{_gitignore → _dot-gitignore} +0 -0
  185. /package/templates/cloud/backends/hono-rest/{_gitignore → _dot-gitignore} +0 -0
  186. /package/templates/cloud/backends/hono-sdk/{_gitignore → _dot-gitignore} +0 -0
  187. /package/templates/cloud/backends/nodejs-rest/{.env.example → _dot-env.example} +0 -0
  188. /package/templates/cloud/backends/nodejs-rest/{_gitignore → _dot-gitignore} +0 -0
  189. /package/templates/cloud/backends/nodejs-sdk/{.env.example → _dot-env.example} +0 -0
  190. /package/templates/cloud/backends/nodejs-sdk/{_gitignore → _dot-gitignore} +0 -0
@@ -0,0 +1,10 @@
1
+ export function downloadBlob(blob: Blob, fileName: string): void {
2
+ const url = URL.createObjectURL(blob);
3
+ const link = document.createElement("a");
4
+ link.href = url;
5
+ link.download = fileName;
6
+ document.body.appendChild(link);
7
+ link.click();
8
+ link.remove();
9
+ setTimeout(() => { URL.revokeObjectURL(url); }, 1000);
10
+ }
@@ -0,0 +1,14 @@
1
+ import { GeometryHelper, MathBitByBit, Transforms, Vector, type Base } from "@bitbybit-dev/base";
2
+ import type { BitByBitBase } from "@bitbybit-dev/threejs";
3
+
4
+ export type Occt = BitByBitBase["occt"];
5
+ export type Shape = Awaited<ReturnType<Occt["shapes"]["solid"]["createBox"]>>;
6
+ export type Wire = Awaited<ReturnType<Occt["shapes"]["wire"]["createCircleWire"]>>;
7
+ export type Point3 = Base.Point3;
8
+ export type Transform = Base.TransformMatrixes;
9
+
10
+ export const ORIGIN: Point3 = [0, 0, 0];
11
+
12
+ const math = new MathBitByBit();
13
+
14
+ export const transforms = new Transforms(new Vector(math, new GeometryHelper()), math);
@@ -0,0 +1,298 @@
1
+ import "./style.css";
2
+ import type { Mesh, Object3D } from "three";
3
+ import { ACESFilmicToneMapping, Color, Group, Matrix4, MeshPhysicalMaterial, PMREMGenerator, Vector3 } from "three";
4
+ import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
5
+ import { BitByBitBase, Inputs, initBitByBit, initThreeJS, type InitBitByBitOptions } from "@bitbybit-dev/threejs";
6
+ import { billOfMaterials, buildDocument, Z_UP, type BuiltDocument } from "./assembly";
7
+ import { downloadBlob } from "./exports";
8
+ import type { Shape, Transform } from "./kernel";
9
+ import { edgeColour, materialSpec, type FinishId, type MaterialId } from "./materials";
10
+ import { buildModel, defaultParams, FLIGHT_CEILING, partOf, type DroneModel, type DroneParams, type Part } from "./model";
11
+ import { mountPoint, mountUi, ROTOR_RPM, type ExportFormat } from "./ui";
12
+
13
+ const LOGO_URL = "https://git-cdn.bitbybit.dev/latest/assets/logo/logo-faces.stp";
14
+
15
+ const EDGE_WIDTH = 2;
16
+
17
+ const FLIGHT = { approach: 1.6, bob: 5, bobHz: 0.35, sway: 0.03, swayHz: 0.21 };
18
+
19
+ void start();
20
+
21
+ function isMesh(object: Object3D): object is Mesh {
22
+ return "isMesh" in object && object.isMesh === true;
23
+ }
24
+
25
+ function required<T>(value: T | undefined, what: string): T {
26
+ if (value === undefined) throw new Error(`${what} is missing`);
27
+ return value;
28
+ }
29
+
30
+ function cameraOptions(sceneSize: number): Inputs.ThreeJSCamera.OrbitCameraDto {
31
+ const camera = new Inputs.ThreeJSCamera.OrbitCameraDto();
32
+ camera.distance = sceneSize * Math.SQRT2;
33
+ camera.distanceMin = sceneSize * 0.02;
34
+ camera.distanceMax = sceneSize * 10;
35
+ return camera;
36
+ }
37
+
38
+ async function start(): Promise<void> {
39
+ const sceneOptions = new Inputs.ThreeJSScene.InitThreeJSDto();
40
+ sceneOptions.canvasId = "three-canvas";
41
+ sceneOptions.sceneSize = 500;
42
+ sceneOptions.groundScaleFactor = 5;
43
+ sceneOptions.backgroundColor = "#15171a";
44
+ sceneOptions.enableGround = true;
45
+ sceneOptions.groundColor = "#24272b";
46
+ sceneOptions.enableShadows = true;
47
+ sceneOptions.shadowMapSize = 2048;
48
+ sceneOptions.directionalLightIntensity = 2.2;
49
+ sceneOptions.hemisphereLightIntensity = 0.6;
50
+ sceneOptions.orbitCameraOptions = cameraOptions(sceneOptions.sceneSize);
51
+ const { scene, renderer, orbitCamera, startAnimationLoop } = initThreeJS(sceneOptions);
52
+
53
+ renderer.toneMapping = ACESFilmicToneMapping;
54
+ renderer.toneMappingExposure = 1.05;
55
+ const pmrem = new PMREMGenerator(renderer);
56
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
57
+ scene.environmentIntensity = 0.55;
58
+
59
+ const bitbybit = new BitByBitBase();
60
+ const options: InitBitByBitOptions = {
61
+ enableOCCT: true,
62
+ enableJSCAD: false,
63
+ enableManifold: false,
64
+ };
65
+ await initBitByBit(scene, bitbybit, options);
66
+
67
+ let params: DroneParams = { ...defaultParams };
68
+ let current: DroneModel | undefined;
69
+ let generation = 0;
70
+ let timer: number | undefined;
71
+ let framedFor = 0;
72
+ let rotorSpeed = (ROTOR_RPM.initial * 2 * Math.PI) / 60;
73
+ let throttle = ROTOR_RPM.initial / ROTOR_RPM.max;
74
+ let edgesVisible = true;
75
+ let flight = 0;
76
+ let clock = 0;
77
+
78
+ const materials = new Map<MaterialId, MeshPhysicalMaterial>();
79
+ const prototypes = new Map<string, Group>();
80
+ const root = new Group();
81
+ root.name = "Drone";
82
+ scene.add(root);
83
+ const propellers: { object: Object3D; handed: 1 | -1 }[] = [];
84
+
85
+ startAnimationLoop((deltaTime) => {
86
+ clock += deltaTime;
87
+ for (const propeller of propellers) propeller.object.rotation.y += propeller.handed * rotorSpeed * deltaTime;
88
+ const target = FLIGHT_CEILING * throttle;
89
+ flight += (target - flight) * Math.min(1, FLIGHT.approach * deltaTime);
90
+ if (flight < 0.05 && target === 0) flight = 0;
91
+ const airborne = flight / FLIGHT_CEILING;
92
+ root.position.y = flight + Math.sin(2 * Math.PI * FLIGHT.bobHz * clock) * FLIGHT.bob * airborne;
93
+ root.rotation.z = Math.sin(2 * Math.PI * FLIGHT.swayHz * clock) * FLIGHT.sway * airborne;
94
+ root.rotation.x = Math.sin(2 * Math.PI * FLIGHT.swayHz * 1.37 * clock + 1) * FLIGHT.sway * 0.7 * airborne;
95
+ });
96
+
97
+ const ui = mountUi(mountPoint("panel"), params, {
98
+ onChange: (next) => {
99
+ params = next;
100
+ window.clearTimeout(timer);
101
+ timer = window.setTimeout(() => void rebuild(), 120);
102
+ },
103
+ onSpeed: (rpm) => {
104
+ rotorSpeed = (rpm * 2 * Math.PI) / 60;
105
+ throttle = rpm / ROTOR_RPM.max;
106
+ },
107
+ onEdges: (next) => { edgesVisible = next; showEdges(root); },
108
+ onExport: (format) => void exportModel(format),
109
+ });
110
+
111
+ function materialFor(id: MaterialId, finish: FinishId): MeshPhysicalMaterial {
112
+ let material = materials.get(id);
113
+ if (!material) {
114
+ material = new MeshPhysicalMaterial();
115
+ material.name = id;
116
+ material.clearcoatRoughness = 0.12;
117
+ materials.set(id, material);
118
+ }
119
+ const spec = materialSpec(id, finish);
120
+ material.color = new Color(spec.colour);
121
+ material.metalness = spec.metalness;
122
+ material.roughness = spec.roughness;
123
+ material.clearcoat = spec.clearcoat;
124
+ material.emissive = new Color(spec.emissive ?? "#000000");
125
+ material.emissiveIntensity = spec.emissive ? 1.6 : 0;
126
+ return material;
127
+ }
128
+
129
+ function prototypeKey(part: Part, finish: FinishId): string {
130
+ return `${part.key}|${edgeColour(materialSpec(part.material, finish).colour)}`;
131
+ }
132
+
133
+ async function prototypeFor(part: Part, finish: FinishId): Promise<Group> {
134
+ const key = prototypeKey(part, finish);
135
+ const kept = prototypes.get(key);
136
+ if (kept) return kept;
137
+ const lines = edgeColour(materialSpec(part.material, finish).colour);
138
+ const drawOptions = new Inputs.Draw.DrawOcctShapeOptions();
139
+ drawOptions.precision = 0.05;
140
+ drawOptions.faceMaterial = materialFor(part.material, finish);
141
+ drawOptions.drawFaces = part.kind === "solid";
142
+ drawOptions.drawEdges = true;
143
+ drawOptions.edgeColour = lines;
144
+ drawOptions.edgeWidth = part.kind === "wires" ? EDGE_WIDTH * 0.75 : EDGE_WIDTH;
145
+ drawOptions.drawTwoSided = false;
146
+ const drawn = await bitbybit.draw.drawAnyAsync({ entity: part.shape, options: drawOptions });
147
+ scene.remove(drawn);
148
+ drawn.traverse((object) => {
149
+ if (!isMesh(object) || object.material === drawOptions.faceMaterial) return;
150
+ if (part.kind === "solid") object.userData["edges"] = true;
151
+
152
+ for (const lineMaterial of Array.isArray(object.material) ? object.material : [object.material]) {
153
+ lineMaterial.polygonOffset = true;
154
+ lineMaterial.polygonOffsetFactor = -1;
155
+ lineMaterial.polygonOffsetUnits = -2;
156
+ }
157
+ });
158
+ for (const [other, old] of prototypes) {
159
+ if (other.split(/[:|]/)[0] === part.id) { disposeGeometry(old); prototypes.delete(other); }
160
+ }
161
+ prototypes.set(key, drawn);
162
+ return drawn;
163
+ }
164
+
165
+ function place(object: Object3D, placement: Transform): void {
166
+ object.matrix.identity();
167
+ for (const step of placement) object.matrix.premultiply(new Matrix4().fromArray(step));
168
+ object.matrix.decompose(object.position, object.quaternion, object.scale);
169
+ }
170
+
171
+ function instanceClone(model: DroneModel, protos: Map<string, Group>, node: Extract<DroneModel["nodes"][number], { kind: "instance" }>): Group {
172
+ const part = partOf(model.parts, node.partId);
173
+ const clone = required(protos.get(prototypeKey(part, model.params.finish)), `the drawn prototype of ${part.id}`).clone();
174
+ clone.name = node.name;
175
+ place(clone, node.placement);
176
+ if (node.material) {
177
+ const base = materials.get(part.material);
178
+ const override = materialFor(node.material, model.params.finish);
179
+ clone.traverse((object) => { if (isMesh(object) && object.material === base) object.material = override; });
180
+ }
181
+ return clone;
182
+ }
183
+
184
+ function assemble(model: DroneModel, protos: Map<string, Group>): void {
185
+ root.clear();
186
+ propellers.length = 0;
187
+ const groups = new Map<string, Object3D>([["drone", root]]);
188
+ const templates = new Map<string, Group>();
189
+ for (const node of model.nodes) {
190
+ if (node.kind === "definition") {
191
+ const template = new Group();
192
+ template.name = node.name;
193
+ templates.set(node.id, template);
194
+ groups.set(node.id, template);
195
+ }
196
+ }
197
+ for (const node of model.nodes) {
198
+ if (node.kind === "definition") continue;
199
+ const parent = required(groups.get(node.parentId ?? "drone"), `the parent group of ${node.id}`);
200
+ if (node.kind === "module") {
201
+ const group = new Group();
202
+ group.name = node.name;
203
+ place(group, node.placement);
204
+ parent.add(group);
205
+ groups.set(node.id, group);
206
+ } else if (node.kind === "instance") {
207
+ const clone = instanceClone(model, protos, node);
208
+ parent.add(clone);
209
+ if (node.partId === "propeller-cw") propellers.push({ object: clone, handed: -1 });
210
+ if (node.partId === "propeller-ccw") propellers.push({ object: clone, handed: 1 });
211
+ }
212
+ }
213
+ for (const node of model.nodes) {
214
+ if (node.kind !== "reference") continue;
215
+ const copy = required(templates.get(node.definitionId), `the ${node.definitionId} definition`).clone();
216
+ copy.name = node.name;
217
+ place(copy, node.placement);
218
+ required(groups.get(node.parentId), `the parent group of ${node.id}`).add(copy);
219
+ }
220
+ showEdges(root);
221
+ }
222
+
223
+ function showEdges(object: Object3D): void {
224
+ object.traverse((child) => { if (child.userData["edges"]) child.visible = edgesVisible; });
225
+ }
226
+
227
+ async function withDocument<T>(model: DroneModel, frame: Transform | undefined, use: (built: BuiltDocument) => Promise<T>): Promise<T> {
228
+ const built = await buildDocument(bitbybit.occt, model, frame);
229
+ try {
230
+ return await use(built);
231
+ } finally {
232
+ for (const document of [built.document, ...built.sources]) await bitbybit.occt.assembly.manager.deleteDocument({ document });
233
+ }
234
+ }
235
+
236
+ async function rebuild(): Promise<void> {
237
+ const mine = ++generation;
238
+ const started = performance.now();
239
+ ui.setStatus(current ? "Rebuilding..." : "Building 27 parts on the OpenCascade kernel...");
240
+ try {
241
+ const model = await buildModel(bitbybit.occt, params, logo, current);
242
+ if (mine !== generation) return;
243
+ ui.setParams(model.params);
244
+ for (const material of materials.keys()) materialFor(material, model.params.finish);
245
+ const protos = new Map<string, Group>();
246
+ for (const part of model.parts) protos.set(prototypeKey(part, model.params.finish), await prototypeFor(part, model.params.finish));
247
+ if (mine !== generation) return;
248
+ assemble(model, protos);
249
+ current = model;
250
+ frame(model);
251
+ const bom = await withDocument(model, undefined, ({ document }) => billOfMaterials(bitbybit.occt, document));
252
+ ui.setBom(bom, model.counts.bolts);
253
+ ui.setStatus(`${bom.parts} parts placed ${bom.instances} times in ${model.counts.modules} sub-assemblies, one leg placed ${model.counts.references} times, ${((performance.now() - started) / 1000).toFixed(1)} s.`);
254
+ } catch (error) {
255
+ ui.setStatus(`Could not build the drone: ${error instanceof Error ? error.message : String(error)}`);
256
+ }
257
+ }
258
+
259
+ async function exportModel(format: ExportFormat): Promise<void> {
260
+ if (!current) return;
261
+ const name = `drone-${current.params.arms}-arms-${current.params.armLength}mm`;
262
+ ui.setStatus(`Writing the ${format.toUpperCase()} assembly...`);
263
+ const manager = bitbybit.occt.assembly.manager;
264
+ const bytes = await withDocument(current, format === "step" ? Z_UP : undefined, ({ document }) => format === "step"
265
+ ? manager.exportDocumentToStep({ document, fileName: `${name}.step`, author: "Drone assembly", organization: "bitbybit.dev", compress: false, tryDownload: false })
266
+ : manager.exportDocumentToGltf({ document, meshDeflection: 0.05, meshAngle: 0.5, internalVerticesMode: false, controlSurfaceDeflection: false, mergeFaces: true, forceUVExport: false, fileName: `${name}.glb`, tryDownload: false }));
267
+ downloadBlob(new Blob([bytes as BlobPart], { type: format === "step" ? "application/step" : "model/gltf-binary" }), `${name}.${format}`);
268
+ ui.setStatus(`${format.toUpperCase()} downloaded: ${(bytes.byteLength / 1024).toFixed(0)} kB with the part tree, names and colours.`);
269
+ }
270
+
271
+ function frame(model: DroneModel): void {
272
+ const extent = model.params.armLength + model.params.propDiameter / 2;
273
+ if (!orbitCamera || (framedFor > 0 && Math.abs(extent - framedFor) / framedFor < 0.3)) return;
274
+ framedFor = extent;
275
+ const distance = extent * 2.2;
276
+ const target = new Vector3(0, model.lift + FLIGHT_CEILING / 2, 0);
277
+ orbitCamera.orbitCamera.resetAndLookAtPoint(new Vector3(distance * 0.55, target.y + distance * 0.42, distance * 0.7), target);
278
+ }
279
+
280
+ function disposeGeometry(group: Group): void {
281
+ group.traverse((object) => { if (isMesh(object)) object.geometry.dispose(); });
282
+ }
283
+
284
+ async function fetchLogo(): Promise<Shape | undefined> {
285
+ try {
286
+ const response = await fetch(LOGO_URL);
287
+ if (!response.ok) return undefined;
288
+ const text = await response.text();
289
+ return await bitbybit.occt.io.loadSTEPorIGESFromText({ text, fileType: Inputs.OCCT.fileTypeEnum.step, adjustZtoY: true });
290
+ } catch {
291
+ return undefined;
292
+ }
293
+ }
294
+
295
+ const logo = await fetchLogo();
296
+ if (!logo) ui.setStatus("The emblem was skipped: the logo could not be fetched from the CDN.");
297
+ await rebuild();
298
+ }
@@ -0,0 +1,58 @@
1
+ export type FinishId = "midnight" | "arctic" | "signal";
2
+
3
+ export type MaterialId = "carbon" | "paint" | "accent" | "emblem" | "aluminium" | "copper" | "steel" | "polymer" | "rubber" | "glass" | "ledGreen" | "ledRed";
4
+
5
+ export interface MaterialSpec {
6
+ colour: string;
7
+ metalness: number;
8
+ roughness: number;
9
+ clearcoat: number;
10
+ emissive?: string;
11
+ }
12
+
13
+ export interface Finish {
14
+ label: string;
15
+ paint: string;
16
+ accent: string;
17
+ emblem: string;
18
+ }
19
+
20
+ export const FINISHES: Record<FinishId, Finish> = {
21
+ midnight: { label: "Midnight", paint: "#1f2b4d", accent: "#f0cebb", emblem: "#f4f4f4" },
22
+ arctic: { label: "Arctic", paint: "#e9eaec", accent: "#ff7a1a", emblem: "#111214" },
23
+ signal: { label: "Signal", paint: "#ff5a1f", accent: "#f4f4f4", emblem: "#111214" },
24
+ };
25
+
26
+ const FIXED: Record<Exclude<MaterialId, "paint" | "accent" | "emblem">, MaterialSpec> = {
27
+ carbon: { colour: "#23262b", metalness: 0.35, roughness: 0.45, clearcoat: 0.3 },
28
+ aluminium: { colour: "#b9bec6", metalness: 1, roughness: 0.32, clearcoat: 0 },
29
+ copper: { colour: "#b87333", metalness: 1, roughness: 0.5, clearcoat: 0 },
30
+ steel: { colour: "#1c1c1e", metalness: 0.9, roughness: 0.42, clearcoat: 0 },
31
+ polymer: { colour: "#2a2d31", metalness: 0.05, roughness: 0.4, clearcoat: 0.6 },
32
+ rubber: { colour: "#111214", metalness: 0, roughness: 0.92, clearcoat: 0 },
33
+ glass: { colour: "#0c1522", metalness: 0.1, roughness: 0.05, clearcoat: 1 },
34
+ ledGreen: { colour: "#22ff66", metalness: 0, roughness: 0.2, clearcoat: 1, emissive: "#22ff66" },
35
+ ledRed: { colour: "#ff2a2a", metalness: 0, roughness: 0.2, clearcoat: 1, emissive: "#ff2a2a" },
36
+ };
37
+
38
+ export function materialSpec(id: MaterialId, finish: FinishId): MaterialSpec {
39
+ const f = FINISHES[finish];
40
+ if (id === "paint") return { colour: f.paint, metalness: 0.1, roughness: 0.25, clearcoat: 1 };
41
+ if (id === "accent") return { colour: f.accent, metalness: 0.85, roughness: 0.35, clearcoat: 0 };
42
+ if (id === "emblem") return { colour: f.emblem, metalness: 0.2, roughness: 0.5, clearcoat: 0.3 };
43
+ return FIXED[id];
44
+ }
45
+
46
+ export function rgba(hex: string): { r: number; g: number; b: number; a: number } {
47
+ const value = parseInt(hex.slice(1), 16);
48
+ return { r: ((value >> 16) & 255) / 255, g: ((value >> 8) & 255) / 255, b: (value & 255) / 255, a: 1 };
49
+ }
50
+
51
+ export function luminance(hex: string): number {
52
+ const { r, g, b } = rgba(hex);
53
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
54
+ }
55
+
56
+ export function edgeColour(surface: string): string {
57
+ return luminance(surface) < 0.3 ? "#f2f2f2" : "#0d0e10";
58
+ }
@@ -0,0 +1,280 @@
1
+ import { ORIGIN, transforms, type Occt, type Point3, type Shape, type Transform } from "./kernel";
2
+ import type { FinishId, MaterialId } from "./materials";
3
+ import * as parts from "./parts";
4
+ import { ARM_TOP, CANOPY_TOP, FRAME, GROUND_LIFT, MOTOR_TOP, PLATE_TOP, TOP_PLATE_TOP, armRootWidth } from "./parts";
5
+
6
+ export type ArmCount = 4 | 6 | 8;
7
+
8
+ export interface DroneParams {
9
+ arms: ArmCount;
10
+ armLength: number;
11
+ propDiameter: number;
12
+ finish: FinishId;
13
+ }
14
+
15
+ export type PartId =
16
+ | "plate" | "canopy" | "hatch" | "emblem" | "honeycomb" | "standoff" | "bolt-m3x8" | "bolt-m3x12" | "bolt-m3x16"
17
+ | "arm" | "motor" | "stator" | "propeller-cw" | "propeller-ccw" | "nut" | "led"
18
+ | "leg" | "damper" | "spring" | "foot" | "gimbal" | "camera" | "lens" | "battery" | "strap" | "gps" | "antenna";
19
+
20
+ export interface Part {
21
+ id: PartId;
22
+
23
+ key: string;
24
+ name: string;
25
+ material: MaterialId;
26
+
27
+ kind: "solid" | "wires";
28
+ shape: Shape;
29
+ }
30
+
31
+ export interface ModuleNode {
32
+ kind: "module";
33
+ id: string;
34
+ name: string;
35
+ parentId?: string;
36
+ placement: Transform;
37
+ }
38
+
39
+ export interface DefinitionNode {
40
+ kind: "definition";
41
+ id: string;
42
+ name: string;
43
+ }
44
+
45
+ export interface ReferenceNode {
46
+ kind: "reference";
47
+ id: string;
48
+ name: string;
49
+ parentId: string;
50
+ definitionId: string;
51
+ placement: Transform;
52
+ }
53
+
54
+ export interface InstanceNode {
55
+ kind: "instance";
56
+ id: string;
57
+ name: string;
58
+ parentId: string;
59
+ partId: PartId;
60
+ placement: Transform;
61
+
62
+ material?: MaterialId;
63
+ }
64
+
65
+ export type Node = ModuleNode | DefinitionNode | ReferenceNode | InstanceNode;
66
+
67
+ export interface Layout {
68
+ params: DroneParams;
69
+ nodes: Node[];
70
+ lift: number;
71
+
72
+ counts: { instances: number; bolts: number; modules: number; definitions: number; references: number };
73
+ }
74
+
75
+ export interface DroneModel extends Layout {
76
+ parts: Part[];
77
+ }
78
+
79
+ export const UNITS = "mm";
80
+
81
+ export const ARM_COUNTS: ArmCount[] = [4, 6, 8];
82
+
83
+ export const LIMITS = {
84
+ armLength: { min: 120, max: 260, step: 5 },
85
+ propDiameter: { min: 100, max: 300, step: 5 },
86
+ } as const;
87
+
88
+ export const TIP_CLEARANCE = 10;
89
+
90
+ export const FLIGHT_CEILING = 90;
91
+
92
+ const CANOPY_REACH = 58;
93
+
94
+ export const defaultParams: DroneParams = { arms: 4, armLength: 185, propDiameter: 230, finish: "midnight" };
95
+
96
+ export function armAngles(arms: ArmCount): number[] {
97
+ return Array.from({ length: arms }, (_, i) => (360 / arms) * i + 180 / arms);
98
+ }
99
+
100
+ export function maxPropDiameter(arms: ArmCount, armLength: number): number {
101
+ const neighbours = 2 * armLength * Math.sin(Math.PI / arms) - TIP_CLEARANCE;
102
+ const canopy = 2 * (armLength - CANOPY_REACH - TIP_CLEARANCE);
103
+ return Math.floor(Math.min(neighbours, canopy) / LIMITS.propDiameter.step) * LIMITS.propDiameter.step;
104
+ }
105
+
106
+ export function clampParams(params: DroneParams): DroneParams {
107
+ const clamp = (value: number, limit: { min: number; max: number }): number => Math.min(Math.max(value, limit.min), limit.max);
108
+ const arms = ARM_COUNTS.includes(params.arms) ? params.arms : 4;
109
+ const armLength = clamp(params.armLength, LIMITS.armLength);
110
+ const propDiameter = Math.min(clamp(params.propDiameter, LIMITS.propDiameter), maxPropDiameter(arms, armLength));
111
+ return { ...params, arms, armLength, propDiameter };
112
+ }
113
+
114
+ const direction = (angle: number): Point3 => [Math.cos((angle * Math.PI) / 180), 0, -Math.sin((angle * Math.PI) / 180)];
115
+
116
+ const onRing = (radius: number, angle: number, y: number): Point3 => {
117
+ const d = direction(angle);
118
+ return [radius * d[0], y, radius * d[2]];
119
+ };
120
+
121
+ const DOWN = transforms.rotationCenterX({ center: ORIGIN, angle: 180 });
122
+
123
+ export function layout(input: DroneParams, withEmblem = true): Layout {
124
+ const params = clampParams(input);
125
+ const { arms, armLength } = params;
126
+ const lift: Point3 = [0, GROUND_LIFT, 0];
127
+ const nodes: Node[] = [];
128
+ const move = (to: Point3): Transform => transforms.translationXYZ({ translation: to });
129
+ const turnX = (angle: number): Transform => transforms.rotationCenterX({ center: ORIGIN, angle });
130
+ const turnY = (angle: number): Transform => transforms.rotationCenterY({ center: ORIGIN, angle });
131
+ const placed = (at: Point3, rotation: Transform): Transform => [...rotation, ...move(at)];
132
+ const module = (id: string, name: string, placement: Transform): void => { nodes.push({ kind: "module", id, name, placement }); };
133
+ const definition = (id: string, name: string): void => { nodes.push({ kind: "definition", id, name }); };
134
+ const reference = (parentId: string, id: string, name: string, definitionId: string, placement: Transform): void => { nodes.push({ kind: "reference", id, name, parentId, definitionId, placement }); };
135
+ const instance = (parentId: string, id: string, name: string, partId: PartId, placement: Transform, material?: MaterialId): void => {
136
+ nodes.push(material ? { kind: "instance", id, name, parentId, partId, placement, material } : { kind: "instance", id, name, parentId, partId, placement });
137
+ };
138
+ const angles = armAngles(arms);
139
+
140
+ module("airframe", "Airframe", move(lift));
141
+ instance("airframe", "plate-bottom", "Bottom plate", "plate", move([0, 0, 0]));
142
+ instance("airframe", "plate-top", "Top plate", "plate", move([0, ARM_TOP, 0]));
143
+ instance("airframe", "canopy", "Canopy", "canopy", move([0, TOP_PLATE_TOP, 0]));
144
+ instance("airframe", "honeycomb", "Canopy honeycomb", "honeycomb", move([0, TOP_PLATE_TOP, 0]));
145
+ instance("airframe", "hatch", "Hatch", "hatch", move([0, CANOPY_TOP, FRAME.canopy.hatchForward]));
146
+ if (withEmblem) instance("airframe", "emblem", "Emblem", "emblem", move([0, CANOPY_TOP, FRAME.canopy.hatchForward]));
147
+ instance("airframe", "gps", "GPS", "gps", move([0, TOP_PLATE_TOP, -FRAME.plate.length / 2 + 5]));
148
+ instance("airframe", "antenna-1", "Antenna 1", "antenna", placed([-14, 0, -FRAME.plate.length / 2 + 8], turnX(225)));
149
+ instance("airframe", "antenna-2", "Antenna 2", "antenna", placed([14, 0, -FRAME.plate.length / 2 + 8], turnX(225)));
150
+ angles.forEach((angle, i) => {
151
+ const between = angle + 180 / arms;
152
+ instance("airframe", `standoff-${i + 1}`, `Standoff ${i + 1}`, "standoff", move(onRing(FRAME.standoff.ring, between, PLATE_TOP)));
153
+ instance("airframe", `standoff-${i + 1}-top-bolt`, `Standoff ${i + 1} top bolt`, "bolt-m3x8", placed(onRing(FRAME.standoff.ring, between, TOP_PLATE_TOP), DOWN));
154
+ instance("airframe", `standoff-${i + 1}-bottom-bolt`, `Standoff ${i + 1} bottom bolt`, "bolt-m3x8", move(onRing(FRAME.standoff.ring, between, 0)));
155
+ });
156
+
157
+ angles.forEach((angle, i) => {
158
+ const n = i + 1;
159
+ const id = `arm-${n}`;
160
+ module(id, `Arm ${n}`, placed(lift, turnY(angle)));
161
+ instance(id, `${id}-tube`, `Arm ${n} tube`, "arm", move([0, 0, 0]));
162
+ instance(id, `${id}-clamp-bolt-1`, `Arm ${n} clamp bolt 1`, "bolt-m3x16", placed([FRAME.armRoot + 6, TOP_PLATE_TOP, 0], DOWN));
163
+ instance(id, `${id}-clamp-bolt-2`, `Arm ${n} clamp bolt 2`, "bolt-m3x16", placed([FRAME.armRoot + 16, TOP_PLATE_TOP, 0], DOWN));
164
+ instance(id, `${id}-motor`, `Arm ${n} motor`, "motor", move([armLength, ARM_TOP, 0]));
165
+ instance(id, `${id}-stator`, `Arm ${n} stator`, "stator", move([armLength, ARM_TOP, 0]));
166
+ for (let k = 0; k < 4; k++) {
167
+ const a = ((45 + 90 * k) * Math.PI) / 180;
168
+ instance(id, `${id}-motor-bolt-${k + 1}`, `Arm ${n} motor bolt ${k + 1}`, "bolt-m3x12", move([armLength + FRAME.motor.boltCircle * Math.cos(a), PLATE_TOP, FRAME.motor.boltCircle * Math.sin(a)]));
169
+ }
170
+ const front = direction(angle)[2] > 0;
171
+ const handed = i % 2 === 0 ? "propeller-cw" : "propeller-ccw";
172
+ instance(id, `${id}-propeller`, `Arm ${n} propeller`, handed, placed([armLength, MOTOR_TOP - 6 + FRAME.propeller.hubBelow, 0], turnY(i * 37)));
173
+ instance(id, `${id}-nut`, `Arm ${n} propeller nut`, "nut", move([armLength, MOTOR_TOP - 6 + FRAME.propeller.hubBelow + FRAME.propeller.hubAbove, 0]));
174
+ instance(id, `${id}-led`, `Arm ${n} LED`, "led", move([armLength - 24, PLATE_TOP, 0]), front ? "ledGreen" : "ledRed");
175
+ });
176
+
177
+ definition("leg", "Leg");
178
+ instance("leg", "leg-tube", "Leg tube", "leg", move([0, 0, 0]));
179
+ instance("leg", "leg-damper", "Damper", "damper", move([FRAME.leg.reach, -FRAME.leg.drop, 0]));
180
+ instance("leg", "leg-spring", "Damper spring", "spring", move([FRAME.leg.reach, -FRAME.leg.drop, 0]));
181
+ instance("leg", "leg-foot", "Foot", "foot", move([FRAME.leg.reach, -FRAME.leg.drop - FRAME.damper.length, 0]));
182
+ instance("leg", "leg-bolt-1", "Leg bolt 1", "bolt-m3x8", move([-FRAME.leg.boltOffset, -3, 0]));
183
+ instance("leg", "leg-bolt-2", "Leg bolt 2", "bolt-m3x8", move([FRAME.leg.boltOffset, -3, 0]));
184
+ module("gear", "Landing gear", move(lift));
185
+ [45, 135, 225, 315].forEach((angle, i) => {
186
+ reference("gear", `leg-${i + 1}`, `Leg ${i + 1}`, "leg", placed(onRing(FRAME.leg.ring, angle, 0), turnY(angle)));
187
+ });
188
+
189
+ module("payload", "Payload", move(lift));
190
+ instance("payload", "gimbal", "Gimbal", "gimbal", move([0, -26, 55]));
191
+ instance("payload", "camera", "Camera", "camera", move([0, -26, 55]));
192
+ instance("payload", "lens", "Lens", "lens", move([0, -26, 55]));
193
+ instance("payload", "battery", "Battery", "battery", move([0, -16, -20]));
194
+ instance("payload", "strap-1", "Battery strap 1", "strap", move([0, -16, -42]));
195
+ instance("payload", "strap-2", "Battery strap 2", "strap", move([0, -16, 2]));
196
+
197
+ const references = new Map<string, number>();
198
+ for (const node of nodes) if (node.kind === "reference") references.set(node.definitionId, (references.get(node.definitionId) ?? 0) + 1);
199
+ const definitionIds = new Set(nodes.filter((node) => node.kind === "definition").map((node) => node.id));
200
+ const times = (node: InstanceNode): number => (definitionIds.has(node.parentId) ? references.get(node.parentId) ?? 0 : 1);
201
+ const instances = nodes.filter((node): node is InstanceNode => node.kind === "instance");
202
+ return {
203
+ params,
204
+ nodes,
205
+ lift: GROUND_LIFT,
206
+ counts: {
207
+ instances: instances.reduce((sum, node) => sum + times(node), 0),
208
+ bolts: instances.filter((node) => node.partId.startsWith("bolt")).reduce((sum, node) => sum + times(node), 0),
209
+ modules: nodes.filter((node) => node.kind === "module").length,
210
+ definitions: definitionIds.size,
211
+ references: nodes.filter((node) => node.kind === "reference").length,
212
+ },
213
+ };
214
+ }
215
+
216
+ export function partOf(parts: Part[], id: PartId): Part {
217
+ const part = parts.find((candidate) => candidate.id === id);
218
+ if (!part) throw new Error(`the ${id} part has not been built`);
219
+ return part;
220
+ }
221
+
222
+ interface PartSpec {
223
+ id: PartId;
224
+ material: MaterialId;
225
+ kind: Part["kind"];
226
+ name: (params: DroneParams) => string;
227
+ key: (params: DroneParams) => string;
228
+ build: (occt: Occt, params: DroneParams, logo: Shape | undefined, built: Part[]) => Promise<Shape>;
229
+ }
230
+
231
+ const fixed = (id: PartId, name: string, material: MaterialId, build: (occt: Occt) => Promise<Shape>, kind: Part["kind"] = "solid"): PartSpec => ({ id, material, kind, name: () => name, key: () => id, build: (occt) => build(occt) });
232
+
233
+ const SPECS: PartSpec[] = [
234
+ fixed("plate", "Carbon plate", "carbon", parts.plate),
235
+ fixed("canopy", "Canopy", "paint", parts.canopy),
236
+ fixed("honeycomb", "Canopy honeycomb", "paint", parts.honeycomb, "wires"),
237
+ { id: "hatch", material: "paint", kind: "solid", name: () => "Hatch", key: () => "hatch", build: (occt, _p, logo) => parts.hatch(occt, logo) },
238
+ fixed("standoff", "Standoff M3x10", "accent", parts.standoff),
239
+ fixed("bolt-m3x8", "Bolt M3x8", "steel", (occt) => parts.bolt(occt, 8)),
240
+ fixed("bolt-m3x12", "Bolt M3x12", "steel", (occt) => parts.bolt(occt, 12)),
241
+ fixed("bolt-m3x16", "Bolt M3x16", "steel", (occt) => parts.bolt(occt, 16)),
242
+ { id: "arm", material: "carbon", kind: "solid", name: (p) => `Arm ${p.armLength} mm`, key: (p) => `arm:${p.armLength}:${p.arms}`, build: (occt, p) => parts.arm(occt, p.armLength, armRootWidth(p.arms)) },
243
+ fixed("motor", "Motor 2806", "aluminium", parts.motor),
244
+ fixed("stator", "Stator", "copper", parts.stator),
245
+ { id: "propeller-cw", material: "accent", kind: "solid", name: (p) => `Propeller ${p.propDiameter} mm CW`, key: (p) => `propeller-cw:${p.propDiameter}`, build: (occt, p) => parts.propeller(occt, p.propDiameter) },
246
+ { id: "propeller-ccw", material: "accent", kind: "solid", name: (p) => `Propeller ${p.propDiameter} mm CCW`, key: (p) => `propeller-ccw:${p.propDiameter}`, build: (occt, _p, _logo, built) => parts.mirrored(occt, partOf(built, "propeller-cw").shape) },
247
+ fixed("nut", "Propeller nut M5", "aluminium", parts.nut),
248
+ fixed("led", "LED", "ledGreen", parts.led),
249
+ fixed("leg", "Landing leg", "carbon", parts.leg),
250
+ fixed("damper", "Landing damper", "aluminium", parts.damper),
251
+ fixed("spring", "Damper spring", "steel", parts.spring),
252
+ fixed("foot", "Rubber foot", "rubber", parts.foot),
253
+ fixed("gimbal", "Gimbal", "aluminium", parts.gimbal),
254
+ fixed("camera", "Camera", "polymer", parts.camera),
255
+ fixed("lens", "Lens", "glass", parts.lens),
256
+ fixed("battery", "Battery 4S", "polymer", parts.battery),
257
+ fixed("strap", "Battery strap", "accent", parts.strap),
258
+ fixed("gps", "GPS", "polymer", parts.gps),
259
+ fixed("antenna", "Antenna", "rubber", parts.antenna),
260
+ ];
261
+
262
+ export async function buildParts(occt: Occt, params: DroneParams, logo?: Shape, previous: Part[] = []): Promise<Part[]> {
263
+ const built: Part[] = [];
264
+ for (const spec of SPECS) {
265
+ const key = spec.id === "hatch" ? (logo ? "hatch:logo" : "hatch:plain") : spec.key(params);
266
+ const kept = previous.find((part) => part.id === spec.id && part.key === key);
267
+ built.push(kept ?? { id: spec.id, key, name: spec.name(params), material: spec.material, kind: spec.kind, shape: await spec.build(occt, params, logo, built) });
268
+ }
269
+ if (logo) {
270
+ const kept = previous.find((part) => part.id === "emblem");
271
+ built.push(kept ?? { id: "emblem", key: "emblem", name: "Emblem", material: "emblem", kind: "solid", shape: await parts.emblem(occt, logo, FRAME.emblem.width, FRAME.emblem.thickness) });
272
+ }
273
+ return built;
274
+ }
275
+
276
+ export async function buildModel(occt: Occt, input: DroneParams, logo?: Shape, previous?: DroneModel): Promise<DroneModel> {
277
+ const params = clampParams(input);
278
+ const built = await buildParts(occt, params, logo, previous?.parts);
279
+ return { ...layout(params, logo !== undefined), parts: built };
280
+ }