dsh-cad-studio 0.2.8 → 0.3.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.
- package/README.md +9 -0
- package/client.js +111 -31
- package/index.js +301 -12
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -18,6 +18,8 @@ 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(主/俯/左/等轴) |
|
|
20
20
|
| 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
|
|
21
|
+
| 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
|
|
22
|
+
| 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
|
|
21
23
|
| 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
|
|
22
24
|
| 面板 | 多页签(上限 5,各自记住相机与配色)、点选联动、色块换色、显隐、透明度、线框、隔离、标准视图、网格/轮廓/光影开关 |
|
|
23
25
|
|
|
@@ -53,6 +55,13 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
|
|
|
53
55
|
|
|
54
56
|
`autoOpen: 'session'` 的判据是宿主侧的两个信号:这个会话最近一次发布过场景(`lastSession`),或它拥有更早发布过的场景。也就是说——只有真正在这里建过模的对话,右栏才会自动让出位置;别的对话不受打扰。
|
|
55
57
|
|
|
58
|
+
## 两个容易踩的接口约定
|
|
59
|
+
|
|
60
|
+
- **导出只走 `cad_studio_export`**。在 `cad_studio_run` 里直接 `Part.export([compound], path)` 会写出一个 1.6 KB 的 STEP 壳子,读回来是空形状,而脚本本身不报错。要么用 `cad_studio_export`,要么给 `cad_studio_run` 传 `check: ["/path/out.step"]`——它会在跑完后把这个文件读回来,回报 `{bytes, solids, volume, valid}`,壳子会显示 `valid:false`。
|
|
61
|
+
- **探查脚本别发布场景**。`cad_studio_run` 默认会把绑定的 `scene` 发布成面板里的一行;只是量体积/查干涉的脚本传 `publish: false`,否则模型列表会被探针卡片塞满(实测一次会话攒到 28 行)。已经混进去的用 `cad_studio_scene {action:"delete", id:"scene-12"}` 清。
|
|
62
|
+
- `cad_studio_export` 的返回里 `volume` / `solids` 是**真正写出去的那一套**,`sourceVolume` / `sourceSolids` 是输入侧的;`minVolume` 会按实体体积过滤(滤掉圆丝、灰尘),`alsoStl` 顺手写一份 STL。
|
|
63
|
+
- `cad_studio_assembly` 传 `measure: true` 会回每实例的 bbox/体积/实体数与总体积,`interference: true` 会回真正重叠的实例对(先用包围盒筛,再做布尔交)。
|
|
64
|
+
|
|
56
65
|
## 场景 JSON 协议
|
|
57
66
|
|
|
58
67
|
```jsonc
|
package/client.js
CHANGED
|
@@ -366,56 +366,74 @@ window.__ModuleLoader__.load({
|
|
|
366
366
|
}
|
|
367
367
|
|
|
368
368
|
/** Rail glyphs — 15px so the 28px rail stays a strip, not a column. */
|
|
369
|
+
// Icons are inline SVG on a 20x20 grid rendered at exactly 20 CSS px, so the
|
|
370
|
+
// scale is 1:1 and the strokes land on whole pixels (a 16-unit viewBox
|
|
371
|
+
// stretched to 17 px is what made the previous set look soft).
|
|
369
372
|
function RailIcon({ name }) {
|
|
370
|
-
const common = {
|
|
373
|
+
const common = {
|
|
374
|
+
width: 20,
|
|
375
|
+
height: 20,
|
|
376
|
+
viewBox: '0 0 20 20',
|
|
377
|
+
fill: 'none',
|
|
378
|
+
stroke: 'currentColor',
|
|
379
|
+
strokeWidth: 1.75,
|
|
380
|
+
strokeLinecap: 'round',
|
|
381
|
+
strokeLinejoin: 'round',
|
|
382
|
+
'aria-hidden': 'true',
|
|
383
|
+
focusable: 'false',
|
|
384
|
+
}
|
|
371
385
|
if (name === 'parts') {
|
|
386
|
+
// A solid body: the isometric cube every CAD app uses for "part".
|
|
372
387
|
return h('svg', common, [
|
|
373
|
-
h('path', { key: 'a', d: '
|
|
374
|
-
h('path', { key: 'b', d: '
|
|
388
|
+
h('path', { key: 'a', d: 'M10 2.5 17 6.4v7.2L10 17.5 3 13.6V6.4L10 2.5Z' }),
|
|
389
|
+
h('path', { key: 'b', d: 'M3 6.4 10 10.3l7-3.9M10 10.3v7.2' }),
|
|
375
390
|
])
|
|
376
391
|
}
|
|
377
|
-
if (name === '
|
|
378
|
-
// A
|
|
392
|
+
if (name === 'features') {
|
|
393
|
+
// A ziggurat: the part as a stack of machining steps.
|
|
379
394
|
return h('svg', common, [
|
|
380
|
-
h('path', { key: '
|
|
381
|
-
h('path', { key: '
|
|
382
|
-
h('
|
|
395
|
+
h('path', { key: 'a', d: 'M3 13.2h14v4H3z' }),
|
|
396
|
+
h('path', { key: 'b', d: 'M5.2 8.4h9.6v4.8H5.2z' }),
|
|
397
|
+
h('path', { key: 'c', d: 'M7.6 3.4h4.8v5H7.6z' }),
|
|
383
398
|
])
|
|
384
399
|
}
|
|
385
|
-
if (name === '
|
|
386
|
-
//
|
|
400
|
+
if (name === 'props') {
|
|
401
|
+
// Sliders: the panel is literally sliders and switches.
|
|
387
402
|
return h('svg', common, [
|
|
388
|
-
h('path', { key: '
|
|
389
|
-
h('
|
|
390
|
-
h('
|
|
403
|
+
h('path', { key: 'a', d: 'M2.8 5.6h14.4M2.8 10h14.4M2.8 14.4h14.4' }),
|
|
404
|
+
h('circle', { key: 'b', cx: 7, cy: 5.6, r: 1.9, fill: 'currentColor', stroke: 'none' }),
|
|
405
|
+
h('circle', { key: 'c', cx: 13, cy: 10, r: 1.9, fill: 'currentColor', stroke: 'none' }),
|
|
406
|
+
h('circle', { key: 'd', cx: 8.4, cy: 14.4, r: 1.9, fill: 'currentColor', stroke: 'none' }),
|
|
391
407
|
])
|
|
392
408
|
}
|
|
393
|
-
if (name === '
|
|
409
|
+
if (name === 'motion') {
|
|
410
|
+
// Articulation: a circular arrow around the pivot. (An axis plus a half
|
|
411
|
+
// arc read as a “D” at this size.)
|
|
394
412
|
return h('svg', common, [
|
|
395
|
-
h('path', { key: '
|
|
396
|
-
h('path', { key: '
|
|
413
|
+
h('path', { key: 'ring', d: 'M10 3.4a6.6 6.6 0 1 1-6.3 8.5' }),
|
|
414
|
+
h('path', { key: 'head', d: 'M3.2 12.4 3 8.9l3.3 1.3' }),
|
|
415
|
+
h('circle', { key: 'pin', cx: 10, cy: 10, r: 1.5, fill: 'currentColor', stroke: 'none' }),
|
|
397
416
|
])
|
|
398
417
|
}
|
|
399
|
-
if (name === '
|
|
418
|
+
if (name === 'view') {
|
|
419
|
+
// A camera: which angle am I looking from, and what gets drawn.
|
|
400
420
|
return h('svg', common, [
|
|
401
|
-
h('path', { key: '
|
|
402
|
-
h('
|
|
403
|
-
h('circle', { key: '
|
|
404
|
-
h('circle', { key: 'd', cx: 6.9, cy: 11.8, r: 1.45, fill: 'currentColor', stroke: 'none' }),
|
|
421
|
+
h('path', { key: 'body', d: 'M3.4 6.8h13.2a1.4 1.4 0 0 1 1.4 1.4v6.4a1.4 1.4 0 0 1-1.4 1.4H3.4A1.4 1.4 0 0 1 2 14.6V8.2a1.4 1.4 0 0 1 1.4-1.4Z' }),
|
|
422
|
+
h('path', { key: 'bump', d: 'M7.4 6.8 8.6 4.4h2.8l1.2 2.4' }),
|
|
423
|
+
h('circle', { key: 'lens', cx: 10, cy: 11.4, r: 2.7 }),
|
|
405
424
|
])
|
|
406
425
|
}
|
|
407
|
-
if (name === '
|
|
408
|
-
// A
|
|
426
|
+
if (name === 'models') {
|
|
427
|
+
// A folder: the model library.
|
|
409
428
|
return h('svg', common, [
|
|
410
|
-
h('path', { key: 'a', d: '
|
|
411
|
-
h('path', { key: 'b', d: '
|
|
412
|
-
h('path', { key: 'c', d: 'M5.3 8.6 4.2 8l-.2 1.5' }),
|
|
429
|
+
h('path', { key: 'a', d: 'M2.6 6.4c0-.9.5-1.4 1.4-1.4h3.4l1.6 1.8h7.4c.9 0 1.4.5 1.4 1.4v6.4c0 .9-.5 1.4-1.4 1.4H4c-.9 0-1.4-.5-1.4-1.4V6.4Z' }),
|
|
430
|
+
h('path', { key: 'b', d: 'M2.6 9.4h14.8' }),
|
|
413
431
|
])
|
|
414
432
|
}
|
|
415
433
|
return h('svg', common, [
|
|
416
|
-
h('circle', { key: 'c', cx:
|
|
417
|
-
h('path', { key: 'd', d: '
|
|
418
|
-
h('circle', { key: 'e', cx:
|
|
434
|
+
h('circle', { key: 'c', cx: 10, cy: 10, r: 7.4 }),
|
|
435
|
+
h('path', { key: 'd', d: 'M10 9.2v5' }),
|
|
436
|
+
h('circle', { key: 'e', cx: 10, cy: 6.4, r: 0.95, fill: 'currentColor', stroke: 'none' }),
|
|
419
437
|
])
|
|
420
438
|
}
|
|
421
439
|
|
|
@@ -1722,6 +1740,12 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1722
1740
|
// the new scene replaces the old one in the tab being looked at.
|
|
1723
1741
|
const featureList = payload && Array.isArray(payload.features) ? payload.features : []
|
|
1724
1742
|
const featureModel = (payload && payload.model) || ''
|
|
1743
|
+
// A script model publishes its params (no feature list); they are editable
|
|
1744
|
+
// the same way — one number, one rebuild of the same document.
|
|
1745
|
+
const modelParams = payload && payload.params && typeof payload.params === 'object' ? payload.params : {}
|
|
1746
|
+
const paramKeys = Object.keys(modelParams)
|
|
1747
|
+
const [paramDraft, setParamDraft] = useState({})
|
|
1748
|
+
const paramTimer = useRef(null)
|
|
1725
1749
|
const featureDefaults = {
|
|
1726
1750
|
box: { size: [40, 30, 10] },
|
|
1727
1751
|
cylinder: { r: 6, h: 20 },
|
|
@@ -1754,13 +1778,38 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1754
1778
|
return null
|
|
1755
1779
|
}
|
|
1756
1780
|
}
|
|
1781
|
+
const postParams = async (params) => {
|
|
1782
|
+
try {
|
|
1783
|
+
const res = await fetch(`${ROUTE}/params`, {
|
|
1784
|
+
method: 'POST',
|
|
1785
|
+
headers: { 'content-type': 'application/json' },
|
|
1786
|
+
body: JSON.stringify({ model: featureModel, params }),
|
|
1787
|
+
})
|
|
1788
|
+
const out = await res.json()
|
|
1789
|
+
if (!res.ok || !out || out.ok === false) {
|
|
1790
|
+
setFeatError(String((out && out.error) || `HTTP ${res.status}`))
|
|
1791
|
+
return null
|
|
1792
|
+
}
|
|
1793
|
+
setFeatError('')
|
|
1794
|
+
setParamDraft({})
|
|
1795
|
+
if (out.sceneId) await applyScene(out.sceneId, out.at)
|
|
1796
|
+
return out
|
|
1797
|
+
} catch (error) {
|
|
1798
|
+
setFeatError(String((error && error.message) || error))
|
|
1799
|
+
return null
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
const queueParams = (merged) => {
|
|
1803
|
+
if (paramTimer.current) clearTimeout(paramTimer.current)
|
|
1804
|
+
paramTimer.current = setTimeout(() => { paramTimer.current = null; postParams(merged) }, 300)
|
|
1805
|
+
}
|
|
1757
1806
|
// Number edits come from a text input: coalesce a burst of keystrokes into
|
|
1758
1807
|
// one rebuild (each rebuild is a full FreeCAD run).
|
|
1759
1808
|
const queueFeature = (body) => {
|
|
1760
1809
|
if (featTimer.current) clearTimeout(featTimer.current)
|
|
1761
1810
|
featTimer.current = setTimeout(() => { featTimer.current = null; postFeature(body) }, 260)
|
|
1762
1811
|
}
|
|
1763
|
-
useEffect(() => () => { if (featTimer.current) clearTimeout(featTimer.current) }, [])
|
|
1812
|
+
useEffect(() => () => { if (featTimer.current) clearTimeout(featTimer.current); if (paramTimer.current) clearTimeout(paramTimer.current) }, [])
|
|
1764
1813
|
const parseParam = (raw) => {
|
|
1765
1814
|
const text = String(raw).trim()
|
|
1766
1815
|
if (!text) return null
|
|
@@ -1805,7 +1854,38 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1805
1854
|
}
|
|
1806
1855
|
queueFeature({ action: 'update', feature: { id: feature.id, params } })
|
|
1807
1856
|
}
|
|
1808
|
-
const
|
|
1857
|
+
const paramsBody = paramKeys.map((key) => {
|
|
1858
|
+
const base = modelParams[key]
|
|
1859
|
+
const draft = paramDraft[key]
|
|
1860
|
+
const value = draft === undefined ? base : draft
|
|
1861
|
+
const numeric = typeof base === 'number'
|
|
1862
|
+
return h('label', { key: `p-${key}`, style: styles.propRow }, [
|
|
1863
|
+
h('span', { key: 'l', style: { ...styles.propLabel, flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } }, key),
|
|
1864
|
+
h('input', {
|
|
1865
|
+
key: 'i',
|
|
1866
|
+
type: numeric ? 'number' : 'text',
|
|
1867
|
+
style: styles.jointNum,
|
|
1868
|
+
'data-cad-param': key,
|
|
1869
|
+
value: String(value),
|
|
1870
|
+
onChange: (event) => {
|
|
1871
|
+
const raw = event.currentTarget.value
|
|
1872
|
+
if (raw === '') return
|
|
1873
|
+
const next = numeric ? Number(raw) : raw
|
|
1874
|
+
if (numeric && !Number.isFinite(next)) return
|
|
1875
|
+
setParamDraft((prev) => ({ ...prev, [key]: next }))
|
|
1876
|
+
queueParams({ ...modelParams, ...paramDraft, [key]: next })
|
|
1877
|
+
},
|
|
1878
|
+
}),
|
|
1879
|
+
])
|
|
1880
|
+
})
|
|
1881
|
+
const paramsSection = paramKeys.length
|
|
1882
|
+
? [h('div', { key: 'params-h', style: styles.treeHint }, `${featureModel} · 参数(改完即重建)`), ...paramsBody]
|
|
1883
|
+
: []
|
|
1884
|
+
const featureBody = paramsSection.length
|
|
1885
|
+
? [...paramsSection, ...(!featureList.length
|
|
1886
|
+
? [h('div', { key: 'script-hint', style: { ...styles.treeHint, whiteSpace: 'nowrap' }, title: '脚本模型:改参数会重跑脚本;逐条特征只适用于声明式模型' }, '脚本模型 · 改参数即重跑脚本')]
|
|
1887
|
+
: [h('div', { key: 'feat-h', style: { ...styles.treeHint, marginTop: 2 } }, `${featureList.length} 特征`)])]
|
|
1888
|
+
: !featureModel || !featureList.length
|
|
1809
1889
|
? [h('div', { key: 'none', style: styles.propEmpty },
|
|
1810
1890
|
featureModel
|
|
1811
1891
|
? `${featureModel} 的特征列表是空的。`
|
package/index.js
CHANGED
|
@@ -353,7 +353,9 @@ class FreeCadBridge {
|
|
|
353
353
|
|
|
354
354
|
/** Candidate models dirs, most recently used first (falls back to config). */
|
|
355
355
|
modelsCandidates() {
|
|
356
|
-
|
|
356
|
+
// A class method cannot see apply()'s `modelsDirFor`; the global dir is the
|
|
357
|
+
// right tail here because panel routes always carry a real dir first.
|
|
358
|
+
const out = [this.modelsDir, ...this.modelsSeen, this.getConfig().modelsDir, GLOBAL_MODELS_DIR]
|
|
357
359
|
return [...new Set(out.filter((d) => typeof d === 'string' && d))]
|
|
358
360
|
}
|
|
359
361
|
|
|
@@ -529,6 +531,54 @@ class FreeCadBridge {
|
|
|
529
531
|
return { id, stats }
|
|
530
532
|
}
|
|
531
533
|
|
|
534
|
+
/** The model list, as the panel sees it (newest first). */
|
|
535
|
+
listSceneRows() {
|
|
536
|
+
return this.history.map((h) => ({
|
|
537
|
+
id: h.id,
|
|
538
|
+
title: h.title,
|
|
539
|
+
at: h.at,
|
|
540
|
+
session: h.session ?? '',
|
|
541
|
+
instances: h.instances ?? 0,
|
|
542
|
+
parts: h.parts ?? 0,
|
|
543
|
+
triangles: h.triangles ?? 0,
|
|
544
|
+
volume: h.volume ?? null,
|
|
545
|
+
docKey: h.docKey ?? '',
|
|
546
|
+
}))
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Drop one row from the model list. A probe that was published by mistake is
|
|
551
|
+
* otherwise only removable by editing state.json by hand — which is exactly
|
|
552
|
+
* how a 28-row list happened in the first place.
|
|
553
|
+
*/
|
|
554
|
+
async removeScene(id) {
|
|
555
|
+
const key = String(id ?? '')
|
|
556
|
+
const row = this.history.find((h) => h.id === key)
|
|
557
|
+
if (!row) throw new Error(`没有这个场景:${key}(可用 ${this.history.map((h) => h.id).join(', ') || '(无)'})`)
|
|
558
|
+
this.history = this.history.filter((h) => h.id !== key)
|
|
559
|
+
this.scenes.delete(key)
|
|
560
|
+
for (const [asmId, rec] of [...this.assemblies]) if (rec.sceneId === key) this.assemblies.delete(asmId)
|
|
561
|
+
try { await rm(join(FreeCadBridge.dataDir, 'scenes', `${key}.json`), { force: true }) } catch {}
|
|
562
|
+
if (this.latest && this.latest.id === key) {
|
|
563
|
+
const next = this.history[0]
|
|
564
|
+
this.latest = next ? { id: next.id, title: next.title, at: next.at, scene: this.scenes.get(next.id) ?? null } : null
|
|
565
|
+
}
|
|
566
|
+
await this.persist()
|
|
567
|
+
return { ok: true, removed: key, scenes: this.history.length, latest: this.latest ? this.latest.id : '' }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async renameScene(id, title) {
|
|
571
|
+
const key = String(id ?? '')
|
|
572
|
+
const row = this.history.find((h) => h.id === key)
|
|
573
|
+
if (!row) throw new Error(`没有这个场景:${key}`)
|
|
574
|
+
const name = String(title ?? '').trim()
|
|
575
|
+
if (!name) throw new Error('新名字不能为空')
|
|
576
|
+
row.title = name
|
|
577
|
+
if (this.latest && this.latest.id === key) this.latest = { ...this.latest, title: name }
|
|
578
|
+
await this.persist()
|
|
579
|
+
return { ok: true, id: key, title: name }
|
|
580
|
+
}
|
|
581
|
+
|
|
532
582
|
/** Reserve the id before publishing, so the scene can carry `asm:<id>`. */
|
|
533
583
|
reserveAssemblyId() {
|
|
534
584
|
return `asm-${++this.assemblySeq}`
|
|
@@ -631,7 +681,7 @@ class FreeCadBridge {
|
|
|
631
681
|
return null
|
|
632
682
|
}
|
|
633
683
|
|
|
634
|
-
async run(code, { title, publishHint = true, meta = null, docKey = '', sceneId = '' } = {}) {
|
|
684
|
+
async run(code, { title, publishHint = true, publish = true, meta = null, docKey = '', sceneId = '' } = {}) {
|
|
635
685
|
const bin = this.refresh()
|
|
636
686
|
if (!bin) {
|
|
637
687
|
return { ok: false, error: 'freecadcmd not found; set freecadPath in the plugin config' }
|
|
@@ -695,7 +745,7 @@ print("${BEGIN}" + __json.dumps(_safe(_payload)) + "${END}", flush=True)\n`
|
|
|
695
745
|
} catch (error) {
|
|
696
746
|
return { ok: false, error: `helper returned non-JSON: ${String(error?.message ?? error)}`, raw: payload.slice(0, 500) }
|
|
697
747
|
}
|
|
698
|
-
if (value?.scene) {
|
|
748
|
+
if (value?.scene && publish !== false) {
|
|
699
749
|
// A shape bound to `scene = box` arrives with the variable name as the
|
|
700
750
|
// instance label; the caller's title is what a human expects in the tree.
|
|
701
751
|
const first = value.scene.instances?.[0]
|
|
@@ -707,6 +757,7 @@ print("${BEGIN}" + __json.dumps(_safe(_payload)) + "${END}", flush=True)\n`
|
|
|
707
757
|
value.sceneId = published.id
|
|
708
758
|
delete value.scene
|
|
709
759
|
}
|
|
760
|
+
if (publish === false) delete value.scene
|
|
710
761
|
const clean = { ok: true, ...value }
|
|
711
762
|
clean.published = Boolean(clean.sceneId)
|
|
712
763
|
if (!clean.published && publishHint) {
|
|
@@ -1052,6 +1103,94 @@ __out = {
|
|
|
1052
1103
|
execute: async () => bridge.status(),
|
|
1053
1104
|
})
|
|
1054
1105
|
|
|
1106
|
+
tool({
|
|
1107
|
+
name: 'cad_studio_legacy',
|
|
1108
|
+
description: 'Read the old dsh-cad document store (/app/.dsh-cad, op logs) that cad_studio_doc cannot see: action=list reports every document with its op mix and body count, action=show prints one document\'s op summary and body names. This is read-only; to bring an old model into CAD Studio, export it to STEP once (exports/ already holds the migrated ones) and assemble from the file.',
|
|
1109
|
+
parameters: {
|
|
1110
|
+
type: 'object',
|
|
1111
|
+
properties: {
|
|
1112
|
+
action: { type: 'string', enum: ['list', 'show'], description: 'list (default) or show.' },
|
|
1113
|
+
doc: { type: 'string', description: 'Document id or title (show only).' },
|
|
1114
|
+
dir: { type: 'string', description: 'Store directory (default /app/.dsh-cad).' },
|
|
1115
|
+
},
|
|
1116
|
+
additionalProperties: false,
|
|
1117
|
+
},
|
|
1118
|
+
output: {
|
|
1119
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, documents: { type: 'number' } } },
|
|
1120
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1121
|
+
},
|
|
1122
|
+
execute: async ({ action, doc, dir: storeDir }) => {
|
|
1123
|
+
const root = typeof storeDir === 'string' && storeDir ? storeDir : '/app/.dsh-cad'
|
|
1124
|
+
const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'))
|
|
1125
|
+
const summarise = (entry) => {
|
|
1126
|
+
const ops = Array.isArray(entry.ops) ? entry.ops : []
|
|
1127
|
+
const kinds = {}
|
|
1128
|
+
for (const op of ops) kinds[op.kind] = (kinds[op.kind] || 0) + 1
|
|
1129
|
+
return { ops: ops.length, kinds, bodies: Array.isArray(entry.bodyNames) ? entry.bodyNames.length : 0 }
|
|
1130
|
+
}
|
|
1131
|
+
let index = { docs: [] }
|
|
1132
|
+
try { index = await readJson(join(root, 'index.json')) } catch {}
|
|
1133
|
+
const docs = Array.isArray(index.docs) ? index.docs : []
|
|
1134
|
+
const loaded = []
|
|
1135
|
+
for (const meta of docs) {
|
|
1136
|
+
try {
|
|
1137
|
+
const entry = await readJson(join(root, 'docs', `${meta.id}.json`))
|
|
1138
|
+
loaded.push({ id: meta.id, title: meta.title ?? '', updatedAt: meta.updatedAt ?? '', ...summarise(entry), entry })
|
|
1139
|
+
} catch {
|
|
1140
|
+
loaded.push({ id: meta.id, title: meta.title ?? '', updatedAt: meta.updatedAt ?? '', ops: 0, kinds: {}, bodies: 0, missing: true })
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
const kind = String(action ?? 'list')
|
|
1144
|
+
if (kind === 'list') {
|
|
1145
|
+
return {
|
|
1146
|
+
ok: true,
|
|
1147
|
+
dir: root,
|
|
1148
|
+
documents: loaded.length,
|
|
1149
|
+
items: loaded.map((d) => ({ id: d.id, title: d.title, updatedAt: d.updatedAt, ops: d.ops, bodies: d.bodies, kinds: d.kinds, ...(d.missing ? { missing: true } : {}) })),
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
if (kind === 'show') {
|
|
1153
|
+
const key = String(doc ?? '').trim()
|
|
1154
|
+
const hit = loaded.find((d) => d.id === key || d.title === key)
|
|
1155
|
+
if (!hit) return { ok: false, error: `没有这个文档:${key}(可用 ${loaded.map((d) => d.title || d.id).join(', ') || '(无)'})` }
|
|
1156
|
+
const ops = Array.isArray(hit.entry?.ops) ? hit.entry.ops : []
|
|
1157
|
+
// Newest bodies first: booleans target them by id, so this is the order
|
|
1158
|
+
// in which a replayer would resolve them.
|
|
1159
|
+
const tail = ops.slice(-12).map((op) => ({ kind: op.kind, bodyId: op.bodyId ?? op.target ?? '', name: op.name ?? '', prim: op.prim ?? '' }))
|
|
1160
|
+
return { ok: true, id: hit.id, title: hit.title, version: hit.entry?.version ?? null, ops: ops.length, kinds: hit.kinds, bodies: hit.entry?.bodyNames ?? [], tail }
|
|
1161
|
+
}
|
|
1162
|
+
return { ok: false, error: `不支持的 action:${kind}(list / show)` }
|
|
1163
|
+
},
|
|
1164
|
+
})
|
|
1165
|
+
|
|
1166
|
+
tool({
|
|
1167
|
+
name: 'cad_studio_scene',
|
|
1168
|
+
description: 'Maintain the model list the panel shows (the persisted scene history): action=list / delete / rename. Use delete to clear probe scenes that a measurement run left behind, and rename when a scene title is a file path or a part id.',
|
|
1169
|
+
parameters: {
|
|
1170
|
+
type: 'object',
|
|
1171
|
+
properties: {
|
|
1172
|
+
action: { type: 'string', enum: ['list', 'delete', 'rename'], description: 'list (default) / delete / rename.' },
|
|
1173
|
+
id: { type: 'string', description: 'Scene id, e.g. scene-12. Required for delete and rename.' },
|
|
1174
|
+
title: { type: 'string', description: 'New title (rename only).' },
|
|
1175
|
+
},
|
|
1176
|
+
additionalProperties: false,
|
|
1177
|
+
},
|
|
1178
|
+
output: {
|
|
1179
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, scenes: { type: 'number' } } },
|
|
1180
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1181
|
+
},
|
|
1182
|
+
execute: async ({ action, id, title }) => {
|
|
1183
|
+
const kind = String(action ?? 'list')
|
|
1184
|
+
if (kind === 'list') {
|
|
1185
|
+
const rows = bridge.listSceneRows()
|
|
1186
|
+
return { ok: true, scenes: rows.length, latest: bridge.latest ? bridge.latest.id : '', items: rows }
|
|
1187
|
+
}
|
|
1188
|
+
if (kind === 'delete') return bridge.removeScene(id)
|
|
1189
|
+
if (kind === 'rename') return bridge.renameScene(id, title)
|
|
1190
|
+
return { ok: false, error: `不支持的 action:${kind}(list / delete / rename)` }
|
|
1191
|
+
},
|
|
1192
|
+
})
|
|
1193
|
+
|
|
1055
1194
|
tool({
|
|
1056
1195
|
name: 'cad_studio_setup',
|
|
1057
1196
|
description: 'Check whether freecadcmd is installed and, when it is missing, install FreeCAD through the system package manager (apt/dnf/pacman/brew). action=check reports binary, version, package manager and the exact command; action=install runs it (needs root on apt) and re-probes afterwards.',
|
|
@@ -1097,12 +1236,18 @@ __out = {
|
|
|
1097
1236
|
|
|
1098
1237
|
tool({
|
|
1099
1238
|
name: 'cad_studio_run',
|
|
1100
|
-
description: 'Run a FreeCAD Python script in freecadcmd headless. Bind the shape to show to a variable named `scene` (e.g. `scene = Part.makeBox(80,40,10)`) — it is tessellated and published to the CAD Studio panel; the result reports sceneId and published. Put extra data in the `__out` dict (or `__out["scene"]` for full control of parts/instances/colors).',
|
|
1239
|
+
description: 'Run a FreeCAD Python script in freecadcmd headless. Bind the shape to show to a variable named `scene` (e.g. `scene = Part.makeBox(80,40,10)`) — it is tessellated and published to the CAD Studio panel; the result reports sceneId and published. Put extra data in the `__out` dict (or `__out["scene"]` for full control of parts/instances/colors). Measurement/verification scripts should pass publish:false — otherwise every probe becomes a row in the model list.',
|
|
1101
1240
|
parameters: {
|
|
1102
1241
|
type: 'object',
|
|
1103
1242
|
properties: {
|
|
1104
1243
|
code: { type: 'string', description: 'FreeCAD Python source. Import Part/Import yourself; helpers describe(path)/_mesh(shape) are preloaded.' },
|
|
1105
1244
|
title: { type: 'string', description: 'Panel title for the published scene.' },
|
|
1245
|
+
publish: { type: 'boolean', description: 'Publish the bound shape as a panel scene (default true). Pass false for a probe that only measures.' },
|
|
1246
|
+
check: {
|
|
1247
|
+
type: 'array',
|
|
1248
|
+
items: { type: 'string' },
|
|
1249
|
+
description: 'Files the script wrote: each is re-read after the run and reported as {path, exists, bytes, solids, volume, valid}. A 1.6 KB STEP shell shows up here as valid:false instead of passing silently.',
|
|
1250
|
+
},
|
|
1106
1251
|
},
|
|
1107
1252
|
required: ['code'],
|
|
1108
1253
|
additionalProperties: false,
|
|
@@ -1111,7 +1256,47 @@ __out = {
|
|
|
1111
1256
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' }, stderr: { type: 'string' } } },
|
|
1112
1257
|
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1113
1258
|
},
|
|
1114
|
-
execute: async (args) =>
|
|
1259
|
+
execute: async (args) => {
|
|
1260
|
+
const files = Array.isArray(args.check) ? args.check.filter((x) => typeof x === 'string' && x) : []
|
|
1261
|
+
const guard = files.length
|
|
1262
|
+
? `
|
|
1263
|
+
# Re-read what the script wrote: FreeCAD's Part.export on a compound can emit a
|
|
1264
|
+
# 1.6 KB STEP that parses back as a null shape, and the call still returns ok.
|
|
1265
|
+
import os as _os
|
|
1266
|
+
_checks = []
|
|
1267
|
+
for _p in ${JSON.stringify(files)}:
|
|
1268
|
+
_e = {"path": _p, "exists": _os.path.isfile(_p)}
|
|
1269
|
+
if _e["exists"]:
|
|
1270
|
+
_e["bytes"] = _os.path.getsize(_p)
|
|
1271
|
+
try:
|
|
1272
|
+
if _p.lower().rsplit(".", 1)[-1] in ("step", "stp", "brep", "iges", "igs"):
|
|
1273
|
+
_s = Part.Shape()
|
|
1274
|
+
_s.read(_p)
|
|
1275
|
+
_e["solids"] = len(_s.Solids)
|
|
1276
|
+
_e["volume"] = round(float(_s.Volume), 3)
|
|
1277
|
+
_e["valid"] = bool(_s.Solids) and float(_s.Volume) > 0.0
|
|
1278
|
+
else:
|
|
1279
|
+
_e["valid"] = _e["bytes"] > 200
|
|
1280
|
+
except Exception as _err:
|
|
1281
|
+
_e["valid"] = False
|
|
1282
|
+
_e["error"] = str(_err)
|
|
1283
|
+
else:
|
|
1284
|
+
_e["valid"] = False
|
|
1285
|
+
_checks.append(_e)
|
|
1286
|
+
__out = dict(globals().get("__out") or {})
|
|
1287
|
+
__out["files"] = _checks
|
|
1288
|
+
`
|
|
1289
|
+
: ''
|
|
1290
|
+
const out = await bridge.run(`${PRELUDE}\n${args.code}\n${guard}`, {
|
|
1291
|
+
title: args.title,
|
|
1292
|
+
publish: args.publish !== false,
|
|
1293
|
+
})
|
|
1294
|
+
if (args.publish === false && out && typeof out === 'object') {
|
|
1295
|
+
// The script may still have bound `scene`; make the contract explicit.
|
|
1296
|
+
out.published = false
|
|
1297
|
+
}
|
|
1298
|
+
return out
|
|
1299
|
+
},
|
|
1115
1300
|
})
|
|
1116
1301
|
|
|
1117
1302
|
tool({
|
|
@@ -1164,7 +1349,9 @@ if not _shapes:
|
|
|
1164
1349
|
`
|
|
1165
1350
|
}
|
|
1166
1351
|
|
|
1167
|
-
const writeShapeFile = (target, src) => {
|
|
1352
|
+
const writeShapeFile = (target, src, opts = {}) => {
|
|
1353
|
+
const minVolume = Number.isFinite(opts.minVolume) && opts.minVolume > 0 ? Number(opts.minVolume) : 0
|
|
1354
|
+
const alsoStl = Boolean(opts.alsoStl)
|
|
1168
1355
|
const py = `${PRELUDE}
|
|
1169
1356
|
${src}
|
|
1170
1357
|
if not _shapes:
|
|
@@ -1174,6 +1361,16 @@ else:
|
|
|
1174
1361
|
_target = ${JSON.stringify(target)}
|
|
1175
1362
|
_fmt = _target.rsplit(".", 1)[-1].lower()
|
|
1176
1363
|
os.makedirs(os.path.dirname(_target) or ".", exist_ok=True)
|
|
1364
|
+
# Flatten to solids so a volume threshold can drop dust (round wires, tiny
|
|
1365
|
+
# fillets) that would otherwise dominate the file size.
|
|
1366
|
+
_solids = []
|
|
1367
|
+
for _s in _shapes:
|
|
1368
|
+
_solids.extend(list(_s.Solids) or [_s])
|
|
1369
|
+
_minv = ${minVolume}
|
|
1370
|
+
_kept = [x for x in _solids if x.Volume >= _minv] if _minv > 0 else _solids
|
|
1371
|
+
if not _kept:
|
|
1372
|
+
raise RuntimeError("no solids left after minVolume=%.3f (smallest %.3f)" % (_minv, min((x.Volume for x in _solids), default=0.0)))
|
|
1373
|
+
_shapes = _kept
|
|
1177
1374
|
if _fmt in ("step", "stp"):
|
|
1178
1375
|
# Part.export([shape]) writes a 1.6 KB STEP that reads back as a NULL shape;
|
|
1179
1376
|
# Shape.exportStep / compound exportStep is the API that produces a valid file.
|
|
@@ -1198,7 +1395,25 @@ else:
|
|
|
1198
1395
|
open(_target, "w").write("\\n".join(_lines) + "\\n")
|
|
1199
1396
|
else:
|
|
1200
1397
|
raise RuntimeError("unsupported export format: ." + _fmt + " (use .step/.stp/.brep/.iges/.igs/.stl)")
|
|
1201
|
-
|
|
1398
|
+
_stl = None
|
|
1399
|
+
if ${alsoStl ? 'True' : 'False'}:
|
|
1400
|
+
_stl = os.path.splitext(_target)[0] + ".stl"
|
|
1401
|
+
_lines = []
|
|
1402
|
+
for _s in _shapes:
|
|
1403
|
+
_verts, _facets = _s.tessellate(0.2)
|
|
1404
|
+
for _f in _facets:
|
|
1405
|
+
_a, _b, _c = (_verts[i] for i in _f)
|
|
1406
|
+
_lines.append("facet normal 0 0 0\\n outer loop")
|
|
1407
|
+
for _p in (_a, _b, _c):
|
|
1408
|
+
_lines.append(" vertex %r %r %r" % (_p.x, _p.y, _p.z))
|
|
1409
|
+
_lines.append(" endloop\\nendfacet")
|
|
1410
|
+
open(_stl, "w").write("solid cad_studio\\n" + "\\n".join(_lines) + "\\nendsolid cad_studio\\n")
|
|
1411
|
+
__out = {"ok": True, "path": _target, "format": _fmt, "bytes": os.path.getsize(_target),
|
|
1412
|
+
"solids": len(_shapes), "volume": round(sum(float(x.Volume) for x in _shapes), 3),
|
|
1413
|
+
"sourceSolids": len(_solids), "sourceVolume": round(sum(float(x.Volume) for x in _solids), 3),
|
|
1414
|
+
"filtered": len(_solids) - len(_shapes)}
|
|
1415
|
+
if _stl:
|
|
1416
|
+
__out["stl"] = {"path": _stl, "bytes": os.path.getsize(_stl)}
|
|
1202
1417
|
`
|
|
1203
1418
|
return bridge.run(py, { title: `export → ${target}`, publishHint: false })
|
|
1204
1419
|
}
|
|
@@ -1212,6 +1427,8 @@ else:
|
|
|
1212
1427
|
target: { type: 'string', description: 'Absolute output path; the extension picks the format (.step/.stp/.brep/.iges/.igs/.stl).' },
|
|
1213
1428
|
source: { type: 'string', description: 'Existing model file to export (STEP/IGES/BREP/STL).' },
|
|
1214
1429
|
code: { type: 'string', description: 'FreeCAD Python that produces the geometry; bind `scene` or `export_shapes`.' },
|
|
1430
|
+
minVolume: { type: 'number', description: 'Drop solids smaller than this (mm³). Use it to keep round wires and dust out of a print file; the return says how many were filtered.' },
|
|
1431
|
+
alsoStl: { type: 'boolean', description: 'Also write an STL next to the target (a light file for viewers that do not read STEP).' },
|
|
1215
1432
|
},
|
|
1216
1433
|
required: ['target'],
|
|
1217
1434
|
additionalProperties: false,
|
|
@@ -1220,11 +1437,15 @@ else:
|
|
|
1220
1437
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
|
|
1221
1438
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
1222
1439
|
},
|
|
1223
|
-
execute: async ({ target, source, code }) => {
|
|
1440
|
+
execute: async ({ target, source, code, minVolume, alsoStl }) => {
|
|
1224
1441
|
if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
|
|
1225
1442
|
const src = shapesFrom({ source, code })
|
|
1226
1443
|
if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
|
|
1227
|
-
|
|
1444
|
+
const out = await writeShapeFile(target, src, { minVolume, alsoStl })
|
|
1445
|
+
// Keep the two numbers apart on purpose: `volume` is what was written,
|
|
1446
|
+
// `sourceVolume` is what the input held. Mixing them is how a batch export
|
|
1447
|
+
// gets mistaken for the part it produced.
|
|
1448
|
+
return { ...out, source: typeof source === 'string' ? source : '' }
|
|
1228
1449
|
},
|
|
1229
1450
|
})
|
|
1230
1451
|
|
|
@@ -1389,6 +1610,8 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
1389
1610
|
},
|
|
1390
1611
|
target: { type: 'string', description: 'Optional .step/.stp output path for the whole assembly.' },
|
|
1391
1612
|
title: { type: 'string', description: 'Panel title.' },
|
|
1613
|
+
measure: { type: 'boolean', description: 'Return per-instance bbox / volume / solid count, and the total volume.' },
|
|
1614
|
+
interference: { type: 'boolean', description: 'Return the instance pairs that actually overlap (bbox prefilter, then a boolean common).' },
|
|
1392
1615
|
assembly: { type: 'string', description: 'Assembly label for cad_studio_joint / cad_studio_drive / cad_studio_explode (defaults to the title).' },
|
|
1393
1616
|
joints: {
|
|
1394
1617
|
type: 'array',
|
|
@@ -1416,7 +1639,7 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
1416
1639
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' }, instances: { type: 'number' }, assembly: { type: 'string' } } },
|
|
1417
1640
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
1418
1641
|
},
|
|
1419
|
-
execute: async ({ parts, instances, target, title, assembly, joints }) => {
|
|
1642
|
+
execute: async ({ parts, instances, target, title, assembly, joints, measure, interference }) => {
|
|
1420
1643
|
if (!Array.isArray(parts) || !parts.length) return { ok: false, error: 'parts must be a non-empty array' }
|
|
1421
1644
|
if (!Array.isArray(instances) || !instances.length) return { ok: false, error: 'instances must be a non-empty array' }
|
|
1422
1645
|
// Only referenced parts are read and tessellated: an export set often
|
|
@@ -1462,8 +1685,50 @@ for _i in _INSTS:
|
|
|
1462
1685
|
_copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
|
|
1463
1686
|
_placed.append(_copy)
|
|
1464
1687
|
|
|
1688
|
+
_MEASURE = ${measure ? 'True' : 'False'}
|
|
1689
|
+
_INTERF = ${interference ? 'True' : 'False'}
|
|
1690
|
+
|
|
1465
1691
|
__out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
|
|
1466
1692
|
"scene": {"parts": _parts, "instances": _instances}}
|
|
1693
|
+
|
|
1694
|
+
if _MEASURE:
|
|
1695
|
+
# Per-instance numbers, so "how big is this part, and does it fit" is one
|
|
1696
|
+
# call instead of an export plus a re-import.
|
|
1697
|
+
_rows = []
|
|
1698
|
+
for _k, _inst in enumerate(_INSTS):
|
|
1699
|
+
_s = _placed[_k]
|
|
1700
|
+
_bb = _s.BoundBox
|
|
1701
|
+
_rows.append({
|
|
1702
|
+
"name": _inst["name"], "part": _inst["part"],
|
|
1703
|
+
"volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
|
|
1704
|
+
"bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
|
|
1705
|
+
"max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
|
|
1706
|
+
})
|
|
1707
|
+
_box = Part.makeCompound(_placed).BoundBox
|
|
1708
|
+
__out["measure"] = {
|
|
1709
|
+
"instances": _rows,
|
|
1710
|
+
"totalVolume": round(sum(r["volume"] for r in _rows), 3),
|
|
1711
|
+
"bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
|
|
1712
|
+
"max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
if _INTERF:
|
|
1716
|
+
# Bounding boxes first: a boolean common on every pair of a 30-solid
|
|
1717
|
+
# assembly is minutes of work for answers that are mostly zero.
|
|
1718
|
+
_pairs = []
|
|
1719
|
+
for _i in range(len(_placed)):
|
|
1720
|
+
for _j in range(_i + 1, len(_placed)):
|
|
1721
|
+
_a, _b = _placed[_i], _placed[_j]
|
|
1722
|
+
if not _a.BoundBox.intersect(_b.BoundBox):
|
|
1723
|
+
continue
|
|
1724
|
+
try:
|
|
1725
|
+
_c = _a.common(_b)
|
|
1726
|
+
_v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
|
|
1727
|
+
except Exception:
|
|
1728
|
+
_v = 0.0
|
|
1729
|
+
if _v > 1e-3:
|
|
1730
|
+
_pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
|
|
1731
|
+
__out["interference"] = _pairs
|
|
1467
1732
|
if _TARGET:
|
|
1468
1733
|
os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
|
|
1469
1734
|
Part.makeCompound(_placed).exportStep(_TARGET)
|
|
@@ -1750,7 +2015,7 @@ if _TARGET:
|
|
|
1750
2015
|
const code = isFeatures
|
|
1751
2016
|
? featuresScript(featureOps(doc))
|
|
1752
2017
|
: `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
|
|
1753
|
-
const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc) } :
|
|
2018
|
+
const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc) } : { model: doc.name, params: doc.params ?? {} }
|
|
1754
2019
|
doc.run = (doc.run ?? 0) + 1
|
|
1755
2020
|
doc.updatedAt = new Date().toISOString()
|
|
1756
2021
|
// One row per model: a rebuild rewrites the model's existing scene.
|
|
@@ -2104,7 +2369,9 @@ if _TARGET:
|
|
|
2104
2369
|
// route closure left by a hot reload still lists what is on disk.
|
|
2105
2370
|
try {
|
|
2106
2371
|
const parsed = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
|
|
2107
|
-
|
|
2372
|
+
// `scenes` is the model list (kept for older panels); `history` is the
|
|
2373
|
+
// same array under the name the file uses. Counts live in `runtime`.
|
|
2374
|
+
return send(200, JSON.stringify({ latest: parsed.latest ?? null, scenes: parsed.history ?? [], history: parsed.history ?? [] }))
|
|
2108
2375
|
} catch {
|
|
2109
2376
|
return send(200, JSON.stringify({ latest: null, scenes: [] }))
|
|
2110
2377
|
}
|
|
@@ -2128,6 +2395,28 @@ if _TARGET:
|
|
|
2128
2395
|
return send(200, JSON.stringify(out))
|
|
2129
2396
|
}
|
|
2130
2397
|
|
|
2398
|
+
if (url.pathname === `${ROUTE_PREFIX}/params` && req.method === 'POST') {
|
|
2399
|
+
// Same path as cad_studio_doc update: the panel edits a number, the doc
|
|
2400
|
+
// is rewritten and rebuilt, and a failed rebuild rolls the params back.
|
|
2401
|
+
const body = await bodyOf()
|
|
2402
|
+
if (!body || typeof body.model !== 'string' || !body.model) return send(400, JSON.stringify({ error: 'bad request' }))
|
|
2403
|
+
try {
|
|
2404
|
+
if (!bridge.modelsSeen.length) {
|
|
2405
|
+
try {
|
|
2406
|
+
const pointer = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
|
|
2407
|
+
if (typeof pointer.modelsDir === 'string' && pointer.modelsDir) bridge.noteModelsDir(pointer.modelsDir)
|
|
2408
|
+
if (Array.isArray(pointer.modelsDirs)) pointer.modelsDirs.forEach((d) => bridge.noteModelsDir(d))
|
|
2409
|
+
} catch {}
|
|
2410
|
+
}
|
|
2411
|
+
const candidates = resolved.modelsDir ? [resolved.modelsDir, ...bridge.modelsCandidates()] : bridge.modelsCandidates()
|
|
2412
|
+
const modelsDir = candidates.find((d) => existsSync(join(d, `${body.model}.json`))) || candidates[0] || modelsDirFor(undefined)
|
|
2413
|
+
const out = await runDocAction({ action: 'update', name: body.model, params: body.params ?? {} }, modelsDir)
|
|
2414
|
+
const entry = out && out.sceneId ? bridge.history.find((h) => h.id === out.sceneId) : null
|
|
2415
|
+
return send(200, JSON.stringify(entry ? { ...out, at: entry.at } : out))
|
|
2416
|
+
} catch (error) {
|
|
2417
|
+
return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2131
2420
|
if (url.pathname === `${ROUTE_PREFIX}/feature` && req.method === 'POST') {
|
|
2132
2421
|
// The panel edits features directly; the same code path as the tool, so
|
|
2133
2422
|
// a slider/number edit and an agent edit produce identical documents.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cad-studio",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
|
|
6
6
|
"exports": {
|
|
@@ -47,4 +47,4 @@
|
|
|
47
47
|
"name": "stofone"
|
|
48
48
|
},
|
|
49
49
|
"license": "MIT"
|
|
50
|
-
}
|
|
50
|
+
}
|