@constructorfleet/sketchforge-engine 1.28.0 → 1.29.1

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 (45) hide show
  1. package/dist/engine.d.ts.map +1 -1
  2. package/dist/engine.js +102 -81
  3. package/dist/engine.js.map +1 -1
  4. package/dist/faceMetadata.d.ts +4 -0
  5. package/dist/faceMetadata.d.ts.map +1 -0
  6. package/dist/faceMetadata.js +71 -0
  7. package/dist/faceMetadata.js.map +1 -0
  8. package/dist/parametricRecompute.d.ts +22 -4
  9. package/dist/parametricRecompute.d.ts.map +1 -1
  10. package/dist/parametricRecompute.js +448 -123
  11. package/dist/parametricRecompute.js.map +1 -1
  12. package/dist/serverCadInterference.d.ts.map +1 -1
  13. package/dist/serverCadInterference.js +3 -1
  14. package/dist/serverCadInterference.js.map +1 -1
  15. package/dist/serverCadMeasure.d.ts.map +1 -1
  16. package/dist/serverCadMeasure.js +4 -1
  17. package/dist/serverCadMeasure.js.map +1 -1
  18. package/dist/serverCadOperations.d.ts.map +1 -1
  19. package/dist/serverCadOperations.js +46 -3
  20. package/dist/serverCadOperations.js.map +1 -1
  21. package/dist/serverCadProjection.d.ts.map +1 -1
  22. package/dist/serverCadProjection.js +8 -2
  23. package/dist/serverCadProjection.js.map +1 -1
  24. package/dist/serverCadProperties.d.ts.map +1 -1
  25. package/dist/serverCadProperties.js +54 -3
  26. package/dist/serverCadProperties.js.map +1 -1
  27. package/dist/serverCadSection.d.ts.map +1 -1
  28. package/dist/serverCadSection.js +5 -2
  29. package/dist/serverCadSection.js.map +1 -1
  30. package/dist/serverCadThickness.d.ts.map +1 -1
  31. package/dist/serverCadThickness.js +3 -1
  32. package/dist/serverCadThickness.js.map +1 -1
  33. package/dist/serverRevolveRecovery.d.ts +5 -0
  34. package/dist/serverRevolveRecovery.d.ts.map +1 -0
  35. package/dist/serverRevolveRecovery.js +35 -0
  36. package/dist/serverRevolveRecovery.js.map +1 -0
  37. package/dist/serverShapeBooleans.d.ts.map +1 -1
  38. package/dist/serverShapeBooleans.js +4 -1
  39. package/dist/serverShapeBooleans.js.map +1 -1
  40. package/dist/skfProject.d.ts +1 -1
  41. package/dist/skfProject.js +1 -1
  42. package/dist/stlImport.d.ts.map +1 -1
  43. package/dist/stlImport.js +9 -1
  44. package/dist/stlImport.js.map +1 -1
  45. package/package.json +1 -1
@@ -1,12 +1,41 @@
1
1
  import { buildGroupFromSelection } from "./serverShapeBooleans.js";
2
2
  import { groupChildFrame } from "./serverShapeGroups.js";
3
3
  import { resizedShapeSize, shapeDepth, shapeWidth } from "./workplaneShapes.js";
4
- import { allEdgeTreatmentEdgeCount, applyDraftPrism, applyEdgeTreatment, applySketchFaceDraft, shapeWithCadResult, } from "./serverCadOperations.js";
4
+ import { allEdgeTreatmentEdgeCount, applyDraftPrism, applyEdgeTreatment, applySketchFaceDraft, exactPlainSketchRevolveResult, sketchResizeFactors, shapeWithCadResult, } from "./serverCadOperations.js";
5
5
  import { shapeFaces } from "./serverCadShell.js";
6
6
  import { cadSketchRegions, cadSketchSweepPaths } from "./sketchCadProfile.js";
7
- import { draftFaceForSketchSegment, legacyDraftSegmentForShape } from "./faceDraftSegmentLineage.js";
7
+ import { draftFaceForSketchSegment, legacyDraftSegmentForShape, sketchSegmentForDraftFace } from "./faceDraftSegmentLineage.js";
8
8
  import { retainedDraftSourcePlacement } from "./sketchFaceDraftKernel.js";
9
9
  import { edgeIndexesForSketchSourceEdges } from "./sketchEdgeSegmentLineage.js";
10
+ import { sketchExtrusionShapeFromRequest } from "./sketchExtrusionRequest.js";
11
+ import { invalidSketchSweepProfile, sketchSweepShapeFromRequest } from "./sketchSweepRequest.js";
12
+ import { serverManifoldRuntime } from "./serverManifoldRuntime.js";
13
+ import { isRevolveShape, rebuiltRevolveShape, requestedRevolveSettings } from "./revolveRequests.js";
14
+ import { preserveUnambiguousFaceMetadata } from "./faceMetadata.js";
15
+ export function deterministicRecomputeSchedule(nodes, affected, dependents) {
16
+ const indegree = new Map();
17
+ for (const id of affected) {
18
+ indegree.set(id, (nodes.get(id)?.dependencies ?? []).filter((dependency) => affected.has(dependency)).length);
19
+ }
20
+ const ready = [...affected].filter((id) => indegree.get(id) === 0)
21
+ .sort((left, right) => nodes.get(left).order - nodes.get(right).order);
22
+ const schedule = [];
23
+ while (ready.length) {
24
+ const id = ready.shift();
25
+ schedule.push(id);
26
+ for (const parent of dependents.get(id) ?? []) {
27
+ if (!affected.has(parent))
28
+ continue;
29
+ const remaining = indegree.get(parent) - 1;
30
+ indegree.set(parent, remaining);
31
+ if (remaining === 0) {
32
+ ready.push(parent);
33
+ ready.sort((left, right) => nodes.get(left).order - nodes.get(right).order);
34
+ }
35
+ }
36
+ }
37
+ return schedule.length === affected.size ? schedule : undefined;
38
+ }
10
39
  /** Where a treatment was applied, so reverting it later carries any move made since. */
11
40
  export function edgeTreatmentAppliedFrame(shape) {
12
41
  return {
@@ -24,8 +53,73 @@ export function edgeTreatmentAppliedFrame(shape) {
24
53
  mirrorZ: Boolean(shape.mirrorZ),
25
54
  };
26
55
  }
56
+ async function replayRetainedFaceDraft(original, treatmentSource, rebuiltSource, previous) {
57
+ if (original.faceDraft === undefined || treatmentSource.faceDraft !== undefined)
58
+ return treatmentSource;
59
+ const profileChanged = previous
60
+ ? JSON.stringify(previous.sketchProfile) !== JSON.stringify(original.sketchProfile)
61
+ || JSON.stringify(previous.sketchRevolve) !== JSON.stringify(original.sketchRevolve)
62
+ || previous.draftPrismAngle !== original.draftPrismAngle
63
+ : JSON.stringify(original.sketchProfile) !== JSON.stringify(rebuiltSource.sketchProfile);
64
+ const legacySegmentMatch = profileChanged && !original.faceDraftSourceSegmentId
65
+ ? await legacyDraftSegmentForShape(previous ?? original)
66
+ : undefined;
67
+ if (legacySegmentMatch?.status === "ambiguous") {
68
+ throw new Error("The saved face draft does not identify one source sketch segment.");
69
+ }
70
+ const selectedFaceSegment = !original.faceDraftSourceSegmentId
71
+ ? await sketchSegmentForDraftFace(previous ?? treatmentSource, original.faceDraft.sourceFaceId)
72
+ : undefined;
73
+ const sourceSegmentId = original.faceDraftSourceSegmentId
74
+ ?? (legacySegmentMatch?.status === "matched" ? legacySegmentMatch.segmentId : undefined)
75
+ ?? (selectedFaceSegment?.status === "matched" ? selectedFaceSegment.segmentId : undefined);
76
+ const segmentMatch = sourceSegmentId
77
+ ? await draftFaceForSketchSegment(treatmentSource, sourceSegmentId)
78
+ : undefined;
79
+ if (segmentMatch && segmentMatch.status !== "matched"
80
+ && (segmentMatch.status !== "unsupported" || original.faceDraftSourceSegmentId !== undefined)) {
81
+ throw new Error("The selected sketch segment no longer maps to exactly one extrusion side face.");
82
+ }
83
+ const useSegmentLineage = segmentMatch?.status === "matched";
84
+ const sourceNormal = useSegmentLineage ? segmentMatch.normal : original.faceDraft.sourceFaceNormal;
85
+ if (!sourceNormal)
86
+ throw new Error("The selected source face has no stable planar reference.");
87
+ const matchingFaces = useSegmentLineage
88
+ ? [{ id: segmentMatch.faceId }]
89
+ : (await shapeFaces(treatmentSource)).filter((face) => face.surfaceType === "plane" && face.normal
90
+ && Math.hypot(face.normal.x - sourceNormal.x, face.normal.y - sourceNormal.y, face.normal.z - sourceNormal.z) <= 1e-5);
91
+ if (matchingFaces.length !== 1)
92
+ throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
93
+ const matchedFace = matchingFaces[0];
94
+ const faceDraft = original.faceDraft;
95
+ const refreshedFaceDraft = profileChanged && useSegmentLineage
96
+ ? { ...faceDraft, sourceFaceId: matchedFace.id, sourceFaceNormal: sourceNormal }
97
+ : faceDraft;
98
+ const drafted = shapeWithCadResult(treatmentSource, await applySketchFaceDraft(treatmentSource, {
99
+ ...faceDraft,
100
+ sourceFaceId: matchedFace.id,
101
+ }));
102
+ const keepSourcePlacement = original.sketchOperation === "extrude"
103
+ || (original.edgeTreatments?.length ?? 0) > 0
104
+ || (original.edgeTreatmentHistory?.length ?? 0) > 0;
105
+ const sourceFaceIds = (profileChanged ? treatmentSource.faceIds : previous?.faceIds ?? treatmentSource.faceIds)?.length
106
+ ? (profileChanged ? treatmentSource.faceIds : previous?.faceIds ?? treatmentSource.faceIds)
107
+ : original.faceDraftSourceFaceIds;
108
+ return {
109
+ ...drafted,
110
+ ...(keepSourcePlacement
111
+ ? retainedDraftSourcePlacement(treatmentSource, drafted.cadBrepFrame, treatmentSource.cadBrepFrame)
112
+ : {}),
113
+ faceDraft: refreshedFaceDraft,
114
+ faceDraftSourceFaceIds: sourceFaceIds?.includes(refreshedFaceDraft.sourceFaceId)
115
+ ? sourceFaceIds
116
+ : [...(sourceFaceIds ?? []), refreshedFaceDraft.sourceFaceId],
117
+ ...(useSegmentLineage ? { faceDraftSourceSegmentId: segmentMatch.segmentId } : {}),
118
+ faceDraftSourceFrame: original.faceDraftSourceFrame ?? treatmentSource.cadBrepFrame,
119
+ };
120
+ }
27
121
  /** Replay one supported all-edge treatment on rebuilt source geometry without carrying transient edge indexes forward. */
28
- export async function replaySingleAllEdgeTreatment(original, rebuilt, draftPrismAngle = original.draftPrismAngle) {
122
+ export async function replaySingleAllEdgeTreatment(original, rebuilt, draftPrismAngle = original.draftPrismAngle, previous) {
29
123
  const features = original.edgeTreatments ?? [];
30
124
  const history = original.edgeTreatmentHistory ?? [];
31
125
  if (features.length === 0 && history.length === 0)
@@ -92,53 +186,7 @@ export async function replaySingleAllEdgeTreatment(original, rebuilt, draftPrism
92
186
  : {}),
93
187
  };
94
188
  }
95
- if (original.faceDraft !== undefined && treatmentSource.faceDraft === undefined) {
96
- const profileChanged = JSON.stringify(original.sketchProfile) !== JSON.stringify(rebuilt.sketchProfile);
97
- const legacySegmentMatch = profileChanged && !original.faceDraftSourceSegmentId
98
- ? await legacyDraftSegmentForShape(original)
99
- : undefined;
100
- if (legacySegmentMatch?.status === "ambiguous") {
101
- throw new Error("The saved face draft does not identify one source sketch segment.");
102
- }
103
- const sourceSegmentId = original.faceDraftSourceSegmentId
104
- ?? (legacySegmentMatch?.status === "matched" ? legacySegmentMatch.segmentId : undefined);
105
- const segmentMatch = sourceSegmentId
106
- ? await draftFaceForSketchSegment(treatmentSource, sourceSegmentId)
107
- : undefined;
108
- if (segmentMatch && segmentMatch.status !== "matched"
109
- && (segmentMatch.status !== "unsupported" || original.faceDraftSourceSegmentId !== undefined)) {
110
- throw new Error("The selected sketch segment no longer maps to exactly one extrusion side face.");
111
- }
112
- const useSegmentLineage = segmentMatch?.status === "matched";
113
- const sourceNormal = useSegmentLineage ? segmentMatch.normal : original.faceDraft.sourceFaceNormal;
114
- if (!sourceNormal)
115
- throw new Error("The selected source face has no stable planar reference.");
116
- const matchingFaces = useSegmentLineage
117
- ? [{ id: segmentMatch.faceId }]
118
- : (await shapeFaces(treatmentSource)).filter((face) => face.surfaceType === "plane" && face.normal
119
- && Math.hypot(face.normal.x - sourceNormal.x, face.normal.y - sourceNormal.y, face.normal.z - sourceNormal.z) <= 1e-5);
120
- if (matchingFaces.length !== 1)
121
- throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
122
- const matchedFace = matchingFaces[0];
123
- const faceSegmentMatch = useSegmentLineage
124
- ? segmentMatch
125
- : undefined;
126
- const faceDraft = original.faceDraft;
127
- const drafted = shapeWithCadResult(treatmentSource, await applySketchFaceDraft(treatmentSource, {
128
- ...faceDraft,
129
- sourceFaceId: matchedFace.id,
130
- }));
131
- treatmentSource = {
132
- ...drafted,
133
- ...retainedDraftSourcePlacement(treatmentSource, drafted.cadBrepFrame, treatmentSource.cadBrepFrame),
134
- faceDraft: useSegmentLineage
135
- ? { ...faceDraft, sourceFaceId: matchedFace.id, sourceFaceNormal: sourceNormal }
136
- : faceDraft,
137
- ...(useSegmentLineage ? { faceDraftSourceFaceIds: treatmentSource.faceIds } : {}),
138
- ...(faceSegmentMatch ? { faceDraftSourceSegmentId: faceSegmentMatch.segmentId } : {}),
139
- faceDraftSourceFrame: original.faceDraftSourceFrame ?? treatmentSource.cadBrepFrame,
140
- };
141
- }
189
+ treatmentSource = await replayRetainedFaceDraft(original, treatmentSource, rebuilt, previous);
142
190
  const result = await applyEdgeTreatment(treatmentSource, {
143
191
  kind: previousFeature.kind,
144
192
  amount: previousFeature.amount,
@@ -207,92 +255,369 @@ async function replaySelectedEdgeTreatment(original, rebuilt, draftPrismAngle) {
207
255
  edgeTreatmentHistory: [{ ...entry, feature: replayedFeature, before: structuredClone(before), appliedFrame: edgeTreatmentAppliedFrame(treated) }],
208
256
  };
209
257
  }
210
- /** Find a retained sketch output anywhere in the feature tree, replace it, then rebuild boolean ancestors bottom-up. */
211
- export async function recomputeSketchOutput(roots, sourceId, replacement) {
258
+ /** Replace a rebuilt sketch output in a project snapshot before scheduling its dependents. */
259
+ export function replaceSketchOutput(roots, sourceId, replacement) {
212
260
  let matchCount = 0;
213
- let updated;
214
- const visit = async (shape) => {
261
+ const visit = (shape) => {
215
262
  if (shape.id === replacement.id && shape.sketchSourceId === sourceId) {
216
263
  matchCount += 1;
217
- updated = replacement;
218
264
  return replacement;
219
265
  }
220
266
  if (!shape.groupedShapes?.length)
221
267
  return shape;
222
- const children = [];
223
- let changed = false;
224
- for (const child of shape.groupedShapes) {
225
- const next = await visit(child);
226
- children.push(next);
227
- changed ||= next !== child;
228
- }
229
- if (!changed)
230
- return shape;
231
- // Plain groups are containers; boolean groups have retained operand hole
232
- // modes and exact BREP. Rebuild those in dependency order after their child.
233
- if (!shape.cadBrep || !children.some((child) => child.hole)) {
234
- return { ...shape, groupedShapes: children };
235
- }
236
- const result = await buildGroupFromSelection(children);
237
- if ("error" in result || result.cutRemovedNothing) {
238
- throw new Error("The edited sketch made a dependent boolean invalid or ineffective.");
239
- }
240
- // `children` are expressed in this group's child frame, so the rebuilt
241
- // group comes back placed in that frame at its natural size. Put it through
242
- // the retained group's frame -- resize, mirror, turn, then move -- the same
243
- // way ungrouping puts each child, and keep the turn, mirror and resize on
244
- // the rebuilt group so its geometry is drawn under them too.
245
- const rebuilt = result.group;
246
- const frame = groupChildFrame(shape);
247
- const width = shapeWidth(rebuilt) * frame.scale.x;
248
- const depth = shapeDepth(rebuilt) * frame.scale.z;
249
- const height = rebuilt.height * frame.scale.y;
250
- const center = frame.toParent(rebuilt.x, (rebuilt.elevation ?? 0) + rebuilt.height / 2, rebuilt.z);
268
+ const children = shape.groupedShapes.map(visit);
269
+ return children.some((child, index) => child !== shape.groupedShapes[index])
270
+ ? { ...shape, groupedShapes: children }
271
+ : shape;
272
+ };
273
+ return { shapes: roots.map(visit), matchCount };
274
+ }
275
+ function sourceRebuildScale(shape, natural, previous) {
276
+ if (previous?.faceDraft && !shape.faceDraft) {
277
+ return previous.faceDraftSourceScale ?? sketchResizeFactors(previous);
278
+ }
279
+ const sourceFrame = shape.faceDraftSourceFrame ?? shape.draftPrismSourceFrame ?? shape.cadBrepFrame;
280
+ const ratio = (current, source, fallback) => source && source > 0 ? current / source : fallback > 0 ? current / fallback : 1;
281
+ if (shape.draftPrismAngle !== undefined)
282
+ return { width: 1, depth: 1, height: 1 };
283
+ if (shape.faceDraft) {
284
+ return shape.faceDraftSourceScale ?? {
285
+ width: 1,
286
+ depth: 1,
287
+ height: ratio(shape.height, sourceFrame?.height, natural.height),
288
+ };
289
+ }
290
+ const treatmentSource = shape.edgeTreatmentHistory?.[0]?.before;
291
+ if (treatmentSource?.sketchOperation === "extrude" && treatmentSource.cadBrep) {
292
+ return sketchResizeFactors(treatmentSource);
293
+ }
294
+ if (shape.sketchOperation === "sweep") {
251
295
  return {
252
- ...rebuilt,
253
- id: shape.id,
254
- name: shape.name,
255
- color: shape.color,
256
- locked: shape.locked,
257
- x: center.x,
258
- z: center.z,
259
- elevation: center.y - height / 2,
260
- width,
261
- depth,
262
- height,
263
- size: resizedShapeSize(width, depth),
264
- rotation: shape.rotation,
265
- rotationX: shape.rotationX,
266
- rotationZ: shape.rotationZ,
267
- mirrorX: shape.mirrorX,
268
- mirrorY: shape.mirrorY,
269
- mirrorZ: shape.mirrorZ,
270
- // The group builder creates fresh child IDs because ordinary grouping
271
- // is a new operation. Recompute is different: each retained child is the
272
- // same feature with new geometry, so keep its existing feature identity.
273
- groupedShapes: result.group.groupedShapes?.map((child, index) => ({
274
- ...child,
275
- id: children[index]?.id ?? child.id,
276
- })),
296
+ width: ratio(shape.width, sourceFrame?.width ?? shape.importedMesh?.baseWidth, natural.width),
297
+ depth: ratio(shape.depth, sourceFrame?.depth ?? shape.importedMesh?.baseDepth, natural.depth),
298
+ height: ratio(shape.height, sourceFrame?.height ?? shape.importedMesh?.baseHeight, natural.height),
277
299
  };
300
+ }
301
+ return { width: 1, depth: 1, height: 1 };
302
+ }
303
+ async function rebuildSketchSourceRecipe(recipe, previous) {
304
+ if (!recipe.sketchProfile || !recipe.sketchSourceId || !recipe.sketchOperation) {
305
+ throw new Error(`Feature node ${recipe.id} does not contain a rebuildable sketch recipe.`);
306
+ }
307
+ if (recipe.shell) {
308
+ throw new Error(`Feature node ${recipe.id} has a shell that cannot be replayed from the stored sketch recipe.`);
309
+ }
310
+ const sourceFrame = recipe.faceDraftSourceFrame ?? recipe.draftPrismSourceFrame ?? recipe.cadBrepFrame;
311
+ let natural;
312
+ if (recipe.sketchOperation === "extrude") {
313
+ const sourceHeight = recipe.draftPrismSourceHeight ?? sourceFrame?.height ?? recipe.height;
314
+ natural = await sketchExtrusionShapeFromRequest({
315
+ id: recipe.id,
316
+ sketchSourceId: recipe.sketchSourceId,
317
+ name: recipe.name,
318
+ color: recipe.color,
319
+ hole: recipe.hole,
320
+ profile: recipe.sketchProfile,
321
+ height: sourceHeight,
322
+ x: 0,
323
+ z: 0,
324
+ elevation: 0,
325
+ rotation: recipe.rotation,
326
+ rotationX: recipe.rotationX,
327
+ rotationZ: recipe.rotationZ,
328
+ });
329
+ }
330
+ else if (recipe.sketchOperation === "sweep") {
331
+ const invalidProfile = invalidSketchSweepProfile(recipe.sketchProfile);
332
+ if (invalidProfile)
333
+ throw new Error(invalidProfile);
334
+ natural = await sketchSweepShapeFromRequest({
335
+ id: recipe.id,
336
+ name: recipe.name,
337
+ color: recipe.color,
338
+ hole: recipe.hole,
339
+ profile: recipe.sketchProfile,
340
+ x: recipe.x - (sourceFrame?.x ?? 0),
341
+ z: recipe.z - (sourceFrame?.z ?? 0),
342
+ elevation: (recipe.elevation ?? 0) - (sourceFrame?.elevation ?? 0),
343
+ rotation: recipe.rotation,
344
+ rotationX: recipe.rotationX,
345
+ rotationZ: recipe.rotationZ,
346
+ });
347
+ }
348
+ else if (isRevolveShape(recipe) && recipe.sketchRevolve) {
349
+ const runtime = await serverManifoldRuntime();
350
+ const seed = sourceFrame ? {
351
+ ...recipe,
352
+ x: sourceFrame.x,
353
+ z: sourceFrame.z,
354
+ elevation: sourceFrame.elevation,
355
+ } : recipe;
356
+ natural = rebuiltRevolveShape(runtime, seed, {
357
+ profile: recipe.sketchProfile,
358
+ settings: recipe.sketchRevolve,
359
+ });
360
+ }
361
+ else {
362
+ throw new Error(`Feature node ${recipe.id} has unsupported sketch operation ${recipe.sketchOperation}.`);
363
+ }
364
+ if (previous && !recipe.faceDraft && !(recipe.edgeTreatments?.length || recipe.edgeTreatmentHistory?.length)
365
+ && JSON.stringify(previous.sketchProfile) === JSON.stringify(recipe.sketchProfile)
366
+ && (previous.faceIds?.length || previous.faceColors)) {
367
+ natural = await preserveUnambiguousFaceMetadata(previous, {
368
+ ...recipe,
369
+ ...natural,
370
+ sketchProfile: recipe.sketchProfile,
371
+ sketchOperation: recipe.sketchOperation,
372
+ sketchRevolve: recipe.sketchRevolve,
373
+ faceIds: undefined,
374
+ faceColors: undefined,
375
+ });
376
+ }
377
+ const scale = sourceRebuildScale(recipe, natural, previous);
378
+ const metadata = { ...recipe };
379
+ delete metadata.importedMesh;
380
+ delete metadata.cadBrep;
381
+ delete metadata.cadBrepFrame;
382
+ delete metadata.faceIds;
383
+ delete metadata.faceColors;
384
+ delete metadata.edgeTreatments;
385
+ delete metadata.edgeTreatmentHistory;
386
+ delete metadata.faceDraft;
387
+ delete metadata.cadDisplayEdges;
388
+ delete metadata.cadDisplayEdgesVersion;
389
+ const rebuilt = {
390
+ ...metadata,
391
+ ...natural,
392
+ id: recipe.id,
393
+ name: recipe.name,
394
+ color: recipe.color,
395
+ hole: recipe.hole,
396
+ sketchSourceId: recipe.sketchSourceId,
397
+ sketchProfile: recipe.sketchProfile,
398
+ sketchOperation: recipe.sketchOperation,
399
+ sketchRevolve: recipe.sketchRevolve,
400
+ ...(recipe.sketchOperation === "sweep" ? {
401
+ x: recipe.x,
402
+ z: recipe.z,
403
+ elevation: recipe.elevation,
404
+ } : {}),
405
+ ...(natural.faceIds || (recipe.faceDraft && recipe.sketchOperation === "sweep")
406
+ ? { faceIds: natural.faceIds ?? (await shapeFaces(natural)).map((face) => face.id) }
407
+ : recipe.faceIds ? { faceIds: recipe.faceIds } : {}),
408
+ mirrorX: recipe.mirrorX,
409
+ mirrorY: recipe.mirrorY,
410
+ mirrorZ: recipe.mirrorZ,
411
+ width: natural.width * scale.width,
412
+ depth: natural.depth * scale.depth,
413
+ height: natural.height * scale.height,
414
+ size: Math.max(natural.width * scale.width, natural.depth * scale.depth),
415
+ faceDraft: undefined,
416
+ faceDraftSourceFrame: undefined,
417
+ faceDraftSourceFaceIds: undefined,
418
+ faceDraftSourceSegmentId: undefined,
419
+ faceDraftSourceScale: previous?.faceDraft && !recipe.faceDraft ? undefined : recipe.faceDraftSourceScale,
420
+ ...(recipe.draftPrismAngle === undefined ? { draftPrismAngle: undefined } : {}),
278
421
  };
279
- try {
280
- const shapes = [];
281
- for (const root of roots)
282
- shapes.push(await visit(root));
283
- if (matchCount === 0)
284
- return { ok: false, reason: "dependency_missing" };
285
- if (matchCount !== 1)
286
- return { ok: false, reason: "dependency_ambiguous" };
287
- return { ok: true, shapes, updated: updated, matchCount };
288
- }
289
- catch (error) {
422
+ const placed = recipe.sketchOperation === "extrude"
423
+ ? {
424
+ ...rebuilt,
425
+ ...retainedDraftSourcePlacement(recipe, natural.cadBrepFrame, recipe.faceDraft && !recipe.edgeTreatments?.length ? recipe.cadBrepFrame : undefined),
426
+ }
427
+ : rebuilt;
428
+ if (recipe.sketchOperation === "revolve" && recipe.faceDraft) {
429
+ const exact = shapeWithCadResult(placed, await exactPlainSketchRevolveResult(placed));
430
+ if (recipe.edgeTreatments?.length || recipe.edgeTreatmentHistory?.length) {
431
+ return replaySingleAllEdgeTreatment(recipe, exact, recipe.draftPrismAngle, previous);
432
+ }
433
+ return replayRetainedFaceDraft(recipe, exact, natural, previous);
434
+ }
435
+ if (recipe.edgeTreatments?.length || recipe.edgeTreatmentHistory?.length) {
436
+ return replaySingleAllEdgeTreatment(recipe, placed, recipe.draftPrismAngle, previous);
437
+ }
438
+ if (recipe.faceDraft)
439
+ return replayRetainedFaceDraft(recipe, placed, natural, previous);
440
+ if (recipe.draftPrismAngle !== undefined) {
290
441
  return {
291
- ok: false,
292
- reason: "recompute_failed",
293
- message: error instanceof Error ? error.message : "A dependent feature could not be recomputed.",
442
+ ...shapeWithCadResult(placed, await applyDraftPrism(placed, { angle: recipe.draftPrismAngle })),
443
+ draftPrismAngle: recipe.draftPrismAngle,
444
+ draftPrismSourceHeight: recipe.draftPrismSourceHeight ?? natural.height,
445
+ ...(recipe.draftPrismSourceFrame ?? natural.cadBrepFrame
446
+ ? { draftPrismSourceFrame: recipe.draftPrismSourceFrame ?? natural.cadBrepFrame }
447
+ : {}),
294
448
  };
295
449
  }
450
+ return placed;
451
+ }
452
+ /**
453
+ * Recompute every dependent node in deterministic dependency order.
454
+ *
455
+ * `project` already contains the newly rebuilt outputs named by
456
+ * `changedSourceIds`; only their retained dependents are evaluated here.
457
+ */
458
+ export async function recompute(project, changedSourceIds, previousProject = project) {
459
+ const nodes = new Map();
460
+ const outputsBySource = new Map();
461
+ const active = new Set();
462
+ let order = 0;
463
+ const collect = (shape) => {
464
+ if (active.has(shape)) {
465
+ return { ok: false, reason: "dependency_cycle", message: `Feature node ${shape.id} creates a dependency cycle.` };
466
+ }
467
+ if (nodes.has(shape.id)) {
468
+ return { ok: false, reason: "dependency_ambiguous", message: `Feature node ${shape.id} appears more than once in the project tree.` };
469
+ }
470
+ active.add(shape);
471
+ const children = shape.groupedShapes ?? [];
472
+ nodes.set(shape.id, { shape, dependencies: children.map((child) => child.id), order: order++ });
473
+ if (shape.sketchSourceId) {
474
+ const outputs = outputsBySource.get(shape.sketchSourceId) ?? [];
475
+ outputs.push(shape.id);
476
+ outputsBySource.set(shape.sketchSourceId, outputs);
477
+ }
478
+ for (const child of children) {
479
+ const failure = collect(child);
480
+ if (failure)
481
+ return failure;
482
+ }
483
+ active.delete(shape);
484
+ return undefined;
485
+ };
486
+ for (const root of project.shapes) {
487
+ const failure = collect(root);
488
+ if (failure)
489
+ return failure;
490
+ }
491
+ const changedNodeIds = [];
492
+ const previousOutputsBySource = new Map();
493
+ const collectPrevious = (shape) => {
494
+ if (shape.sketchSourceId) {
495
+ const outputs = previousOutputsBySource.get(shape.sketchSourceId) ?? [];
496
+ outputs.push(shape);
497
+ previousOutputsBySource.set(shape.sketchSourceId, outputs);
498
+ }
499
+ shape.groupedShapes?.forEach(collectPrevious);
500
+ };
501
+ previousProject.shapes.forEach(collectPrevious);
502
+ const sourceForChangedNode = new Map();
503
+ for (const sourceId of changedSourceIds) {
504
+ const outputs = outputsBySource.get(sourceId) ?? [];
505
+ if (outputs.length === 0)
506
+ return { ok: false, reason: "dependency_missing", message: `Sketch source ${sourceId} has no output node.` };
507
+ if (outputs.length !== 1)
508
+ return { ok: false, reason: "dependency_ambiguous", message: `Sketch source ${sourceId} has multiple output nodes.` };
509
+ changedNodeIds.push(outputs[0]);
510
+ sourceForChangedNode.set(outputs[0], sourceId);
511
+ }
512
+ if (changedNodeIds.length === 0)
513
+ return { ok: false, reason: "dependency_missing", message: "No changed sketch sources were supplied." };
514
+ const dependents = new Map();
515
+ for (const [id, node] of nodes) {
516
+ for (const dependency of node.dependencies) {
517
+ if (!nodes.has(dependency)) {
518
+ return { ok: false, reason: "dependency_missing", message: `Feature node ${id} depends on missing node ${dependency}.` };
519
+ }
520
+ const parents = dependents.get(dependency) ?? [];
521
+ parents.push(id);
522
+ dependents.set(dependency, parents);
523
+ }
524
+ }
525
+ const affected = new Set(changedNodeIds);
526
+ const pending = [...changedNodeIds];
527
+ while (pending.length) {
528
+ const dependency = pending.shift();
529
+ for (const parent of dependents.get(dependency) ?? []) {
530
+ if (!affected.has(parent)) {
531
+ affected.add(parent);
532
+ pending.push(parent);
533
+ }
534
+ }
535
+ }
536
+ const schedule = deterministicRecomputeSchedule(nodes, affected, dependents);
537
+ if (!schedule) {
538
+ const nodeId = [...affected].find((id) => (nodes.get(id)?.dependencies ?? []).some((dependency) => affected.has(dependency))) ?? [...affected][0];
539
+ return { ok: false, reason: "dependency_cycle", message: `Feature node ${nodeId} is part of a dependency cycle.` };
540
+ }
541
+ const rebuilt = new Map();
542
+ for (const id of schedule) {
543
+ const node = nodes.get(id);
544
+ const shape = node.shape;
545
+ if (changedNodeIds.includes(id)) {
546
+ try {
547
+ const previousOutputs = previousOutputsBySource.get(sourceForChangedNode.get(id));
548
+ if (previousOutputs && previousOutputs.length > 1) {
549
+ return { ok: false, reason: "dependency_ambiguous", message: `Sketch source ${sourceForChangedNode.get(id)} has multiple previous output nodes.` };
550
+ }
551
+ rebuilt.set(id, await rebuildSketchSourceRecipe(shape, previousOutputs?.[0]));
552
+ }
553
+ catch (error) {
554
+ const detail = error instanceof Error ? error.message : "an unexpected recompute error occurred";
555
+ return { ok: false, reason: "recompute_failed", message: `Feature node ${id} could not be recomputed: ${detail}` };
556
+ }
557
+ continue;
558
+ }
559
+ const children = node.dependencies.map((dependency) => rebuilt.get(dependency) ?? nodes.get(dependency).shape);
560
+ try {
561
+ if (shape.cadBrep && children.some((child) => child.hole)) {
562
+ const result = await buildGroupFromSelection(children);
563
+ if ("error" in result || result.cutRemovedNothing) {
564
+ const detail = "error" in result ? result.error : "the cut removed no material";
565
+ return { ok: false, reason: "recompute_failed", message: `Dependent boolean node ${id} could not be recomputed: ${detail}` };
566
+ }
567
+ // The group builder returns a natural-frame result. Restore the retained
568
+ // group's resize, mirror, rotation and placement around that result.
569
+ const frame = groupChildFrame(shape);
570
+ const width = shapeWidth(result.group) * frame.scale.x;
571
+ const depth = shapeDepth(result.group) * frame.scale.z;
572
+ const height = result.group.height * frame.scale.y;
573
+ const center = frame.toParent(result.group.x, (result.group.elevation ?? 0) + result.group.height / 2, result.group.z);
574
+ rebuilt.set(id, {
575
+ ...result.group,
576
+ id: shape.id,
577
+ name: shape.name,
578
+ color: shape.color,
579
+ locked: shape.locked,
580
+ x: center.x,
581
+ z: center.z,
582
+ elevation: center.y - height / 2,
583
+ width,
584
+ depth,
585
+ height,
586
+ size: resizedShapeSize(width, depth),
587
+ rotation: shape.rotation,
588
+ rotationX: shape.rotationX,
589
+ rotationZ: shape.rotationZ,
590
+ mirrorX: shape.mirrorX,
591
+ mirrorY: shape.mirrorY,
592
+ mirrorZ: shape.mirrorZ,
593
+ groupedShapes: result.group.groupedShapes?.map((child, index) => {
594
+ const source = children[index];
595
+ return {
596
+ ...child,
597
+ ...(source ? {
598
+ faceDraft: source.faceDraft,
599
+ faceDraftSourceFaceIds: source.faceDraftSourceFaceIds,
600
+ faceDraftSourceSegmentId: source.faceDraftSourceSegmentId,
601
+ faceDraftSourceFrame: source.faceDraftSourceFrame,
602
+ faceDraftSourceScale: source.faceDraftSourceScale,
603
+ } : {}),
604
+ id: source?.id ?? child.id,
605
+ };
606
+ }),
607
+ });
608
+ }
609
+ else {
610
+ rebuilt.set(id, { ...shape, ...(children.length ? { groupedShapes: children } : {}) });
611
+ }
612
+ }
613
+ catch (error) {
614
+ const detail = error instanceof Error ? error.message : "an unexpected recompute error occurred";
615
+ return { ok: false, reason: "recompute_failed", message: `Dependent boolean node ${id} could not be recomputed: ${detail}` };
616
+ }
617
+ }
618
+ const shapes = project.shapes.map((shape) => rebuilt.get(shape.id) ?? shape);
619
+ const updated = rebuilt.get(changedNodeIds[0]);
620
+ return { ok: true, shapes, updated, matchCount: changedNodeIds.length };
296
621
  }
297
622
  export function findSketchOutput(roots, sourceId) {
298
623
  const matches = [];