dsh-cad-studio 0.21.0 → 0.23.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 (4) hide show
  1. package/README.md +2 -0
  2. package/client.js +40 -6
  3. package/index.js +309 -5
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -17,6 +17,8 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
17
17
  | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
+ | 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
21
+ | 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
20
22
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
21
23
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
22
24
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
package/client.js CHANGED
@@ -1309,12 +1309,22 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1309
1309
  pendingCameraRef.current = saved.camera || null
1310
1310
  return
1311
1311
  }
1312
- const nextVisibility = {}
1313
- for (const inst of scene.instances || []) nextVisibility[inst.name] = true
1314
- setVisibility(nextVisibility)
1315
- setOverrides({ inst: {}, part: {} })
1316
- setOpacities({})
1317
- setWireframes({})
1312
+ // No local memory for this tab: start from whatever the model itself
1313
+ // remembers. Colours and hidden parts are the model's, not the tab's.
1314
+ const savedLook = scene.appearance
1315
+ if (savedLook) {
1316
+ setVisibility(savedLook.visibility || {})
1317
+ setOverrides(savedLook.overrides || { inst: {}, part: {} })
1318
+ setOpacities(savedLook.opacities || {})
1319
+ setWireframes(savedLook.wireframes || {})
1320
+ } else {
1321
+ const nextVisibility = {}
1322
+ for (const inst of scene.instances || []) nextVisibility[inst.name] = true
1323
+ setVisibility(nextVisibility)
1324
+ setOverrides({ inst: {}, part: {} })
1325
+ setOpacities({})
1326
+ setWireframes({})
1327
+ }
1318
1328
  pendingCameraRef.current = null
1319
1329
  }
1320
1330
 
@@ -1640,6 +1650,30 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1640
1650
  setHistTick((t) => t + 1)
1641
1651
  }, [lookSnap, sceneKey])
1642
1652
 
1653
+ // ---- 外观落盘:颜色 / 显隐 / 透明度 / 线框存回模型 --------------------
1654
+ // The look belongs to the model, not to this tab or this browser session:
1655
+ // a reload, a restart, or another tab on the same model all show the same
1656
+ // colours. Debounced because dragging an opacity slider fires per pixel.
1657
+ const lookSaveTimer = useRef(null)
1658
+ const lookSaveRef = useRef('')
1659
+ useEffect(() => {
1660
+ const key = (payload && (payload.docKey || (payload.assembly && payload.assembly.id ? `asm:${payload.assembly.id}` : ''))) || ''
1661
+ if (!key) return
1662
+ const snap = lookSnap
1663
+ if (snap === lookSaveRef.current) return
1664
+ if (lookSaveTimer.current) clearTimeout(lookSaveTimer.current)
1665
+ lookSaveTimer.current = setTimeout(() => {
1666
+ lookSaveRef.current = snap
1667
+ try {
1668
+ fetch('/cad-studio/appearance', {
1669
+ method: 'POST',
1670
+ headers: { 'content-type': 'application/json' },
1671
+ body: JSON.stringify({ docKey: key, look: JSON.parse(snap) }),
1672
+ }).catch(() => {})
1673
+ } catch (err) { /* a failed save must not break the panel */ }
1674
+ }, 700)
1675
+ }, [lookSnap, payload])
1676
+
1643
1677
  useEffect(() => {
1644
1678
  const onKey = (event) => {
1645
1679
  const key = String(event.key || '').toLowerCase()
package/index.js CHANGED
@@ -353,6 +353,21 @@ function instanceCenter(parts, inst) {
353
353
  return scaleVec(addVec(mn, mx), 0.5)
354
354
  }
355
355
 
356
+ /** World AABB of one placement ({rot, translate}) of an instance. */
357
+ function worldBox(parts, placement) {
358
+ if (!placement) return null
359
+ const bx = partLocalBox(parts, placement.part)
360
+ if (!bx) return null
361
+ const mn = [Infinity, Infinity, Infinity]
362
+ const mx = [-Infinity, -Infinity, -Infinity]
363
+ for (let i = 0; i < 8; i += 1) {
364
+ const p = [i & 1 ? bx.mx[0] : bx.mn[0], i & 2 ? bx.mx[1] : bx.mn[1], i & 4 ? bx.mx[2] : bx.mn[2]]
365
+ const w = addVec(mulVec(placement.rot, p), placement.translate)
366
+ for (let k = 0; k < 3; k += 1) { if (w[k] < mn[k]) mn[k] = w[k]; if (w[k] > mx[k]) mx[k] = w[k] }
367
+ }
368
+ return { mn, mx }
369
+ }
370
+
356
371
  function bboxCenterOfInstances(parts, instances) {
357
372
  const centers = instances.map((inst) => instanceCenter(parts, inst))
358
373
  if (!centers.length) return [0, 0, 0]
@@ -361,6 +376,33 @@ function bboxCenterOfInstances(parts, instances) {
361
376
  }
362
377
 
363
378
  /** Normalise one joint spec against the assembly it belongs to. */
379
+ /**
380
+ * One mate, normalised. A mate PLACES the moving instance against a fixed one
381
+ * and then stops being dynamic — it is solved once per republish, not stepped
382
+ * like a joint. Three kinds cover the assembly idioms we can verify:
383
+ * concentric two axes become collinear, axial distance = offset
384
+ * flush two faces touch, gap = 0 (offset must be 0)
385
+ * distance two faces stay `offset` apart along the axis
386
+ */
387
+ function normalizeMate(record, spec) {
388
+ const names = new Set(record.base.map((b) => b.name))
389
+ const a = String(spec.a ?? '')
390
+ const b = String(spec.b ?? '')
391
+ if (!names.has(a)) throw new Error(`装配里没有这个实例(移动件 a):${a}`)
392
+ if (!names.has(b)) throw new Error(`装配里没有这个实例(固定件 b):${b}`)
393
+ if (a === b) throw new Error('a 与 b 不能是同一个实例')
394
+ const TYPES = ['concentric', 'flush', 'distance']
395
+ const type = TYPES.includes(spec.type) ? spec.type : 'concentric'
396
+ const axis = normVec(Array.isArray(spec.axis) && spec.axis.length === 3 ? spec.axis.map(Number) : [0, 0, 1])
397
+ const offset = Number.isFinite(Number(spec.offset)) ? Number(spec.offset) : 0
398
+ if (type === 'flush' && Math.abs(offset) > 1e-9) {
399
+ throw new Error('flush 是「贴住」,offset 必须为 0(要留缝用 distance)')
400
+ }
401
+ const side = Number(spec.side) === -1 ? -1 : 1
402
+ const id = typeof spec.id === 'string' && spec.id.trim() ? spec.id.trim() : `mate-${(record.mates?.length ?? 0) + 1}`
403
+ return { id, type, a, b, axis, offset, side }
404
+ }
405
+
364
406
  function normalizeJoint(record, spec) {
365
407
  const inst = record.base.find((b) => b.name === spec.instance)
366
408
  if (!inst) throw new Error(`装配里没有这个实例:${spec.instance}`)
@@ -488,12 +530,59 @@ function resolveParams(value, vars, where) {
488
530
  return value
489
531
  }
490
532
 
533
+ /** Projection range of an AABB along a unit axis (handles negative components). */
534
+ function projRange(box, axis) {
535
+ let lo = 0
536
+ let hi = 0
537
+ for (let k = 0; k < 3; k += 1) {
538
+ const a = axis[k]
539
+ lo += a > 0 ? box.mn[k] * a : box.mx[k] * a
540
+ hi += a > 0 ? box.mx[k] * a : box.mn[k] * a
541
+ }
542
+ return [lo, hi]
543
+ }
544
+
545
+ /** Per-instance placements after the mates, before joints and explode. */
546
+ function solveMates(record) {
547
+ const out = new Map()
548
+ for (const base of record.base) out.set(base.name, { name: base.name, part: base.part, rot: base.rot.slice(), translate: base.translate.slice() })
549
+ for (const mate of record.mates ?? []) {
550
+ const moving = out.get(mate.a)
551
+ const fixed = out.get(mate.b)
552
+ if (!moving || !fixed) continue
553
+ const axis = normVec(mate.axis ?? [0, 0, 1])
554
+ const offset = Number.isFinite(Number(mate.offset)) ? Number(mate.offset) : 0
555
+ const boxB = worldBox(record.parts, out.get(mate.b))
556
+ const boxA = worldBox(record.parts, moving)
557
+ if (!boxA || !boxB) continue
558
+ if (mate.type === 'concentric') {
559
+ // Perpendicular drift to zero, axial distance to `offset`: the two axes
560
+ // end up collinear. Keep the moving part's own orientation — a mate moves
561
+ // it, it does not re-aim it.
562
+ const ca = scaleVec(addVec(boxA.mn, boxA.mx), 0.5)
563
+ const cb = scaleVec(addVec(boxB.mn, boxB.mx), 0.5)
564
+ const want = addVec(cb, scaleVec(axis, offset))
565
+ moving.translate = addVec(moving.translate, subVec(want, ca))
566
+ } else {
567
+ // flush / distance: face-to-face gap along the axis equals `offset`.
568
+ const ra = projRange(boxA, axis)
569
+ const rb = projRange(boxB, axis)
570
+ const side = mate.side === -1 ? -1 : 1
571
+ const shift = side > 0 ? (rb[1] + offset) - ra[0] : (rb[0] - offset) - ra[1]
572
+ moving.translate = addVec(moving.translate, scaleVec(axis, shift))
573
+ }
574
+ }
575
+ return out
576
+ }
577
+
491
578
  /** Base placements + joints + explode → a scene payload ready to publish. */
492
579
  function assembleScene(record) {
493
580
  const explode = record.explode ?? 0
581
+ const placed = solveMates(record)
494
582
  const instances = record.base.map((base) => {
495
- let rot = base.rot.slice()
496
- let translate = base.translate.slice()
583
+ const start = placed.get(base.name) ?? base
584
+ let rot = start.rot.slice()
585
+ let translate = start.translate.slice()
497
586
  for (const joint of record.joints) {
498
587
  if (joint.instance !== base.name) continue
499
588
  const axis = normVec(joint.axis)
@@ -527,6 +616,42 @@ function assembleScene(record) {
527
616
  }
528
617
  }
529
618
 
619
+ /**
620
+ * The saved look of one model: which instances are hidden, their hand-picked
621
+ * colours, per-instance opacity and wireframe. Validated here because the panel
622
+ * posts it straight from the browser — anything malformed is dropped, never
623
+ * stored, so a bad value cannot poison every later load.
624
+ */
625
+ const LOOK_HEX = /^#[0-9a-f]{6}$/i
626
+ function normalizeLook(raw) {
627
+ const src = raw && typeof raw === 'object' ? raw : {}
628
+ const pick = (obj, test, fix) => {
629
+ const out = {}
630
+ let n = 0
631
+ for (const [k, v] of Object.entries(obj && typeof obj === 'object' ? obj : {})) {
632
+ if (n >= 400) break
633
+ const key = String(k).slice(0, 120)
634
+ if (!key || !test(v)) continue
635
+ out[key] = fix(v)
636
+ n += 1
637
+ }
638
+ return out
639
+ }
640
+ const isBool = (v) => typeof v === 'boolean'
641
+ const isHex = (v) => typeof v === 'string' && LOOK_HEX.test(v)
642
+ const isNum = (v) => Number.isFinite(Number(v))
643
+ const ov = src.overrides && typeof src.overrides === 'object' ? src.overrides : {}
644
+ return {
645
+ visibility: pick(src.visibility, isBool, (v) => v),
646
+ overrides: {
647
+ inst: pick(ov.inst, isHex, (v) => v.toLowerCase()),
648
+ part: pick(ov.part, isHex, (v) => v.toLowerCase()),
649
+ },
650
+ opacities: pick(src.opacities, isNum, (v) => Math.min(1, Math.max(0, Number(v)))),
651
+ wireframes: pick(src.wireframes, isBool, (v) => v),
652
+ }
653
+ }
654
+
530
655
  class FreeCadBridge {
531
656
  constructor(getConfig, log) {
532
657
  this.getConfig = getConfig
@@ -552,6 +677,10 @@ class FreeCadBridge {
552
677
  this.modelsDir = ''
553
678
  /** Every models dir a tool has used (panel posts carry no session). */
554
679
  this.modelsSeen = []
680
+ /** Saved look per model key (`asm:asm-3`, `model:名字`): colours,
681
+ * visibility, opacity, wireframe. Keyed by the model, not the scene id,
682
+ * because every republish makes a fresh scene. */
683
+ this.appearances = {}
555
684
  }
556
685
 
557
686
  /** Remember a models dir: newest first, deduped, bounded. */
@@ -607,9 +736,11 @@ class FreeCadBridge {
607
736
  await mkdir(join(dir, 'scenes'), { recursive: true })
608
737
  // Whatever an earlier process registered stays registered.
609
738
  let prevAssemblies = []
739
+ let prevAppearances = {}
610
740
  try {
611
741
  const prev = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
612
742
  prevAssemblies = Array.isArray(prev.assemblies) ? prev.assemblies : []
743
+ if (prev.appearances && typeof prev.appearances === 'object') prevAppearances = prev.appearances
613
744
  } catch {}
614
745
  // Keep new ids clear of the ones already in use.
615
746
  for (const rec of this.assembleRecords(prevAssemblies).values()) {
@@ -642,6 +773,9 @@ class FreeCadBridge {
642
773
  // Base placements ride along so a restarted process can still drive them
643
774
  // (the meshes stay in the scene file; only placements are small).
644
775
  modelsDir: this.modelsDir ?? '',
776
+ // The saved look outlives the process: merged, so a fresh process that
777
+ // only knows about the models it touched does not wipe the others.
778
+ appearances: { ...prevAppearances, ...this.appearances },
645
779
  modelsDirs: this.modelsSeen.slice(0, 12),
646
780
  // Which session last published: the panel only places its tab in the
647
781
  // sidebar for that session (or one that owns older scenes), so unrelated
@@ -657,6 +791,7 @@ class FreeCadBridge {
657
791
  base: a.base,
658
792
  center: a.center,
659
793
  joints: a.joints.map((j) => ({ id: j.id, instance: j.instance, type: j.type, value: j.value, min: j.min, max: j.max, axis: j.axis, origin: j.origin })),
794
+ mates: a.mates ?? [],
660
795
  explode: a.explode,
661
796
  })),
662
797
  }
@@ -677,6 +812,9 @@ class FreeCadBridge {
677
812
  if (!this.modelsDir && typeof pointer.modelsDir === 'string') this.modelsDir = pointer.modelsDir
678
813
  if (Array.isArray(pointer.modelsDirs)) this.modelsSeen = [...new Set([...this.modelsSeen, ...pointer.modelsDirs.filter((d) => typeof d === 'string' && d)])].slice(0, 12)
679
814
  if (!this.lastSession && typeof pointer.lastSession === 'string') this.lastSession = pointer.lastSession
815
+ if (pointer.appearances && typeof pointer.appearances === 'object') {
816
+ this.appearances = { ...pointer.appearances, ...this.appearances }
817
+ }
680
818
  const disk = Array.isArray(pointer.history) ? pointer.history : []
681
819
  const asmTitles = new Map()
682
820
  for (const a of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
@@ -730,6 +868,10 @@ class FreeCadBridge {
730
868
  if (!id && typeof opts.id === 'string' && /^scene-\d+$/.test(opts.id)) id = opts.id
731
869
  if (!id) id = `scene-${++this.seq}`
732
870
  else this.seq = Math.max(this.seq, Number(id.slice('scene-'.length)))
871
+ if (docKey) {
872
+ scene.docKey = docKey
873
+ scene.appearance = this.appearances[docKey] ?? null
874
+ }
733
875
  this.scenes.set(id, scene)
734
876
  // Count what the viewport shows: per-instance totals and only the parts an
735
877
  // instance actually references (a scene may carry unreferenced parts).
@@ -838,6 +980,30 @@ class FreeCadBridge {
838
980
  return { ok: true, id: key, title: name }
839
981
  }
840
982
 
983
+ /** Save the look of one model and mirror it into that model's scene file. */
984
+ async setAppearance(docKey, look) {
985
+ const key = String(docKey ?? '').trim()
986
+ if (!key) throw new Error('docKey 必填')
987
+ const clean = normalizeLook(look)
988
+ this.appearances[key] = clean
989
+ const dir = FreeCadBridge.dataDir
990
+ await mkdir(join(dir, 'scenes'), { recursive: true })
991
+ for (const row of this.history) {
992
+ if (row.docKey !== key) continue
993
+ const file = join(dir, 'scenes', `${row.id}.json`)
994
+ let scene = this.scenes.get(row.id)
995
+ if (!scene) {
996
+ try { scene = JSON.parse(await readFile(file, 'utf8')) } catch { continue }
997
+ this.scenes.set(row.id, scene)
998
+ }
999
+ scene.docKey = key
1000
+ scene.appearance = clean
1001
+ try { await writeFile(file, JSON.stringify(scene), 'utf8') } catch {}
1002
+ }
1003
+ await this.persist()
1004
+ return clean
1005
+ }
1006
+
841
1007
  /** Reserve the id before publishing, so the scene can carry `asm:<id>`. */
842
1008
  reserveAssemblyId() {
843
1009
  return `asm-${++this.assemblySeq}`
@@ -862,12 +1028,36 @@ class FreeCadBridge {
862
1028
  })),
863
1029
  center: bboxCenterOfInstances(scene.parts, scene.instances),
864
1030
  joints: joints ?? [],
1031
+ mates: [],
865
1032
  explode: 0,
866
1033
  }
867
1034
  this.assemblies.set(id, record)
868
1035
  return record
869
1036
  }
870
1037
 
1038
+ /** Replace the parts/placements of an existing assembly, keeping its joints,
1039
+ * mates and saved look. Re-running `cad_studio_assembly` with `assembly` uses
1040
+ * this: the model keeps its identity while its geometry changes. */
1041
+ rebaseAssembly(record, { title, sceneId, scene }) {
1042
+ record.title = title ?? record.title
1043
+ record.sceneId = sceneId
1044
+ record.parts = scene.parts
1045
+ record.base = scene.instances.map((inst) => ({
1046
+ name: inst.name,
1047
+ part: inst.part,
1048
+ rot: inst.rot.slice(),
1049
+ translate: inst.translate.slice(),
1050
+ center: instanceCenter(scene.parts, inst),
1051
+ }))
1052
+ record.center = bboxCenterOfInstances(scene.parts, scene.instances)
1053
+ // A mate or joint naming an instance that no longer exists would silently
1054
+ // do nothing, so drop those rather than keep dead rows in the panel.
1055
+ const names = new Set(record.base.map((b) => b.name))
1056
+ record.joints = (record.joints ?? []).filter((j) => names.has(j.instance))
1057
+ record.mates = (record.mates ?? []).filter((m) => names.has(m.a) && names.has(m.b))
1058
+ return record
1059
+ }
1060
+
871
1061
  setJoint(record, spec) {
872
1062
  const value = normalizeJoint(record, spec)
873
1063
  const existing = record.joints.find((j) => j.id === spec.id)
@@ -876,6 +1066,24 @@ class FreeCadBridge {
876
1066
  return value
877
1067
  }
878
1068
 
1069
+ /** Add or replace one mate; returns the stored spec. */
1070
+ setMate(record, spec) {
1071
+ const value = normalizeMate(record, spec)
1072
+ record.mates = Array.isArray(record.mates) ? record.mates : []
1073
+ const existing = record.mates.find((m) => m.id === value.id)
1074
+ if (existing) Object.assign(existing, value)
1075
+ else record.mates.push(value)
1076
+ return value
1077
+ }
1078
+
1079
+ removeMate(record, id) {
1080
+ const list = record.mates ?? []
1081
+ const at = list.findIndex((m) => m.id === id)
1082
+ if (at < 0) return null
1083
+ const [gone] = list.splice(at, 1)
1084
+ return gone
1085
+ }
1086
+
879
1087
  driveJoint(record, jointId, rawValue) {
880
1088
  const joint = record.joints.find((j) => j.id === jointId)
881
1089
  if (!joint) return null
@@ -895,7 +1103,12 @@ class FreeCadBridge {
895
1103
 
896
1104
  // ---- 装配层撤销:关节值 / 关节增删 / 爆炸系数 ----
897
1105
  snapshotAssembly(record) {
898
- return { id: record.id, joints: JSON.parse(JSON.stringify(record.joints ?? [])), explode: record.explode ?? 0 }
1106
+ return {
1107
+ id: record.id,
1108
+ joints: JSON.parse(JSON.stringify(record.joints ?? [])),
1109
+ mates: JSON.parse(JSON.stringify(record.mates ?? [])),
1110
+ explode: record.explode ?? 0,
1111
+ }
899
1112
  }
900
1113
 
901
1114
  beginAssemblyEdit(record, label) {
@@ -3175,13 +3388,24 @@ if _TARGET:
3175
3388
  `
3176
3389
  // Allocate the assembly id before publishing: the scene carries `asm:<id>`
3177
3390
  // so later joint moves rewrite this same entry instead of adding one.
3178
- const asmId = bridge.reserveAssemblyId()
3391
+ // Re-running with `assembly` rebuilds THAT assembly in place: same id, so
3392
+ // its joints, mates and saved look survive a change to the parts.
3393
+ // `assembly` is an id when it looks like one (`asm-3`) and a display name
3394
+ // otherwise — older callers passed a title here.
3395
+ let reuse = null
3396
+ if (assembly && /^asm-\d+$/.test(String(assembly))) {
3397
+ try { reuse = await bridge.loadAssembly(String(assembly)) } catch {}
3398
+ if (!reuse) return { ok: false, error: `没有这个装配:${assembly}` }
3399
+ }
3400
+ const asmId = reuse ? reuse.id : bridge.reserveAssemblyId()
3179
3401
  const out = await bridge.run(py, { title: title ?? 'assembly', docKey: `asm:${asmId}` })
3180
3402
  if (!out.ok || !out.sceneId) return out
3181
3403
  // Keep the base placements: without them a joint has nothing to move.
3182
3404
  const scene = bridge.scenes.get(out.sceneId)
3183
3405
  if (!scene) return out
3184
- const record = bridge.registerAssembly({ id: asmId, title: assembly || title || 'assembly', sceneId: out.sceneId, scene, joints: [] })
3406
+ const record = reuse
3407
+ ? bridge.rebaseAssembly(reuse, { title: title || reuse.title, sceneId: out.sceneId, scene })
3408
+ : bridge.registerAssembly({ id: asmId, title: assembly || title || 'assembly', sceneId: out.sceneId, scene, joints: [] })
3185
3409
  for (const spec of joints ?? []) {
3186
3410
  try {
3187
3411
  bridge.setJoint(record, spec)
@@ -3335,6 +3559,74 @@ if _TARGET:
3335
3559
  },
3336
3560
  })
3337
3561
 
3562
+ tool({
3563
+ name: 'cad_studio_mate',
3564
+ description: 'Place an assembly instance against another with a mate: concentric (axes collinear, axial distance = offset), flush (faces touch), or distance (faces `offset` apart along the axis). A mate is solved once per republish and then holds — it is not a driven joint. Use cad_studio_drive for the moving degrees of freedom.',
3565
+ parameters: {
3566
+ type: 'object',
3567
+ properties: {
3568
+ assembly: { type: 'string' },
3569
+ action: { type: 'string', enum: ['set', 'list', 'remove'], description: 'Default: set.' },
3570
+ id: { type: 'string', description: 'Mate id (remove / replace). Default: mate-<n>.' },
3571
+ type: { type: 'string', enum: ['concentric', 'flush', 'distance'] },
3572
+ a: { type: 'string', description: 'Instance name that moves.' },
3573
+ b: { type: 'string', description: 'Instance name that stays put.' },
3574
+ axis: { type: 'array', items: { type: 'number' }, description: 'Mate axis. Default [0,0,1].' },
3575
+ offset: { type: 'number', description: 'mm: axial distance (concentric) or face gap (distance). flush requires 0.' },
3576
+ side: { type: 'number', description: '+1 puts `a` on the positive side of `b` (default), -1 the negative side.' },
3577
+ },
3578
+ additionalProperties: false,
3579
+ },
3580
+ output: {
3581
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' } } },
3582
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3583
+ },
3584
+ execute: async ({ assembly, action, id, type, a, b, axis, offset, side }) => {
3585
+ let record
3586
+ try {
3587
+ record = findAssembly(assembly)
3588
+ } catch (error) {
3589
+ return { ok: false, error: String(error?.message ?? error) }
3590
+ }
3591
+ const list = () => (record.mates ?? []).map((m) => ({ ...m, axis: m.axis.map(round6) }))
3592
+ const want = action ?? 'set'
3593
+ if (want === 'list') {
3594
+ return { ok: true, assembly: record.id, sceneId: record.sceneId, mates: list(), instances: record.base.map((x) => x.name) }
3595
+ }
3596
+ if (want === 'remove') {
3597
+ const target = String(id ?? '')
3598
+ const edit = bridge.beginAssemblyEdit(record, `mate remove ${target}`)
3599
+ const gone = bridge.removeMate(record, target)
3600
+ if (!gone) {
3601
+ const have = (record.mates ?? []).map((m) => m.id).join(', ') || '(没有)'
3602
+ return { ok: false, error: `没有这个约束:${target}(现有 ${have})` }
3603
+ }
3604
+ const published = await bridge.republishAssembly(record)
3605
+ bridge.endAssemblyEdit(edit, record)
3606
+ return { ok: true, assembly: record.id, sceneId: published.id, removed: gone.id, mates: list(), instances: published.stats.instances }
3607
+ }
3608
+ let value
3609
+ try {
3610
+ value = normalizeMate(record, { id, type, a, b, axis, offset, side })
3611
+ } catch (error) {
3612
+ return { ok: false, error: String(error?.message ?? error) }
3613
+ }
3614
+ const edit = bridge.beginAssemblyEdit(record, `mate ${value.type} ${value.a}→${value.b}`)
3615
+ bridge.setMate(record, value)
3616
+ const published = await bridge.republishAssembly(record)
3617
+ bridge.endAssemblyEdit(edit, record)
3618
+ return {
3619
+ ok: true,
3620
+ assembly: record.id,
3621
+ sceneId: published.id,
3622
+ mate: { ...value, axis: value.axis.map(round6) },
3623
+ mates: list(),
3624
+ instances: published.stats.instances,
3625
+ volume: round6(published.stats.volume),
3626
+ }
3627
+ },
3628
+ })
3629
+
3338
3630
  tool({
3339
3631
  name: 'cad_studio_explode',
3340
3632
  description: 'Exploded view: push every instance radially away from the assembly centre by `factor` (0 = assembled, 0.5 = half the distance outward). Republished scene only — geometry and exports are untouched.',
@@ -4440,6 +4732,18 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4440
4732
  try { return JSON.parse(raw) } catch { return null }
4441
4733
  }
4442
4734
 
4735
+ if (url.pathname === `${ROUTE_PREFIX}/appearance` && req.method === 'POST') {
4736
+ // Colours / visibility picked by hand in the panel: stored per model so
4737
+ // a reload or a restart shows the same look.
4738
+ const body = await bodyOf()
4739
+ if (!body || typeof body.docKey !== 'string' || !body.docKey) return send(400, JSON.stringify({ error: 'bad request' }))
4740
+ try {
4741
+ const saved = await bridge.setAppearance(body.docKey, body.look ?? body.appearance ?? {})
4742
+ return send(200, JSON.stringify({ ok: true, docKey: body.docKey, appearance: saved }))
4743
+ } catch (error) {
4744
+ return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
4745
+ }
4746
+ }
4443
4747
  if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
4444
4748
  bridge.refresh()
4445
4749
  return send(200, JSON.stringify(diagnose(bridge, resolved)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {