dsh-cad-studio 0.3.1 → 0.4.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 +5 -0
- package/index.js +135 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
|
|
|
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
21
|
| 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
|
|
22
|
+
| 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
|
|
22
23
|
| 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
|
|
23
24
|
| 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
|
|
24
25
|
| 面板 | 多页签(上限 5,各自记住相机与配色)、点选联动、色块换色、显隐、透明度、线框、隔离、标准视图、网格/轮廓/光影开关 |
|
|
@@ -61,6 +62,10 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
|
|
|
61
62
|
- **探查脚本别发布场景**。`cad_studio_run` 默认会把绑定的 `scene` 发布成面板里的一行;只是量体积/查干涉的脚本传 `publish: false`,否则模型列表会被探针卡片塞满(实测一次会话攒到 28 行)。已经混进去的用 `cad_studio_scene {action:"delete", id:"scene-12"}` 清。
|
|
62
63
|
- `cad_studio_export` 的返回里 `volume` / `solids` 是**真正写出去的那一套**,`sourceVolume` / `sourceSolids` 是输入侧的;`minVolume` 会按实体体积过滤(滤掉圆丝、灰尘),`alsoStl` 顺手写一份 STL。
|
|
63
64
|
- `cad_studio_assembly` 传 `measure: true` 会回每实例的 bbox/体积/实体数与总体积,`interference: true` 会回真正重叠的实例对(先用包围盒筛,再做布尔交)。
|
|
65
|
+
- **`fuse` / `cut` / `common` 的 `with` 可以是数组**:U 形围壁写成「一条 `fuse` 外块 + 一条 `cut` 带两个内腔」即可,不必拆成中间状态(中间状态是实心块,顺序错了会削到别处)。
|
|
66
|
+
- **`extrude` 支持 3D 剖面点与 `dir`**:三角棱柱写 `{kind:"extrude", points:[[0,0,0],[40,0,0],[0,30,0]], dir:[0,0,20]}`,不用再拿 `base`/`h` 手算覆盖范围。
|
|
67
|
+
- 特征参数在 `normalizeFeature` 阶段就校验,报错带行号与名字:`特征 f10(倒角_左后) cut:需要 with 子图元(…)`——不会再从 FreeCAD 里冒出一句 `第 10 步(cut)失败:'with'`。
|
|
68
|
+
- 删掉的面板行不会被下一次发布「复活」:`persist()` 会跟磁盘对账,只保留磁盘上还有的、或本进程发布过的行。
|
|
64
69
|
|
|
65
70
|
## 场景 JSON 协议
|
|
66
71
|
|
package/index.js
CHANGED
|
@@ -18,7 +18,7 @@ import { existsSync } from 'node:fs'
|
|
|
18
18
|
import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
|
19
19
|
import { tmpdir } from 'node:os'
|
|
20
20
|
import { fileURLToPath } from 'node:url'
|
|
21
|
-
import { join } from 'node:path'
|
|
21
|
+
import { dirname, join } from 'node:path'
|
|
22
22
|
|
|
23
23
|
export const name = 'dsh-cad-studio'
|
|
24
24
|
|
|
@@ -331,6 +331,9 @@ class FreeCadBridge {
|
|
|
331
331
|
this.latest = undefined
|
|
332
332
|
this.seq = 0
|
|
333
333
|
this.history = []
|
|
334
|
+
// Ids this process published since boot: a row that is neither here nor on
|
|
335
|
+
// disk was deleted on purpose and must not be resurrected by the next write.
|
|
336
|
+
this.touched = new Set()
|
|
334
337
|
/** Assemblies keep their base placements so joints can re-place instances. */
|
|
335
338
|
this.assemblies = new Map()
|
|
336
339
|
this.assemblySeq = 0
|
|
@@ -399,6 +402,21 @@ class FreeCadBridge {
|
|
|
399
402
|
const n = Number(String(rec.id).replace(/\D+/g, ''))
|
|
400
403
|
if (Number.isFinite(n)) this.assemblySeq = Math.max(this.assemblySeq, n)
|
|
401
404
|
}
|
|
405
|
+
// A row deleted from state.json (by hand or by another process) must stay
|
|
406
|
+
// deleted: without this, the next publish wrote the whole in-memory history
|
|
407
|
+
// back and undid the prune — which is exactly what the reviewer hit twice.
|
|
408
|
+
let diskIds = null
|
|
409
|
+
try {
|
|
410
|
+
const prev = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
|
|
411
|
+
diskIds = new Set((Array.isArray(prev.history) ? prev.history : []).map((h) => h.id))
|
|
412
|
+
} catch {}
|
|
413
|
+
if (diskIds) {
|
|
414
|
+
this.history = this.history.filter((h) => diskIds.has(h.id) || this.touched.has(h.id))
|
|
415
|
+
if (this.latest && !this.history.some((h) => h.id === this.latest.id)) {
|
|
416
|
+
const next = this.history[0]
|
|
417
|
+
this.latest = next ? { id: next.id, title: next.title, at: next.at, scene: this.scenes.get(next.id) ?? null } : null
|
|
418
|
+
}
|
|
419
|
+
}
|
|
402
420
|
const latest = this.latest
|
|
403
421
|
if (latest) await writeFile(join(dir, 'scenes', `${latest.id}.json`), JSON.stringify(latest.scene), 'utf8')
|
|
404
422
|
const pointer = {
|
|
@@ -523,6 +541,7 @@ class FreeCadBridge {
|
|
|
523
541
|
volume,
|
|
524
542
|
...(docKey ? { docKey } : {}),
|
|
525
543
|
}
|
|
544
|
+
this.touched.add(id)
|
|
526
545
|
this.history = [stats, ...this.history.filter((h) => h.id !== id)].slice(0, 30)
|
|
527
546
|
this.latest = { id, title, at: stats.at, scene }
|
|
528
547
|
// Persist so a restarted process (and any stale route closure left by a
|
|
@@ -866,9 +885,15 @@ def _prim(op):
|
|
|
866
885
|
return Part.makeTorus(float(op["r1"]), float(op["r2"]), at, _dir(op.get("axis")))
|
|
867
886
|
if k == "extrude":
|
|
868
887
|
base = float(op.get("base", 0.0))
|
|
869
|
-
h = float(op
|
|
870
|
-
|
|
871
|
-
|
|
888
|
+
h = float(op.get("h", 0.0))
|
|
889
|
+
# Points may be 2D (z = base) or 3D; dir replaces the +Z extrusion,
|
|
890
|
+
# which is what a chamfer prism or a slanted rib actually needs.
|
|
891
|
+
pts = [tuple(p) for p in op["points"]]
|
|
892
|
+
ps = [Vector(float(q[0]), float(q[1]), float(q[2]) if len(q) > 2 else base) for q in pts]
|
|
893
|
+
vec = _v3(op.get("dir"), (0.0, 0.0, h)) if op.get("dir") else Vector(0.0, 0.0, h)
|
|
894
|
+
if abs(vec.Length) < 1e-9:
|
|
895
|
+
raise RuntimeError("extrude 需要 h 或 dir(当前的挤出向量长度为 0)")
|
|
896
|
+
return Part.Face(Part.makePolygon(ps + [ps[0]])).extrude(vec)
|
|
872
897
|
if k == "revolve":
|
|
873
898
|
ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
|
|
874
899
|
ang = float(op.get("angle", 360.0))
|
|
@@ -883,8 +908,14 @@ for _idx, _op in enumerate(_OPS):
|
|
|
883
908
|
_s = _prim(_op)
|
|
884
909
|
_shape = _s if _shape is None else _shape.fuse(_s)
|
|
885
910
|
elif _k in ("fuse", "cut", "common"):
|
|
886
|
-
|
|
887
|
-
|
|
911
|
+
# A U-shaped wall is one feature, not two: with takes a list, and
|
|
912
|
+
# the tools are combined in order against the running shape.
|
|
913
|
+
_ws = _op["with"]
|
|
914
|
+
if not isinstance(_ws, (list, tuple)):
|
|
915
|
+
_ws = [_ws]
|
|
916
|
+
for _w in _ws:
|
|
917
|
+
_s = _prim(_w)
|
|
918
|
+
_shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
|
|
888
919
|
elif _k == "fillet":
|
|
889
920
|
_shape = _shape.makeFillet(float(_op["r"]), _shape.Edges)
|
|
890
921
|
elif _k == "chamfer":
|
|
@@ -926,7 +957,10 @@ for _idx, _op in enumerate(_OPS):
|
|
|
926
957
|
else:
|
|
927
958
|
raise RuntimeError("未知特征:" + str(_k))
|
|
928
959
|
except Exception as _e:
|
|
929
|
-
|
|
960
|
+
# Name the feature, not just its position: "step 10 (cut) failed: 'with'"
|
|
961
|
+
# told the caller nothing about which row to fix.
|
|
962
|
+
raise RuntimeError("第 %d 步 · 特征 %s(%s,%s)失败:%s" % (
|
|
963
|
+
_idx + 1, _op.get("_id", "?"), _op.get("_label") or "-", _k, _e))
|
|
930
964
|
|
|
931
965
|
if _shape is None:
|
|
932
966
|
raise RuntimeError("ops 为空:至少给一个图元")
|
|
@@ -1427,6 +1461,7 @@ else:
|
|
|
1427
1461
|
target: { type: 'string', description: 'Absolute output path; the extension picks the format (.step/.stp/.brep/.iges/.igs/.stl).' },
|
|
1428
1462
|
source: { type: 'string', description: 'Existing model file to export (STEP/IGES/BREP/STL).' },
|
|
1429
1463
|
code: { type: 'string', description: 'FreeCAD Python that produces the geometry; bind `scene` or `export_shapes`.' },
|
|
1464
|
+
model: { type: 'string', description: 'Export a saved model document by name (feature or script model) instead of a file or a script.' },
|
|
1430
1465
|
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
1466
|
alsoStl: { type: 'boolean', description: 'Also write an STL next to the target (a light file for viewers that do not read STEP).' },
|
|
1432
1467
|
},
|
|
@@ -1437,8 +1472,16 @@ else:
|
|
|
1437
1472
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
|
|
1438
1473
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
1439
1474
|
},
|
|
1440
|
-
execute: async ({ target, source, code, minVolume, alsoStl }) => {
|
|
1475
|
+
execute: async ({ target, source, code, model, minVolume, alsoStl }) => {
|
|
1441
1476
|
if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
|
|
1477
|
+
if (typeof model === 'string' && model) {
|
|
1478
|
+
const dirs = bridge.modelsCandidates()
|
|
1479
|
+
const dir = dirs.find((d) => existsSync(join(d, `${model}.json`))) || dirs[0]
|
|
1480
|
+
const doc = await readModel(model, dir)
|
|
1481
|
+
bridge.noteModelsDir(dir)
|
|
1482
|
+
const exported = await exportModelStep(doc, target)
|
|
1483
|
+
return { ...exported, source: `model:${model}` }
|
|
1484
|
+
}
|
|
1442
1485
|
const src = shapesFrom({ source, code })
|
|
1443
1486
|
if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
|
|
1444
1487
|
const out = await writeShapeFile(target, src, { minVolume, alsoStl })
|
|
@@ -1974,7 +2017,7 @@ if _TARGET:
|
|
|
1974
2017
|
/** Feature objects to flat ops (`{kind, ...params}`) for the Python emitter. */
|
|
1975
2018
|
const featureOps = (doc) => doc.features
|
|
1976
2019
|
.filter((f) => f.enabled !== false)
|
|
1977
|
-
.map((f) => ({ kind: f.kind, ...(f.params ?? {}) }))
|
|
2020
|
+
.map((f) => ({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' }))
|
|
1978
2021
|
|
|
1979
2022
|
const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
|
|
1980
2023
|
|
|
@@ -1996,10 +2039,46 @@ if _TARGET:
|
|
|
1996
2039
|
if (hit) maxId = Math.max(maxId, Number(hit[1]))
|
|
1997
2040
|
}
|
|
1998
2041
|
const id = /^f\d+$/.test(String(raw.id ?? '')) ? String(raw.id) : `f${maxId + 1}`
|
|
2042
|
+
const label = String(raw.label ?? '').slice(0, 40)
|
|
2043
|
+
// Validate here, not in FreeCAD: a missing `with` used to surface as
|
|
2044
|
+
// "第 10 步(cut)失败:'with'" — a KeyError with no idea which row to fix.
|
|
2045
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v)
|
|
2046
|
+
const pos = (v) => num(v) && v > 0
|
|
2047
|
+
const triple = (v) => Array.isArray(v) && v.length === 3 && v.every(num)
|
|
2048
|
+
const where = `特征 ${id}${label ? `(${label})` : ''} ${kind}`
|
|
2049
|
+
const need = (cond, hint) => {
|
|
2050
|
+
if (!cond) throw new Error(`${where}:${hint}`)
|
|
2051
|
+
}
|
|
2052
|
+
const tool = (v) => v && typeof v === 'object' && ['box', 'cylinder', 'sphere', 'cone', 'torus', 'extrude', 'revolve'].includes(String(v.kind))
|
|
2053
|
+
const withs = params.with
|
|
2054
|
+
if (kind === 'box') need(triple(params.size) && params.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
|
|
2055
|
+
else if (kind === 'cylinder') need(pos(params.r) && pos(params.h), '需要 r>0 与 h>0')
|
|
2056
|
+
else if (kind === 'sphere') need(pos(params.r), '需要 r>0')
|
|
2057
|
+
else if (kind === 'cone') need(num(params.r1) && num(params.r2) && pos(params.h), '需要 r1 / r2 / h>0')
|
|
2058
|
+
else if (kind === 'torus') need(pos(params.r1) && pos(params.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
|
|
2059
|
+
else if (kind === 'extrude') {
|
|
2060
|
+
const points = Array.isArray(params.points) ? params.points : []
|
|
2061
|
+
need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
|
|
2062
|
+
need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
|
|
2063
|
+
need(pos(params.h) || triple(params.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
|
|
2064
|
+
} else if (kind === 'revolve') {
|
|
2065
|
+
const points = Array.isArray(params.points) ? params.points : []
|
|
2066
|
+
need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
|
|
2067
|
+
} else if (kind === 'fuse' || kind === 'cut' || kind === 'common') {
|
|
2068
|
+
const list = Array.isArray(withs) ? withs : withs ? [withs] : []
|
|
2069
|
+
need(list.length > 0, `需要 with 子图元({kind:"box",size:[…]},或用数组一次减/并多个)`)
|
|
2070
|
+
need(list.every(tool), 'with 里的每一项都要是图元(box/cylinder/sphere/cone/torus/extrude/revolve),且带 kind')
|
|
2071
|
+
} else if (kind === 'fillet') need(pos(params.r), '需要 r>0')
|
|
2072
|
+
else if (kind === 'chamfer') need(pos(params.d), '需要 d>0')
|
|
2073
|
+
else if (kind === 'shell') need(pos(params.t), '需要 t>0(壁厚)')
|
|
2074
|
+
else if (kind === 'pattern_linear') need(triple(params.delta) && num(params.count) && params.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
|
|
2075
|
+
else if (kind === 'pattern_circular') need(num(params.count) && params.count >= 2, '需要 count>=2')
|
|
2076
|
+
else if (kind === 'translate') need(triple(params.v), '需要 v:[dx,dy,dz]')
|
|
2077
|
+
else if (kind === 'rotate') need(num(params.deg), '需要 deg(角度)')
|
|
1999
2078
|
return {
|
|
2000
2079
|
id,
|
|
2001
2080
|
kind,
|
|
2002
|
-
label
|
|
2081
|
+
label,
|
|
2003
2082
|
params: JSON.parse(JSON.stringify(params)),
|
|
2004
2083
|
enabled: raw.enabled !== false,
|
|
2005
2084
|
}
|
|
@@ -2026,11 +2105,15 @@ if _TARGET:
|
|
|
2026
2105
|
sceneId: doc.stats?.sceneId || '',
|
|
2027
2106
|
})
|
|
2028
2107
|
if (out.ok === false) return { ...out, name: doc.name, params: doc.params }
|
|
2108
|
+
// run() returns volume/bounds but not triangle count, so read it back from
|
|
2109
|
+
// the row that was just published (a null here forced the panel to guess).
|
|
2110
|
+
const sceneId = out.sceneId ?? ''
|
|
2111
|
+
const row = sceneId ? bridge.history.find((h) => h.id === sceneId) : null
|
|
2029
2112
|
doc.stats = {
|
|
2030
2113
|
volume: out.volume ?? null,
|
|
2031
|
-
triangles:
|
|
2114
|
+
triangles: row?.triangles ?? null,
|
|
2032
2115
|
bounds: out.bounds ?? null,
|
|
2033
|
-
sceneId
|
|
2116
|
+
sceneId,
|
|
2034
2117
|
at: doc.updatedAt,
|
|
2035
2118
|
}
|
|
2036
2119
|
if (note) doc.note = note
|
|
@@ -2062,6 +2145,7 @@ if _TARGET:
|
|
|
2062
2145
|
features: { type: 'array', items: { type: 'object' }, description: 'For kind="features": the initial feature list, each {kind, label?, params?} (flat params such as {kind:"box", size:[60,40,20]} also work).' },
|
|
2063
2146
|
params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
|
|
2064
2147
|
note: { type: 'string', description: 'What this revision changed (kept in history).' },
|
|
2148
|
+
export: { type: 'string', description: 'Also write the model out as STEP at this path (create / update / show). Saves the caller from re-implementing the feature emitter.' },
|
|
2065
2149
|
},
|
|
2066
2150
|
required: ['action'],
|
|
2067
2151
|
additionalProperties: false,
|
|
@@ -2072,7 +2156,19 @@ if _TARGET:
|
|
|
2072
2156
|
},
|
|
2073
2157
|
execute: async (args, exec) => {
|
|
2074
2158
|
try {
|
|
2075
|
-
|
|
2159
|
+
const dir = modelsDirFor(exec)
|
|
2160
|
+
const out = await runDocAction(args, dir)
|
|
2161
|
+
if (args && typeof args.export === 'string' && args.export && args.name) {
|
|
2162
|
+
// A feature model is the source of truth; the STEP is a product. Do it
|
|
2163
|
+
// here so the caller never has to copy the emitter to their side.
|
|
2164
|
+
try {
|
|
2165
|
+
const doc = await readModel(args.name, dir)
|
|
2166
|
+
out.exported = await exportModelStep(doc, args.export)
|
|
2167
|
+
} catch (error) {
|
|
2168
|
+
out.exportError = String(error?.message ?? error)
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
return out
|
|
2076
2172
|
} catch (err) {
|
|
2077
2173
|
// Tool errors are data, not exceptions: the agent needs to read the
|
|
2078
2174
|
// message and try something else, and a throw would also skip cleanup.
|
|
@@ -2192,6 +2288,32 @@ if _TARGET:
|
|
|
2192
2288
|
},
|
|
2193
2289
|
})
|
|
2194
2290
|
|
|
2291
|
+
/**
|
|
2292
|
+
* Turn a model document into a STEP file without the caller re-implementing
|
|
2293
|
+
* the emitter. A feature model runs its own `featuresScript` (which already
|
|
2294
|
+
* knows how to export); a script model gets three extra lines appended.
|
|
2295
|
+
*/
|
|
2296
|
+
async function exportModelStep(doc, target) {
|
|
2297
|
+
if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
|
|
2298
|
+
await mkdir(dirname(target), { recursive: true })
|
|
2299
|
+
const head = doc.kind === 'features'
|
|
2300
|
+
? featuresScript(featureOps(doc), target)
|
|
2301
|
+
: `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
|
|
2302
|
+
const code = doc.kind === 'features'
|
|
2303
|
+
? head
|
|
2304
|
+
: `${head}import os as _os
|
|
2305
|
+
_os.makedirs(_os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
|
|
2306
|
+
Part.makeCompound([scene]).exportStep(${JSON.stringify(target)})
|
|
2307
|
+
__out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scene.Volume, 3),
|
|
2308
|
+
"bytes": _os.path.getsize(${JSON.stringify(target)})}`
|
|
2309
|
+
// publish:false — an export is a product, not a new row in the model list.
|
|
2310
|
+
const out = await bridge.run(code, { title: `${doc.name} → STEP`, publish: false })
|
|
2311
|
+
if (out.ok === false) return { ...out, model: doc.name, path: target }
|
|
2312
|
+
let bytes = Number(out.bytes ?? 0)
|
|
2313
|
+
try { bytes = (await stat(target)).size } catch {}
|
|
2314
|
+
return { ok: true, model: doc.name, path: target, bytes, valid: bytes > 200, volume: out.volume ?? null }
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2195
2317
|
async function runDocAction(args, dir) {
|
|
2196
2318
|
bridge.noteModelsDir(dir)
|
|
2197
2319
|
const action = String(args.action ?? '')
|