circuit-json-to-gltf 0.0.158 → 0.0.159

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.
package/README.md CHANGED
@@ -80,8 +80,59 @@ models throw; open surfaces remain open for the caller's solid validation.
80
80
  Model-loading options `projectBaseUrl`, `authHeaders` and `coordinateTransform`
81
81
  are also supported. Indexed vertices retain their coordinates without snapping.
82
82
 
83
+ ### Assembly explosion stages
84
+
85
+ The real RP2040/NEMA17 example below lifts the cover and bolts together, then
86
+ separates the bolts, motor and spacers. These snapshots render the serialized
87
+ Circuit JSON program directly, including a halfway bolt-removal pose. The TSX
88
+ beside each view is the source that authored that stage.
89
+
90
+ ![RP2040 assembly explosion stages with TSX](./docs/images/rp2040-explosion-stages.png)
91
+
92
+ `cad_explosion_stage` and `cad_explosion_move` records describe a playback program.
93
+ Exports remain assembled by default. Select a pose with the `explosion` option:
94
+
95
+ ```typescript
96
+ import {
97
+ convertCircuitJsonToGltf,
98
+ getAssemblyExplosionFrames,
99
+ } from "circuit-json-to-gltf"
100
+
101
+ const halfway = await convertCircuitJsonToGltf(circuitJson, {
102
+ format: "glb",
103
+ explosion: { throughStageRef: "DEVICE.lift-cover", stageProgress: 0.5 },
104
+ })
105
+
106
+ // Assembled, then every completed stage in declared order. Keep one camera
107
+ // across these GLBs and label each image with frame.name for a storyboard.
108
+ for (const frame of getAssemblyExplosionFrames(circuitJson)) {
109
+ const glb = await convertCircuitJsonToGltf(circuitJson, {
110
+ format: "glb",
111
+ explosion: frame.explosion,
112
+ })
113
+ // Save/render glb and label it with frame.name.
114
+ }
115
+ ```
116
+
117
+ `explosion: {}` finishes all stages. Progress divides the selected stage into its
118
+ ordered moves, retaining all earlier displacement. A stage target expands its
119
+ explicit CAD/reference-surface membership; overlapping targets move once per
120
+ instruction. All references, orders and memberships are validated even when
121
+ selecting an early pose. The assembled input is never mutated.
122
+
123
+ Frames also include evaluated `circuitJson` and guide `lines` in circuit-world
124
+ XYZ (mm, right-handed +X right, +Y top, +Z above). Evaluated poses omit explosion
125
+ instructions to prevent applying them twice after saving. The usual exporter
126
+ converts these positions to glTF +Y-up coordinates. Node and browser entry points
127
+ support the same program, including assemblies without a PCB.
128
+
129
+ Each export is a static pose, not a glTF animation track. Playback supports CAD
130
+ and reference-surface translations; PCB/cable movement, rotation instructions
131
+ and swept collision checking are not supported.
132
+
83
133
  ### Options
84
134
 
135
+ - `explosion`: Optional `{ throughStageRef?, stageProgress? }` selecting a serialized assembly pose; omitted means assembled.
85
136
  - `format`: "gltf" (JSON) or "glb" (binary) - default: "gltf"
86
137
  - `boardTextureResolution`: Resolution for board texture rendering - default: 1024
87
138
  - `showPcbNotes`: Include `pcb_note*` elements in board texture rendering (default: `false`)
package/dist/index.d.ts CHANGED
@@ -32,7 +32,30 @@ type CircuitJsonWithPcbFlex = (CircuitJson[number] | PcbBendRecord | PcbStiffene
32
32
  interface AuthHeaders extends Record<string, string> {
33
33
  Authorization: string;
34
34
  }
35
+ /** A pose within the serialized explosion program. Earlier stages stay applied. */
36
+ interface AssemblyExplosionOptions {
37
+ /** Inclusive qualified stage name. Omit to finish all stages. */
38
+ throughStageRef?: string;
39
+ /** Fraction of the selected stage's sequential moves, from 0 to 1. */
40
+ stageProgress?: number;
41
+ }
42
+ /** Circuit-world points in mm: right-handed +X right, +Y top, +Z above. */
43
+ interface AssemblyExplosionLine {
44
+ stageRef: string;
45
+ targetRef: string;
46
+ points: Point3[];
47
+ }
48
+ interface AssemblyExplosionFrame {
49
+ name: string;
50
+ /** Options for rendering the original assembled document at this pose. */
51
+ explosion?: AssemblyExplosionOptions;
52
+ /** Evaluated pose without instructions, safe to save and reopen. */
53
+ circuitJson: CircuitJsonWithPcbFlex;
54
+ lines: AssemblyExplosionLine[];
55
+ }
35
56
  interface ConversionOptions {
57
+ /** Render a serialized explosion pose. Omit to keep the assembly assembled. */
58
+ explosion?: AssemblyExplosionOptions;
36
59
  /** Override the render fold state. Undefined follows CAD is_on_folded_board in Circuit JSON. */
37
60
  foldPcbs?: boolean;
38
61
  format?: "gltf" | "glb";
@@ -198,6 +221,8 @@ interface GLTFExportOptions {
198
221
  includeCustomExtensions?: boolean;
199
222
  }
200
223
  interface CircuitTo3DOptions {
224
+ /** Evaluate CAD explosion instructions before conversion to scene coordinates. */
225
+ explosion?: AssemblyExplosionOptions;
201
226
  /** Override folding for supported PCB bend regions. Undefined follows CAD is_on_folded_board. */
202
227
  foldPcbs?: boolean;
203
228
  pcbColor?: Color;
@@ -235,6 +260,12 @@ interface BoardRenderOptions {
235
260
  showPcbNotes?: boolean;
236
261
  }
237
262
 
263
+ /** Named assembled and end-of-stage poses for storyboard snapshots or playback.
264
+ * Positions and guide points remain in circuit-world XYZ, mm, right-handed +Z up.
265
+ * Rendering uses the normal exporter frame conversion. Input is never mutated.
266
+ */
267
+ declare function getAssemblyExplosionFrames(assembled: CircuitJsonWithPcbFlex): AssemblyExplosionFrame[];
268
+
238
269
  interface PoppyglErrorOverlayOptions {
239
270
  /** Final image dimensions in pixels, before PoppyGL supersampling. */
240
271
  width: number;
@@ -435,4 +466,4 @@ interface BRepShape {
435
466
  is_negative?: boolean;
436
467
  }
437
468
 
438
- export { type BRepShape, type BoardRenderOptions, type BoundingBox, type Box3D, CAMERA_PRESET_DIRECTIONS, COORDINATE_TRANSFORMS, type CadComponentMesh, type CadComponentMeshOptions, type Camera3D, type CameraFitOptions, type CameraPreset, type CircuitJsonWithPcbFlex, type CircuitTo3DOptions, type Color, type ConversionOptions, type CoordinateTransformConfig, type GLTFExportOptions, type LayerRef, type Light3D, type OBJMaterial, type OBJMesh, type OcctImportJsFactory, type PcbBendRecord, type PcbStiffenerRecord, type Point, type Point3, type PoppyglErrorOverlay, type PoppyglErrorOverlayOptions, type STLMesh, type Scene3D, type Size3, type Triangle, applyCoordinateTransform, clearGLBCache, clearOBJCache, clearSTLCache, convertCircuitJsonTo3D, convertCircuitJsonToGltf, convertSceneToGLTF, getBestCameraPosition, getPoppyglErrorOverlayOptions, loadCadComponentMesh, loadGLB, loadJscadPlan, loadOBJ, loadSTL, renderBoardLayer, renderBoardTextures, setOcctImportJs, transformTriangles };
469
+ export { type AssemblyExplosionFrame, type AssemblyExplosionLine, type AssemblyExplosionOptions, type BRepShape, type BoardRenderOptions, type BoundingBox, type Box3D, CAMERA_PRESET_DIRECTIONS, COORDINATE_TRANSFORMS, type CadComponentMesh, type CadComponentMeshOptions, type Camera3D, type CameraFitOptions, type CameraPreset, type CircuitJsonWithPcbFlex, type CircuitTo3DOptions, type Color, type ConversionOptions, type CoordinateTransformConfig, type GLTFExportOptions, type LayerRef, type Light3D, type OBJMaterial, type OBJMesh, type OcctImportJsFactory, type PcbBendRecord, type PcbStiffenerRecord, type Point, type Point3, type PoppyglErrorOverlay, type PoppyglErrorOverlayOptions, type STLMesh, type Scene3D, type Size3, type Triangle, applyCoordinateTransform, clearGLBCache, clearOBJCache, clearSTLCache, convertCircuitJsonTo3D, convertCircuitJsonToGltf, convertSceneToGLTF, getAssemblyExplosionFrames, getBestCameraPosition, getPoppyglErrorOverlayOptions, loadCadComponentMesh, loadGLB, loadJscadPlan, loadOBJ, loadSTL, renderBoardLayer, renderBoardTextures, setOcctImportJs, transformTriangles };
package/dist/index.js CHANGED
@@ -13696,6 +13696,205 @@ var require_src = __commonJS({
13696
13696
  }
13697
13697
  });
13698
13698
 
13699
+ // lib/utils/evaluate-assembly-explosion.ts
13700
+ import {
13701
+ cad_explosion_move,
13702
+ cad_explosion_stage
13703
+ } from "circuit-json";
13704
+ var plus = (a, b) => ({
13705
+ x: a.x + b.x,
13706
+ y: a.y + b.y,
13707
+ z: a.z + b.z
13708
+ });
13709
+ var zero = () => ({ x: 0, y: 0, z: 0 });
13710
+ function evaluateAssemblyExplosion(assembled, options = {}) {
13711
+ const stages = assembled.filter((record) => record.type === "cad_explosion_stage").map((record) => {
13712
+ const parsed = cad_explosion_stage.safeParse(record);
13713
+ if (!parsed.success) throw new Error("Invalid explosion stage record");
13714
+ return parsed.data;
13715
+ }).sort((a, b) => a.order - b.order);
13716
+ const moves = assembled.filter((record) => record.type === "cad_explosion_move").map((record) => {
13717
+ const parsed = cad_explosion_move.safeParse(record);
13718
+ if (!parsed.success) throw new Error("Invalid explosion movement record");
13719
+ return parsed.data;
13720
+ });
13721
+ const cad = assembled.filter(
13722
+ (record) => record.type === "cad_component"
13723
+ );
13724
+ const surfaces = assembled.filter(
13725
+ (record) => record.type === "cad_reference_surface"
13726
+ );
13727
+ const cadById = new Map(
13728
+ cad.map((record) => [record.cad_component_id, record])
13729
+ );
13730
+ const surfaceById = new Map(
13731
+ surfaces.map((record) => [record.cad_reference_surface_id, record])
13732
+ );
13733
+ const stageById = new Map(
13734
+ stages.map((stage) => [stage.cad_explosion_stage_id, stage])
13735
+ );
13736
+ if (cadById.size !== cad.length || surfaceById.size !== surfaces.length || stageById.size !== stages.length || new Set(stages.map((stage) => stage.name)).size !== stages.length || new Set(moves.map((move) => move.cad_explosion_move_id)).size !== moves.length)
13737
+ throw new Error(
13738
+ "Explosion document contains duplicate identities or stage names"
13739
+ );
13740
+ const expand = (targets) => {
13741
+ const cadIds = /* @__PURE__ */ new Set();
13742
+ const surfaceIds = /* @__PURE__ */ new Set();
13743
+ for (const target of targets) {
13744
+ if (target.type === "cad_component") cadIds.add(target.cad_component_id);
13745
+ else if (target.type === "cad_reference_surface")
13746
+ surfaceIds.add(target.cad_reference_surface_id);
13747
+ else {
13748
+ const stage = stageById.get(target.cad_explosion_stage_id);
13749
+ if (!stage)
13750
+ throw new Error("Explosion movement references a missing stage");
13751
+ for (const id of stage.cad_component_ids) cadIds.add(id);
13752
+ for (const id of stage.cad_reference_surface_ids ?? [])
13753
+ surfaceIds.add(id);
13754
+ }
13755
+ }
13756
+ return { cadIds, surfaceIds };
13757
+ };
13758
+ for (const [order, stage] of stages.entries()) {
13759
+ if (stage.order !== order)
13760
+ throw new Error(
13761
+ `Invalid playback order for explosion stage "${stage.name}"`
13762
+ );
13763
+ if (new Set(stage.cad_component_ids).size !== stage.cad_component_ids.length || new Set(stage.cad_reference_surface_ids).size !== (stage.cad_reference_surface_ids?.length ?? 0))
13764
+ throw new Error(`Duplicate membership in explosion stage "${stage.name}"`);
13765
+ for (const id of stage.cad_component_ids) {
13766
+ const component = cadById.get(id);
13767
+ if (!component)
13768
+ throw new Error(`Missing component in explosion stage "${stage.name}"`);
13769
+ if (component.pcb_component_id)
13770
+ throw new Error(
13771
+ `Explosion stage "${stage.name}" includes unsupported PCB geometry`
13772
+ );
13773
+ if (![
13774
+ component.position.x,
13775
+ component.position.y,
13776
+ component.position.z
13777
+ ].every(Number.isFinite))
13778
+ throw new Error(`Invalid geometry in explosion stage "${stage.name}"`);
13779
+ }
13780
+ for (const id of stage.cad_reference_surface_ids ?? []) {
13781
+ const surface = surfaceById.get(id);
13782
+ if (!surface || ![surface.center.x, surface.center.y, surface.center.z].every(
13783
+ Number.isFinite
13784
+ ))
13785
+ throw new Error(
13786
+ `Missing or invalid reference surface in explosion stage "${stage.name}"`
13787
+ );
13788
+ }
13789
+ }
13790
+ const movesByStage = /* @__PURE__ */ new Map();
13791
+ for (const move of moves) {
13792
+ const owner = stageById.get(move.cad_explosion_stage_id);
13793
+ if (!owner) throw new Error("Explosion movement has no executing stage");
13794
+ const members = expand(move.targets);
13795
+ if ([...members.cadIds].some((id) => !owner.cad_component_ids.includes(id)) || [...members.surfaceIds].some(
13796
+ (id) => !owner.cad_reference_surface_ids?.includes(id)
13797
+ ))
13798
+ throw new Error(
13799
+ `Movement targets are outside explosion stage "${owner.name}"`
13800
+ );
13801
+ movesByStage.set(move.cad_explosion_stage_id, [
13802
+ ...movesByStage.get(move.cad_explosion_stage_id) ?? [],
13803
+ move
13804
+ ]);
13805
+ }
13806
+ for (const [stageId, stageMoves] of movesByStage) {
13807
+ stageMoves.sort((a, b) => a.order - b.order);
13808
+ if (stageMoves.some((move, order) => move.order !== order))
13809
+ throw new Error(
13810
+ `Invalid movement order in explosion stage "${stageById.get(stageId).name}"`
13811
+ );
13812
+ }
13813
+ const progress = options.stageProgress ?? 1;
13814
+ if (!Number.isFinite(progress) || progress < 0 || progress > 1)
13815
+ throw new Error("Explosion progress must be between zero and one");
13816
+ const stop = options.throughStageRef === void 0 ? stages.length - 1 : stages.findIndex((stage) => stage.name === options.throughStageRef);
13817
+ if (options.throughStageRef !== void 0 && stop < 0)
13818
+ throw new Error("Unknown explosion playback stage");
13819
+ const cadOffsets = /* @__PURE__ */ new Map();
13820
+ const surfaceOffsets = /* @__PURE__ */ new Map();
13821
+ const lines = [];
13822
+ for (const [stageIndex, stage] of stages.entries()) {
13823
+ if (stageIndex > stop) break;
13824
+ const stageMoves = movesByStage.get(stage.cad_explosion_stage_id) ?? [];
13825
+ for (const [moveIndex, move] of stageMoves.entries()) {
13826
+ const fraction = stageIndex === stop ? Math.max(0, Math.min(1, progress * stageMoves.length - moveIndex)) : 1;
13827
+ if (!fraction) continue;
13828
+ const offset = {
13829
+ x: move.translation.x * fraction,
13830
+ y: move.translation.y * fraction,
13831
+ z: move.translation.z * fraction
13832
+ };
13833
+ const { cadIds, surfaceIds } = expand(move.targets);
13834
+ for (const id of cadIds) {
13835
+ const prior = cadOffsets.get(id) ?? zero();
13836
+ const from = plus(cadById.get(id).position, prior);
13837
+ if (Math.hypot(offset.x, offset.y, offset.z))
13838
+ lines.push({
13839
+ stageRef: stage.name,
13840
+ targetRef: id,
13841
+ points: [from, plus(from, offset)]
13842
+ });
13843
+ cadOffsets.set(id, plus(prior, offset));
13844
+ }
13845
+ for (const id of surfaceIds)
13846
+ surfaceOffsets.set(id, plus(surfaceOffsets.get(id) ?? zero(), offset));
13847
+ }
13848
+ }
13849
+ return {
13850
+ circuitJson: structuredClone(assembled).filter(
13851
+ (record) => record.type !== "cad_explosion_stage" && record.type !== "cad_explosion_move"
13852
+ ).map((record) => {
13853
+ if (record.type === "cad_component")
13854
+ return {
13855
+ ...record,
13856
+ position: plus(
13857
+ record.position,
13858
+ cadOffsets.get(record.cad_component_id) ?? zero()
13859
+ )
13860
+ };
13861
+ if (record.type === "cad_reference_surface")
13862
+ return {
13863
+ ...record,
13864
+ center: plus(
13865
+ record.center,
13866
+ surfaceOffsets.get(record.cad_reference_surface_id) ?? zero()
13867
+ )
13868
+ };
13869
+ return record;
13870
+ }),
13871
+ stages: stages.map((stage) => stage.name),
13872
+ lines
13873
+ };
13874
+ }
13875
+
13876
+ // lib/utils/get-assembly-explosion-frames.ts
13877
+ function getAssemblyExplosionFrames(assembled) {
13878
+ const full = evaluateAssemblyExplosion(assembled);
13879
+ const initial = full.stages.length ? evaluateAssemblyExplosion(assembled, {
13880
+ throughStageRef: full.stages[0],
13881
+ stageProgress: 0
13882
+ }) : full;
13883
+ return [
13884
+ { name: "Assembled", circuitJson: initial.circuitJson, lines: [] },
13885
+ ...full.stages.map((name) => {
13886
+ const explosion = { throughStageRef: name, stageProgress: 1 };
13887
+ const view = evaluateAssemblyExplosion(assembled, explosion);
13888
+ return {
13889
+ name,
13890
+ explosion,
13891
+ circuitJson: view.circuitJson,
13892
+ lines: view.lines
13893
+ };
13894
+ })
13895
+ ];
13896
+ }
13897
+
13699
13898
  // lib/utils/mesh-orientation.ts
13700
13899
  function getLinearTransformDeterminant(m) {
13701
13900
  return m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
@@ -18798,6 +18997,11 @@ var DEFAULT_COMPONENT_HEIGHT = 2;
18798
18997
  var FAUX_BOARD_MARGIN = 2;
18799
18998
  var DEFAULT_FAUX_BOARD_SIZE = 10;
18800
18999
  async function convertCircuitJsonTo3D(inputCircuitJson, options = {}) {
19000
+ if (options.explosion)
19001
+ inputCircuitJson = evaluateAssemblyExplosion(
19002
+ inputCircuitJson,
19003
+ options.explosion
19004
+ ).circuitJson;
18801
19005
  const {
18802
19006
  boardSideColor,
18803
19007
  componentColor = "rgba(128,128,128,0.5)",
@@ -20701,6 +20905,7 @@ async function convertCircuitJsonToGltf(circuitJson, options = {}) {
20701
20905
  } = options;
20702
20906
  const scene3D = await convertCircuitJsonTo3D(circuitJson, {
20703
20907
  renderBoardTextures: true,
20908
+ explosion: options.explosion,
20704
20909
  foldPcbs: options.foldPcbs,
20705
20910
  textureResolution: boardTextureResolution,
20706
20911
  showPcbNotes,
@@ -20737,6 +20942,7 @@ export {
20737
20942
  convertCircuitJsonTo3D,
20738
20943
  convertCircuitJsonToGltf,
20739
20944
  convertSceneToGLTF,
20945
+ getAssemblyExplosionFrames,
20740
20946
  getBestCameraPosition,
20741
20947
  getPoppyglErrorOverlayOptions,
20742
20948
  loadCadComponentMesh,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "circuit-json-to-gltf",
3
3
  "main": "dist/index.js",
4
4
  "type": "module",
5
- "version": "0.0.158",
5
+ "version": "0.0.159",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/tscircuit/circuit-json-to-gltf.git"
@@ -54,7 +54,7 @@
54
54
  "@types/react-dom": "^19.1.7",
55
55
  "@vitejs/plugin-react": "^5.0.0",
56
56
  "bun-match-svg": "^0.0.12",
57
- "circuit-json": "https://pkg.pr.new/circuit-json@90e54bd",
57
+ "circuit-json": "^0.0.539",
58
58
  "circuit-to-svg": "^0.0.445",
59
59
  "graphics-debug": "^0.0.96",
60
60
  "poppygl": "0.0.32",
@@ -73,7 +73,7 @@
73
73
  "@resvg/resvg-js": "2",
74
74
  "circuit-to-svg": ">=0.0.445",
75
75
  "@tscircuit/circuit-json-util": "*",
76
- "circuit-json": "*"
76
+ "circuit-json": ">=0.0.539"
77
77
  },
78
78
  "peerDependenciesMeta": {
79
79
  "@resvg/resvg-wasm": {
@@ -85,6 +85,6 @@
85
85
  },
86
86
  "overrides": {
87
87
  "@tscircuit/core": "^0.0.1955",
88
- "circuit-json": "https://pkg.pr.new/circuit-json@90e54bd"
88
+ "circuit-json": "^0.0.539"
89
89
  }
90
90
  }