dsh-cad-studio 0.2.9 → 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/index.js +275 -10
- 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/index.js
CHANGED
|
@@ -531,6 +531,54 @@ class FreeCadBridge {
|
|
|
531
531
|
return { id, stats }
|
|
532
532
|
}
|
|
533
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
|
+
|
|
534
582
|
/** Reserve the id before publishing, so the scene can carry `asm:<id>`. */
|
|
535
583
|
reserveAssemblyId() {
|
|
536
584
|
return `asm-${++this.assemblySeq}`
|
|
@@ -633,7 +681,7 @@ class FreeCadBridge {
|
|
|
633
681
|
return null
|
|
634
682
|
}
|
|
635
683
|
|
|
636
|
-
async run(code, { title, publishHint = true, meta = null, docKey = '', sceneId = '' } = {}) {
|
|
684
|
+
async run(code, { title, publishHint = true, publish = true, meta = null, docKey = '', sceneId = '' } = {}) {
|
|
637
685
|
const bin = this.refresh()
|
|
638
686
|
if (!bin) {
|
|
639
687
|
return { ok: false, error: 'freecadcmd not found; set freecadPath in the plugin config' }
|
|
@@ -697,7 +745,7 @@ print("${BEGIN}" + __json.dumps(_safe(_payload)) + "${END}", flush=True)\n`
|
|
|
697
745
|
} catch (error) {
|
|
698
746
|
return { ok: false, error: `helper returned non-JSON: ${String(error?.message ?? error)}`, raw: payload.slice(0, 500) }
|
|
699
747
|
}
|
|
700
|
-
if (value?.scene) {
|
|
748
|
+
if (value?.scene && publish !== false) {
|
|
701
749
|
// A shape bound to `scene = box` arrives with the variable name as the
|
|
702
750
|
// instance label; the caller's title is what a human expects in the tree.
|
|
703
751
|
const first = value.scene.instances?.[0]
|
|
@@ -709,6 +757,7 @@ print("${BEGIN}" + __json.dumps(_safe(_payload)) + "${END}", flush=True)\n`
|
|
|
709
757
|
value.sceneId = published.id
|
|
710
758
|
delete value.scene
|
|
711
759
|
}
|
|
760
|
+
if (publish === false) delete value.scene
|
|
712
761
|
const clean = { ok: true, ...value }
|
|
713
762
|
clean.published = Boolean(clean.sceneId)
|
|
714
763
|
if (!clean.published && publishHint) {
|
|
@@ -1054,6 +1103,94 @@ __out = {
|
|
|
1054
1103
|
execute: async () => bridge.status(),
|
|
1055
1104
|
})
|
|
1056
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
|
+
|
|
1057
1194
|
tool({
|
|
1058
1195
|
name: 'cad_studio_setup',
|
|
1059
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.',
|
|
@@ -1099,12 +1236,18 @@ __out = {
|
|
|
1099
1236
|
|
|
1100
1237
|
tool({
|
|
1101
1238
|
name: 'cad_studio_run',
|
|
1102
|
-
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.',
|
|
1103
1240
|
parameters: {
|
|
1104
1241
|
type: 'object',
|
|
1105
1242
|
properties: {
|
|
1106
1243
|
code: { type: 'string', description: 'FreeCAD Python source. Import Part/Import yourself; helpers describe(path)/_mesh(shape) are preloaded.' },
|
|
1107
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
|
+
},
|
|
1108
1251
|
},
|
|
1109
1252
|
required: ['code'],
|
|
1110
1253
|
additionalProperties: false,
|
|
@@ -1113,7 +1256,47 @@ __out = {
|
|
|
1113
1256
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' }, stderr: { type: 'string' } } },
|
|
1114
1257
|
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1115
1258
|
},
|
|
1116
|
-
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
|
+
},
|
|
1117
1300
|
})
|
|
1118
1301
|
|
|
1119
1302
|
tool({
|
|
@@ -1166,7 +1349,9 @@ if not _shapes:
|
|
|
1166
1349
|
`
|
|
1167
1350
|
}
|
|
1168
1351
|
|
|
1169
|
-
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)
|
|
1170
1355
|
const py = `${PRELUDE}
|
|
1171
1356
|
${src}
|
|
1172
1357
|
if not _shapes:
|
|
@@ -1176,6 +1361,16 @@ else:
|
|
|
1176
1361
|
_target = ${JSON.stringify(target)}
|
|
1177
1362
|
_fmt = _target.rsplit(".", 1)[-1].lower()
|
|
1178
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
|
|
1179
1374
|
if _fmt in ("step", "stp"):
|
|
1180
1375
|
# Part.export([shape]) writes a 1.6 KB STEP that reads back as a NULL shape;
|
|
1181
1376
|
# Shape.exportStep / compound exportStep is the API that produces a valid file.
|
|
@@ -1200,7 +1395,25 @@ else:
|
|
|
1200
1395
|
open(_target, "w").write("\\n".join(_lines) + "\\n")
|
|
1201
1396
|
else:
|
|
1202
1397
|
raise RuntimeError("unsupported export format: ." + _fmt + " (use .step/.stp/.brep/.iges/.igs/.stl)")
|
|
1203
|
-
|
|
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)}
|
|
1204
1417
|
`
|
|
1205
1418
|
return bridge.run(py, { title: `export → ${target}`, publishHint: false })
|
|
1206
1419
|
}
|
|
@@ -1214,6 +1427,8 @@ else:
|
|
|
1214
1427
|
target: { type: 'string', description: 'Absolute output path; the extension picks the format (.step/.stp/.brep/.iges/.igs/.stl).' },
|
|
1215
1428
|
source: { type: 'string', description: 'Existing model file to export (STEP/IGES/BREP/STL).' },
|
|
1216
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).' },
|
|
1217
1432
|
},
|
|
1218
1433
|
required: ['target'],
|
|
1219
1434
|
additionalProperties: false,
|
|
@@ -1222,11 +1437,15 @@ else:
|
|
|
1222
1437
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
|
|
1223
1438
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
1224
1439
|
},
|
|
1225
|
-
execute: async ({ target, source, code }) => {
|
|
1440
|
+
execute: async ({ target, source, code, minVolume, alsoStl }) => {
|
|
1226
1441
|
if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
|
|
1227
1442
|
const src = shapesFrom({ source, code })
|
|
1228
1443
|
if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
|
|
1229
|
-
|
|
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 : '' }
|
|
1230
1449
|
},
|
|
1231
1450
|
})
|
|
1232
1451
|
|
|
@@ -1391,6 +1610,8 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
1391
1610
|
},
|
|
1392
1611
|
target: { type: 'string', description: 'Optional .step/.stp output path for the whole assembly.' },
|
|
1393
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).' },
|
|
1394
1615
|
assembly: { type: 'string', description: 'Assembly label for cad_studio_joint / cad_studio_drive / cad_studio_explode (defaults to the title).' },
|
|
1395
1616
|
joints: {
|
|
1396
1617
|
type: 'array',
|
|
@@ -1418,7 +1639,7 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
1418
1639
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' }, instances: { type: 'number' }, assembly: { type: 'string' } } },
|
|
1419
1640
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
1420
1641
|
},
|
|
1421
|
-
execute: async ({ parts, instances, target, title, assembly, joints }) => {
|
|
1642
|
+
execute: async ({ parts, instances, target, title, assembly, joints, measure, interference }) => {
|
|
1422
1643
|
if (!Array.isArray(parts) || !parts.length) return { ok: false, error: 'parts must be a non-empty array' }
|
|
1423
1644
|
if (!Array.isArray(instances) || !instances.length) return { ok: false, error: 'instances must be a non-empty array' }
|
|
1424
1645
|
// Only referenced parts are read and tessellated: an export set often
|
|
@@ -1464,8 +1685,50 @@ for _i in _INSTS:
|
|
|
1464
1685
|
_copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
|
|
1465
1686
|
_placed.append(_copy)
|
|
1466
1687
|
|
|
1688
|
+
_MEASURE = ${measure ? 'True' : 'False'}
|
|
1689
|
+
_INTERF = ${interference ? 'True' : 'False'}
|
|
1690
|
+
|
|
1467
1691
|
__out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
|
|
1468
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
|
|
1469
1732
|
if _TARGET:
|
|
1470
1733
|
os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
|
|
1471
1734
|
Part.makeCompound(_placed).exportStep(_TARGET)
|
|
@@ -2106,7 +2369,9 @@ if _TARGET:
|
|
|
2106
2369
|
// route closure left by a hot reload still lists what is on disk.
|
|
2107
2370
|
try {
|
|
2108
2371
|
const parsed = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
|
|
2109
|
-
|
|
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 ?? [] }))
|
|
2110
2375
|
} catch {
|
|
2111
2376
|
return send(200, JSON.stringify({ latest: null, scenes: [] }))
|
|
2112
2377
|
}
|
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
|
+
}
|