dsh-cad-studio 0.22.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 +1 -0
  2. package/client.js +40 -6
  3. package/index.js +124 -2
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -18,6 +18,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
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
20
  | 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
21
+ | 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
21
22
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
22
23
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
23
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
@@ -616,6 +616,42 @@ function assembleScene(record) {
616
616
  }
617
617
  }
618
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
+
619
655
  class FreeCadBridge {
620
656
  constructor(getConfig, log) {
621
657
  this.getConfig = getConfig
@@ -641,6 +677,10 @@ class FreeCadBridge {
641
677
  this.modelsDir = ''
642
678
  /** Every models dir a tool has used (panel posts carry no session). */
643
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 = {}
644
684
  }
645
685
 
646
686
  /** Remember a models dir: newest first, deduped, bounded. */
@@ -696,9 +736,11 @@ class FreeCadBridge {
696
736
  await mkdir(join(dir, 'scenes'), { recursive: true })
697
737
  // Whatever an earlier process registered stays registered.
698
738
  let prevAssemblies = []
739
+ let prevAppearances = {}
699
740
  try {
700
741
  const prev = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
701
742
  prevAssemblies = Array.isArray(prev.assemblies) ? prev.assemblies : []
743
+ if (prev.appearances && typeof prev.appearances === 'object') prevAppearances = prev.appearances
702
744
  } catch {}
703
745
  // Keep new ids clear of the ones already in use.
704
746
  for (const rec of this.assembleRecords(prevAssemblies).values()) {
@@ -731,6 +773,9 @@ class FreeCadBridge {
731
773
  // Base placements ride along so a restarted process can still drive them
732
774
  // (the meshes stay in the scene file; only placements are small).
733
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 },
734
779
  modelsDirs: this.modelsSeen.slice(0, 12),
735
780
  // Which session last published: the panel only places its tab in the
736
781
  // sidebar for that session (or one that owns older scenes), so unrelated
@@ -767,6 +812,9 @@ class FreeCadBridge {
767
812
  if (!this.modelsDir && typeof pointer.modelsDir === 'string') this.modelsDir = pointer.modelsDir
768
813
  if (Array.isArray(pointer.modelsDirs)) this.modelsSeen = [...new Set([...this.modelsSeen, ...pointer.modelsDirs.filter((d) => typeof d === 'string' && d)])].slice(0, 12)
769
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
+ }
770
818
  const disk = Array.isArray(pointer.history) ? pointer.history : []
771
819
  const asmTitles = new Map()
772
820
  for (const a of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
@@ -820,6 +868,10 @@ class FreeCadBridge {
820
868
  if (!id && typeof opts.id === 'string' && /^scene-\d+$/.test(opts.id)) id = opts.id
821
869
  if (!id) id = `scene-${++this.seq}`
822
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
+ }
823
875
  this.scenes.set(id, scene)
824
876
  // Count what the viewport shows: per-instance totals and only the parts an
825
877
  // instance actually references (a scene may carry unreferenced parts).
@@ -928,6 +980,30 @@ class FreeCadBridge {
928
980
  return { ok: true, id: key, title: name }
929
981
  }
930
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
+
931
1007
  /** Reserve the id before publishing, so the scene can carry `asm:<id>`. */
932
1008
  reserveAssemblyId() {
933
1009
  return `asm-${++this.assemblySeq}`
@@ -959,6 +1035,29 @@ class FreeCadBridge {
959
1035
  return record
960
1036
  }
961
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
+
962
1061
  setJoint(record, spec) {
963
1062
  const value = normalizeJoint(record, spec)
964
1063
  const existing = record.joints.find((j) => j.id === spec.id)
@@ -3289,13 +3388,24 @@ if _TARGET:
3289
3388
  `
3290
3389
  // Allocate the assembly id before publishing: the scene carries `asm:<id>`
3291
3390
  // so later joint moves rewrite this same entry instead of adding one.
3292
- 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()
3293
3401
  const out = await bridge.run(py, { title: title ?? 'assembly', docKey: `asm:${asmId}` })
3294
3402
  if (!out.ok || !out.sceneId) return out
3295
3403
  // Keep the base placements: without them a joint has nothing to move.
3296
3404
  const scene = bridge.scenes.get(out.sceneId)
3297
3405
  if (!scene) return out
3298
- 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: [] })
3299
3409
  for (const spec of joints ?? []) {
3300
3410
  try {
3301
3411
  bridge.setJoint(record, spec)
@@ -4622,6 +4732,18 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4622
4732
  try { return JSON.parse(raw) } catch { return null }
4623
4733
  }
4624
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
+ }
4625
4747
  if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
4626
4748
  bridge.refresh()
4627
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.22.0",
3
+ "version": "0.23.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {