dsh-cad-studio 0.6.0 → 0.8.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 +63 -0
  2. package/client.js +90 -2
  3. package/index.js +466 -40
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -69,6 +69,18 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
69
69
 
70
70
  选不中会**报错并在面板标红**:`选择器没有选中任何边:{"axis":"Z","type":"circle"}(当前形状有 12 条边)`。设计取舍见 `docs/RESEARCH-SELECTORS.md`。
71
71
 
72
+ ## 增量重算
73
+
74
+ 改一条特征不需要重跑整条链:每一步的 BREP 快照按「前缀哈希」缓存在 `$TMPDIR/dsh-cad-studio/cache/`,重算从最深命中的前缀恢复。
75
+
76
+ ```
77
+ 首次 17 条特征 354 ms
78
+ 无改动的重建 1 ms (完全不起内核进程,revalidated: true)
79
+ 只改最后一条 264 ms (16/17 来自缓存)
80
+ ```
81
+
82
+ 面板的特征页头会显示 `· 缓存 16/17`。缓存按 400 文件 / 14 天淘汰;`EMITTER_VERSION` 一变即整体失效(防止旧快照复活错误几何)。
83
+
72
84
  ## 接口约定与踩过的坑
73
85
 
74
86
  - **导出只走 `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`。
@@ -156,3 +168,54 @@ node scripts/shots.mjs --url http://127.0.0.1:3201 --token-file /tmp/dev-token.t
156
168
  ## License
157
169
 
158
170
  MIT
171
+
172
+ ## 安装即用 与 环境自检
173
+
174
+ 插件本体零依赖(只有 JS + three.js),但**几何内核是外部程序**:`freecadcmd`(约 213 MB,
175
+ 按平台编译,LGPL)。这是唯一一个「不能安装即用」的必要依赖,所以它必须有引导:
176
+
177
+ - **面板内引导**:内核缺失时,面板主体不是空白视口,而是三步卡片——① 点「安装 FreeCAD」
178
+ (apt/dnf/pacman/brew 自动识别,非 root 会显示原因与手抄命令)② 装完点「重新检测」
179
+ ③ 装在非标准位置就配 `freecadPath`。装好后面板自动恢复,无需重启。
180
+ - **给 AI 的自检**:`cad_studio_doctor` 返回每一项前置条件的 `ok / detail / fix` 与
181
+ 当前能力开关(modeling / assembly / drawing / measure / export / incremental);
182
+ `cad_studio_setup` 负责实际安装。**报错先自检**,别把环境问题当成模型问题。
183
+ - **可选能力**:全部随内核可用,没有第二个需要单独安装的可选项;出图(HLR→SVG)、
184
+ 测量、STEP/STL 导出都在进程内完成。若将来引入外部可选件,同样走「状态检测 + 安装引导」。
185
+
186
+ ## 特征挂在面上(`at.ref`)
187
+
188
+ 图元的位置可以写成一个面选择器加偏移,而不是绝对坐标:
189
+
190
+ ```json
191
+ {"kind": "fuse", "with": {"kind": "cylinder", "r": 10, "h": 12,
192
+ "at": {"ref": {"axis": "Z", "mode": "aligned", "dir": "+", "type": "plane"},
193
+ "offset": [0, 0, -6]}}}
194
+ ```
195
+
196
+ 板子从 16 厚改到 30 厚,凸台跟着顶面走(实测总面积增量恒为 100×80×14 = 112000 mm³)。
197
+ 选择器选不中时会**明确报错**(`at.ref 没有选中任何面:{…}(当前形状有 6 个面)`),
198
+ 不会静默落到原点。
199
+
200
+ ## 变量与表达式
201
+
202
+ 文档可以带一组命名的尺寸,特征的数值可以写表达式:
203
+
204
+ ```json
205
+ {"vars": {"w": 100, "d": 80, "t": 10},
206
+ "features": [
207
+ {"kind": "box", "size": ["w", "d", "t"]},
208
+ {"kind": "cut", "with": {"kind": "cylinder", "r": "w/10", "h": "t*3",
209
+ "at": ["w/2", "d/2", "-t"]}}]}
210
+ ```
211
+
212
+ 改 `w` 只需 `cad_studio_doc {"action":"update","vars":{"w":200}}`,所有依赖它的尺寸一起变
213
+ (100→200 实测体积 76858.41→147433.63 mm³)。表达式由 60 行 shunting-yard 在 JS 里算,
214
+ **绝不用 `eval`、也不交给 FreeCAD**:只接受 `数字 / 变量名 / + - * / ( ) / 一元负号`,
215
+ 出现引号或函数调用的字符串一律当字面量并随后被类型校验拒掉。
216
+
217
+ ## 依赖关系(哪些东西会互相影响)
218
+
219
+ `cad_studio_features {action:"list"}` 与 `cad_studio_doc {action:"show"}` 返回的 `graph.nodes`
220
+ 里,每个节点带 `dependsOn / dependents / anchored`:特征是顺序求值链(`f3` 依赖 `f2`),
221
+ `anchored: true` 表示它还跟着某个面走。这是如实的表示——我们不假装有一个比实际更复杂的图。
package/client.js CHANGED
@@ -80,6 +80,13 @@ window.__ModuleLoader__.load({
80
80
  modelRow: (active) => ({ display: 'flex', flexDirection: 'column', gap: 1, width: '100%', textAlign: 'left', padding: '5px 9px', border: 'none', background: active ? 'rgba(77,107,254,0.14)' : 'transparent', color: 'inherit', cursor: 'pointer', font: 'inherit', borderRadius: 0 }),
81
81
  modelName: { fontSize: 11.5, fontWeight: active => (active ? 600 : 400), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
82
82
  modelMeta: { fontSize: 9.5, opacity: 0.55, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
83
+ guide: { display: 'flex', flexDirection: 'column', gap: 8, padding: '14px 12px', fontSize: 12, lineHeight: 1.6, overflowY: 'auto' },
84
+ guideTitle: { fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 },
85
+ guideStep: { display: 'flex', gap: 7, alignItems: 'flex-start' },
86
+ guideNum: { flex: '0 0 auto', width: 16, height: 16, borderRadius: 8, marginTop: 2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, background: 'rgba(120,130,145,.18)' },
87
+ guideCode: { fontFamily: 'ui-monospace, monospace', fontSize: 11, padding: '3px 6px', borderRadius: 4, background: 'rgba(120,130,145,.14)', display: 'inline-block', marginTop: 2, userSelect: 'all', wordBreak: 'break-all' },
88
+ guideRow: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginTop: 2 },
89
+ guideDot: (ok, required) => ({ flex: '0 0 auto', width: 6, height: 6, borderRadius: 3, marginTop: 6, background: ok ? '#2ea043' : (required ? '#e5534b' : '#e0a33a') }),
83
90
  installBox: { margin: '8px 9px 6px', padding: '8px 9px', borderRadius: 8, border: '1px solid rgba(224,163,58,.45)', background: 'rgba(224,163,58,.10)', fontSize: 11, lineHeight: 1.5 },
84
91
  installBtn: { marginTop: 6, width: '100%', padding: '5px 8px', borderRadius: 6, border: '1px solid rgba(77,107,254,.5)', background: 'rgba(77,107,254,.16)', color: 'inherit', fontSize: 11, cursor: 'pointer' },
85
92
  installHint: { opacity: 0.72, marginTop: 4, wordBreak: 'break-all' },
@@ -1246,6 +1253,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1246
1253
  const [visibility, setVisibility] = useState({})
1247
1254
  const [error, setError] = useState('')
1248
1255
  const [installing, setInstalling] = useState('')
1256
+ const [installMsg, setInstallMsg] = useState('')
1249
1257
  // The visible scene, and the identity the per-scene view state is keyed
1250
1258
  // on: republishing one assembly (drive / explode) keeps its colours,
1251
1259
  // switching to another scene does not.
@@ -1749,6 +1757,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1749
1757
  // the new scene replaces the old one in the tab being looked at.
1750
1758
  const featureList = payload && Array.isArray(payload.features) ? payload.features : []
1751
1759
  const featureModel = (payload && payload.model) || ''
1760
+ const cacheChip = payload && payload.cache && payload.cache.cached > 0 ? payload.cache : null
1752
1761
  // A script model publishes its params (no feature list); they are editable
1753
1762
  // the same way — one number, one rebuild of the same document.
1754
1763
  const modelParams = payload && payload.params && typeof payload.params === 'object' ? payload.params : {}
@@ -1930,7 +1939,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1930
1939
  : '当前场景不是特征模型。用 cad_studio_doc create kind="features" 建一个(features 里每个 {kind,params}),就能在这里逐条改数值。')]
1931
1940
  : [
1932
1941
  h('div', { key: 'h', style: { ...styles.treeHint, display: 'flex', gap: 6, alignItems: 'center' } }, [
1933
- h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, `${featureModel} · ${featureList.length} 特征`),
1942
+ h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', title: cacheChip ? `本次重算:${cacheChip.cached}/${cacheChip.of} 步来自缓存` : undefined } }, `${featureModel} · ${featureList.length} 特征${cacheChip ? ` · 缓存 ${cacheChip.cached}/${cacheChip.of}` : ''}`),
1934
1943
  h('button', {
1935
1944
  key: 'a',
1936
1945
  type: 'button',
@@ -2146,6 +2155,78 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2146
2155
  }
2147
2156
  }
2148
2157
 
2158
+ const redetect = async () => {
2159
+ setInstallMsg('正在检测…')
2160
+ try {
2161
+ const res = await fetch(`${ROUTE}/state`, { headers: { accept: 'application/json' } })
2162
+ if (res.ok) setState(await res.json())
2163
+ const doc = await fetch(`${ROUTE}/doctor`, { headers: { accept: 'application/json' } })
2164
+ if (doc.ok) {
2165
+ const d = await doc.json()
2166
+ const bad = (d.checks || []).filter((c) => !c.ok)
2167
+ setInstallMsg(d.ready ? '检测通过,可以用了。' : (bad.length ? `${bad[0].label}:${bad[0].detail}` : '仍未就绪'))
2168
+ } else setInstallMsg('')
2169
+ } catch (e) {
2170
+ setInstallMsg(`检测失败:${String(e).slice(0, 120)}`)
2171
+ }
2172
+ }
2173
+
2174
+ const installNow = async () => {
2175
+ setInstallMsg('')
2176
+ await installFreecad()
2177
+ setInstallMsg(installing || '')
2178
+ try {
2179
+ const doc = await fetch(`${ROUTE}/doctor`, { headers: { accept: 'application/json' } })
2180
+ if (doc.ok) {
2181
+ const d = await doc.json()
2182
+ setInstallMsg(d.ready ? '装好了,正在重新读取模型…' : ((d.checks || []).filter((c) => !c.ok)[0] || {}).fix || '装完但仍未就绪')
2183
+ }
2184
+ } catch {}
2185
+ }
2186
+
2187
+ // Install-and-run promise: when the kernel is missing, the panel is a
2188
+ // three-step guide, not an empty viewport with a red dot somewhere else.
2189
+ const diagChecks = (state && state.diag && state.diag.checks) || []
2190
+ const guideNode = h('div', { key: 'guide', style: styles.guide, 'data-cad-guide': '1' }, [
2191
+ h('div', { key: 't', style: styles.guideTitle }, [h('span', { style: styles.guideDot(false, true) }), '需要 FreeCAD(唯一的外部依赖)']),
2192
+ h('div', { key: 'why', style: { opacity: 0.75, fontSize: 11 } }, `几何内核不随插件分发(约 213 MB,按平台编译)。装好之后这个面板就能用,无需再配置。`),
2193
+ h('div', { key: 's1', style: styles.guideStep }, [
2194
+ h('span', { key: 'n', style: styles.guideNum }, '1'),
2195
+ h('div', { key: 'b' }, [
2196
+ h('div', { key: 'l' }, setup.canInstall ? `点下面的按钮自动安装(${setup.packageManager || '系统包管理器'})` : '用系统的包管理器安装'),
2197
+ setup.command ? h('div', { key: 'c', style: styles.guideCode }, setup.reason ? `${setup.command} # ${setup.reason}` : setup.command) : null,
2198
+ ]),
2199
+ ]),
2200
+ h('div', { key: 's2', style: styles.guideStep }, [
2201
+ h('span', { key: 'n', style: styles.guideNum }, '2'),
2202
+ h('div', { key: 'b' }, [h('div', { key: 'l' }, '装完点「重新检测」;也可以直接装好再来,面板每次打开都会自检'),]),
2203
+ ]),
2204
+ h('div', { key: 's3', style: styles.guideStep }, [
2205
+ h('span', { key: 'n', style: styles.guideNum }, '3'),
2206
+ h('div', { key: 'b' }, [
2207
+ h('div', { key: 'l' }, '装在非标准位置?配置 freecadPath 指到 freecadcmd 即可(探测顺序:配置 → /usr/bin → /usr/local/bin → /opt/freecad → macOS app)'),
2208
+ ]),
2209
+ ]),
2210
+ h('div', { key: 'row', style: styles.guideRow }, [
2211
+ h('button', {
2212
+ key: 'install',
2213
+ type: 'button',
2214
+ style: styles.installBtn,
2215
+ 'data-cad-install': '1',
2216
+ disabled: installing !== '' || !setup.canInstall,
2217
+ onClick: installNow,
2218
+ }, installing || (setup.canInstall ? '安装 FreeCAD' : '需要 root 才能自动安装')),
2219
+ h('button', {
2220
+ key: 'recheck',
2221
+ type: 'button',
2222
+ style: styles.microBtn,
2223
+ 'data-cad-recheck': '1',
2224
+ onClick: () => { redetect() },
2225
+ }, '重新检测'),
2226
+ ]),
2227
+ installMsg ? h('div', { key: 'msg', style: { fontSize: 11, opacity: 0.8, whiteSpace: 'pre-wrap' }, 'data-cad-install-msg': '1' }, installMsg) : null,
2228
+ ])
2229
+
2149
2230
  const installNode = runtime.available
2150
2231
  ? null
2151
2232
  : h('div', { key: 'install', style: styles.installBox, 'data-cad-install-box': '1' }, [
@@ -2411,6 +2492,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2411
2492
  h('span', { key: 'k', style: styles.infoKey }, key),
2412
2493
  h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '65%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: value }, value),
2413
2494
  ])),
2495
+ ...diagChecks.map((chk) => h('div', { key: `diag-${chk.id}`, style: { ...styles.infoRow, alignItems: 'flex-start' }, 'data-cad-diag': chk.id }, [
2496
+ h('span', { key: 'd', style: styles.guideDot(chk.ok, chk.required) }),
2497
+ h('span', { key: 'k', style: { ...styles.infoKey, maxWidth: '46%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: chk.label }, chk.label),
2498
+ h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '52%', whiteSpace: 'normal' }, title: chk.fix || chk.detail }, chk.ok ? chk.detail : (chk.fix || chk.detail)),
2499
+ ])),
2414
2500
  ...(installNode ? [installNode] : []),
2415
2501
  ]
2416
2502
  : null
@@ -2537,7 +2623,9 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2537
2623
  onClick: () => { setAddOpen(false); setPanel((p) => (p === item.id ? '' : item.id)) },
2538
2624
  }, h(RailIcon, { name: item.id })))),
2539
2625
  h('div', { key: 'main', style: { flex: '1 1 auto', minWidth: 0, position: 'relative', display: 'flex', flexDirection: 'column' } }, [
2540
- payload
2626
+ !runtime.available
2627
+ ? guideNode
2628
+ : payload
2541
2629
  ? h('div', { key: 'stage', style: styles.stage }, h(Viewport, { payload, visibility, options: { ...display, overrides, opacities, wireframes, restoreCamera: pendingCameraRef.current, onPick: pickInViewport }, handleRef: viewportRef }))
2542
2630
  : h('div', { key: 'empty', style: styles.empty }, '还没有模型。让 AI 跑一次 FreeCAD 脚本或打开一个 STEP 文件,这里会自动显示。'),
2543
2631
  picked && panel !== 'parts'
package/index.js CHANGED
@@ -14,7 +14,8 @@
14
14
  * GET /cad-studio/client.js the panel bundle (dev-mode serving)
15
15
  */
16
16
  import { spawn, spawnSync } from 'node:child_process'
17
- import { existsSync } from 'node:fs'
17
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, statfsSync, writeFileSync } from 'node:fs'
18
+ import crypto from 'node:crypto'
18
19
  import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
19
20
  import { tmpdir } from 'node:os'
20
21
  import { fileURLToPath } from 'node:url'
@@ -109,6 +110,89 @@ function setupStatus(bridge, { withVersion = true } = {}) {
109
110
  }
110
111
 
111
112
  /** Install FreeCAD through the detected packager; returns a plain outcome. */
113
+ /**
114
+ * "Install and it works" is the product promise; this is the function that
115
+ * tells the truth about whether we can keep it. Every check says what is wrong
116
+ * AND what to do about it, so the panel never shows a dead end.
117
+ */
118
+ function diagnose(bridge, cfg = {}) {
119
+ const kernel = setupStatus(bridge, { withVersion: true })
120
+ const dir = FreeCadBridge.dataDir
121
+ const checks = []
122
+ checks.push({
123
+ id: 'kernel',
124
+ label: '几何内核(FreeCAD / OCCT)',
125
+ required: true,
126
+ ok: kernel.available === true,
127
+ detail: kernel.available ? [kernel.binary, kernel.version].filter(Boolean).join(' · ') : '没有找到 freecadcmd',
128
+ fix: kernel.available ? '' : (kernel.canInstall
129
+ ? '点「安装 FreeCAD」自动装(需要 root),或手动执行:' + (kernel.command || 'apt install freecad')
130
+ : (kernel.reason || '请手动安装 FreeCAD,再把 freecadPath 指到 freecadcmd')),
131
+ action: kernel.available ? '' : (kernel.canInstall ? 'install' : ''),
132
+ packageManager: kernel.packageManager || '',
133
+ })
134
+ let writable = false
135
+ try {
136
+ mkdirSync(dir, { recursive: true })
137
+ const probe = join(dir, '.write-probe')
138
+ writeFileSync(probe, '1')
139
+ rmSync(probe, { force: true })
140
+ writable = true
141
+ } catch {}
142
+ checks.push({
143
+ id: 'datadir',
144
+ label: '数据目录(场景与缓存)',
145
+ required: true,
146
+ ok: writable,
147
+ detail: writable ? dir : `${dir}(不可写)`,
148
+ fix: writable ? '' : '把这个目录改成可写,或用环境变量 TMPDIR 指到可写位置',
149
+ })
150
+ let freeMB = null
151
+ try { const st = statfsSync(dir); freeMB = Math.round((st.bavail * st.bsize) / 1048576) } catch {}
152
+ checks.push({
153
+ id: 'disk',
154
+ label: '可用磁盘',
155
+ required: false,
156
+ ok: freeMB === null || freeMB > 500,
157
+ detail: freeMB === null ? '无法读取' : `${freeMB} MB`,
158
+ fix: freeMB !== null && freeMB <= 500 ? '剩余空间不足 500 MB,重建大模型可能失败' : '',
159
+ })
160
+ const modelsDir = cfg.modelsDir || ''
161
+ checks.push({
162
+ id: 'models',
163
+ label: '模型目录',
164
+ required: false,
165
+ ok: true,
166
+ detail: modelsDir || '跟随会话工作区(<cwd>/cad-models)',
167
+ fix: '',
168
+ })
169
+ const ready = checks.filter((c) => c.required).every((c) => c.ok)
170
+ return {
171
+ ready,
172
+ kernel,
173
+ checks,
174
+ // What the plugin can actually do right now. The panel greys out the rest
175
+ // instead of letting a click fail deep inside a spawn.
176
+ capabilities: {
177
+ modeling: ready,
178
+ assembly: ready,
179
+ drawing: ready,
180
+ measure: ready,
181
+ export: ready,
182
+ incremental: ready,
183
+ },
184
+ }
185
+ }
186
+
187
+ const renderDoctor = (v) => {
188
+ const lines = [`ready: ${v.ready ? 'yes' : 'no'}`]
189
+ if (v.kernel) lines.push(`kernel: ${v.kernel}`)
190
+ for (const c of v.checks || []) lines.push(`- ${c}`)
191
+ const caps = Object.entries(v.capabilities || {}).map(([k, ok]) => `${k}=${ok ? 'yes' : 'no'}`).join(' ')
192
+ if (caps) lines.push(`capabilities: ${caps}`)
193
+ return lines.join('\n')
194
+ }
195
+
112
196
  function installFreeCad(bridge, { timeoutMs = 900000 } = {}) {
113
197
  const before = setupStatus(bridge)
114
198
  if (before.available) return { ok: true, alreadyInstalled: true, ...before, log: '' }
@@ -270,19 +354,130 @@ function bboxCenterOfInstances(parts, instances) {
270
354
  function normalizeJoint(record, spec) {
271
355
  const inst = record.base.find((b) => b.name === spec.instance)
272
356
  if (!inst) throw new Error(`装配里没有这个实例:${spec.instance}`)
273
- const type = spec.type === 'linear' ? 'linear' : 'revolute'
274
- const fallbackAxis = type === 'linear' ? [1, 0, 0] : [0, 0, 1]
357
+ // Five declared joint kinds, all driven along their single declared axis.
358
+ // This is deliberately not a constraint solver: a joint states which DOF the
359
+ // AI/user may drive, and the panel exposes exactly that one number.
360
+ // revolute rotate about axis linear slide along axis
361
+ // cylindrical rotate about axis planar slide in the plane
362
+ // ball rotate about axis (free direction, single driven angle)
363
+ const JOINTS = ['revolute', 'linear', 'cylindrical', 'planar', 'ball']
364
+ const type = JOINTS.includes(spec.type) ? spec.type : 'revolute'
365
+ const slidey = type === 'linear' || type === 'planar'
366
+ const fallbackAxis = slidey ? [1, 0, 0] : [0, 0, 1]
275
367
  const axis = normVec(Array.isArray(spec.axis) && spec.axis.length === 3 ? spec.axis : fallbackAxis)
276
368
  // Rotating about the instance's own centre is the useful default (a spinning
277
369
  // wheel); a hinge passes an explicit origin on the edge.
278
370
  const origin = Array.isArray(spec.origin) && spec.origin.length === 3 ? spec.origin.map(Number) : inst.center.slice()
279
- const min = Number.isFinite(spec.min) ? Number(spec.min) : type === 'linear' ? -1000 : -180
280
- const max = Number.isFinite(spec.max) ? Number(spec.max) : type === 'linear' ? 1000 : 180
371
+ const min = Number.isFinite(spec.min) ? Number(spec.min) : slidey ? -1000 : -180
372
+ const max = Number.isFinite(spec.max) ? Number(spec.max) : slidey ? 1000 : 180
281
373
  const value = Math.min(max, Math.max(min, Number.isFinite(spec.value) ? Number(spec.value) : 0))
374
+ // A cylindrical joint has two DOF but we drive one number; the other is a
375
+ // fixed second parameter so the geometry stays deterministic.
376
+
282
377
  const id = typeof spec.id === 'string' && spec.id.trim() ? spec.id.trim() : `${type}-${record.joints.length + 1}`
283
378
  return { id, instance: spec.instance, type, axis, origin, min, max, value }
284
379
  }
285
380
 
381
+ /**
382
+ * Variables and expressions (DESIGN §7 Phase 4).
383
+ *
384
+ * Dimensions are allowed to be expressions over the document's `vars`, e.g.
385
+ * `"w*2 + 10"`. They are evaluated here, in JS, with a 60-line shunting-yard —
386
+ * deliberately NOT by handing the string to FreeCAD or to `eval`: a model file
387
+ * that arrives from someone else must not be able to execute anything.
388
+ */
389
+ /** `vars` is a flat bag of named dimensions; anything else is ignored. */
390
+ function normalizeVars(raw, base = {}) {
391
+ const out = { ...base }
392
+ if (raw === null) return {}
393
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
394
+ for (const [k, v] of Object.entries(raw)) {
395
+ if (!/^[A-Za-z_]\w{0,40}$/.test(k)) continue
396
+ if (v === null) { delete out[k]; continue }
397
+ if (Number.isFinite(Number(v))) out[k] = Number(v)
398
+ }
399
+ return out
400
+ }
401
+
402
+ const EXPR_OK = /^[0-9A-Za-z_+\-*/(). \t]*$/
403
+
404
+ function evalExpression(src, vars) {
405
+ const text = String(src).trim()
406
+ if (!EXPR_OK.test(text)) throw new Error(`表达式里有不支持的字符:${text}`)
407
+ const tokens = text.match(/\d+\.?\d*|[A-Za-z_]\w*|[+\-*/()]/g) || []
408
+ const out = []
409
+ const ops = []
410
+ const prec = { '+': 1, '-': 1, '*': 2, '/': 2 }
411
+ const apply = (op) => {
412
+ const b = out.pop()
413
+ const a = out.pop()
414
+ if (a === undefined || b === undefined) throw new Error(`表达式不完整:${text}`)
415
+ out.push(op === '+' ? a + b : op === '-' ? a - b : op === '*' ? a * b : a / b)
416
+ }
417
+ let prev = ''
418
+ for (const tk of tokens) {
419
+ if (tk === '-' && (prev === '' || prev === '(' || prec[prev])) {
420
+ // Unary minus: "−t" is 0 − t, not a syntax error.
421
+ out.push(0)
422
+ ops.push('-')
423
+ prev = '-'
424
+ continue
425
+ }
426
+ if (/^\d/.test(tk)) out.push(Number(tk))
427
+ else if (/^[A-Za-z_]/.test(tk)) {
428
+ const v = vars?.[tk]
429
+ if (!Number.isFinite(v)) throw new Error(`表达式里的变量没有定义或不是数字:${tk}`)
430
+ out.push(Number(v))
431
+ } else if (tk === '(') ops.push(tk)
432
+ else if (tk === ')') {
433
+ while (ops.length && ops[ops.length - 1] !== '(') apply(ops.pop())
434
+ if (ops.pop() !== '(') throw new Error(`括号不配对:${text}`)
435
+ prev = tk
436
+ } else {
437
+ while (ops.length && prec[ops[ops.length - 1]] >= prec[tk]) apply(ops.pop())
438
+ ops.push(tk)
439
+ }
440
+ }
441
+ while (ops.length) {
442
+ const op = ops.pop()
443
+ if (op === '(') throw new Error(`括号不配对:${text}`)
444
+ apply(op)
445
+ }
446
+ if (out.length !== 1 || !Number.isFinite(out[0])) throw new Error(`表达式算不出数值:${text}`)
447
+ return out[0]
448
+ }
449
+
450
+ // Keys whose strings are vocabulary, not arithmetic: a `kind: "cylinder"` or a
451
+ // selector's `axis: "Z"` must never be mistaken for an expression.
452
+ const EXPR_SKIP_KEYS = new Set(['kind', 'type', 'axis', 'mode', 'dir', 'pick', 'label', 'name', 'ref'])
453
+
454
+ /** Deep-walk feature params and resolve any expression string. */
455
+ function resolveParams(value, vars, where) {
456
+ if (typeof value === 'string') {
457
+ // A string is an expression only when it is plain arithmetic AND every
458
+ // identifier in it is a declared var. Selectors ("Z", "aligned", "+") and
459
+ // enums therefore pass through untouched.
460
+ const text = value.trim()
461
+ if (!text || !/^[\w.\s+\-*/()]+$/.test(text)) return value
462
+ const ids = text.match(/[A-Za-z_]\w*/g) || []
463
+ const known = ids.filter((id) => Number.isFinite(vars?.[id]))
464
+ if (ids.length && !known.length) return value
465
+ if (!ids.length && !/[+\-*/]/.test(text)) return /^\d+(\.\d+)?$/.test(text) ? Number(text) : value
466
+ try { return evalExpression(text, vars) } catch (error) {
467
+ throw new Error(`${where}:${error.message}`)
468
+ }
469
+ }
470
+ if (Array.isArray(value)) return value.map((v) => resolveParams(v, vars, where))
471
+ if (value && typeof value === 'object') {
472
+ const out = {}
473
+ for (const [k, v] of Object.entries(value)) {
474
+ out[k] = EXPR_SKIP_KEYS.has(k) ? v : resolveParams(v, vars, where)
475
+ }
476
+ return out
477
+ }
478
+ return value
479
+ }
480
+
286
481
  /** Base placements + joints + explode → a scene payload ready to publish. */
287
482
  function assembleScene(record) {
288
483
  const explode = record.explode ?? 0
@@ -292,7 +487,7 @@ function assembleScene(record) {
292
487
  for (const joint of record.joints) {
293
488
  if (joint.instance !== base.name) continue
294
489
  const axis = normVec(joint.axis)
295
- if (joint.type === 'linear') {
490
+ if (joint.type === 'linear' || joint.type === 'planar') {
296
491
  translate = addVec(translate, scaleVec(axis, joint.value))
297
492
  } else {
298
493
  const R = axisAngle(axis, joint.value)
@@ -364,6 +559,13 @@ class FreeCadBridge {
364
559
 
365
560
  refresh() {
366
561
  this.bin = probeBinary(this.getConfig().freecadPath)
562
+ // Version costs a spawn, so ask once per binary rather than every poll
563
+ // (the panel polls /state every 1.5 s).
564
+ if (this.bin && this.versionOf !== this.bin) {
565
+ this.versionOf = this.bin
566
+ try { this.kernelVersion = freecadVersion(this.bin) } catch { this.kernelVersion = '' }
567
+ }
568
+ if (!this.bin) { this.kernelVersion = ''; this.versionOf = '' }
367
569
  return this.bin
368
570
  }
369
571
 
@@ -420,7 +622,7 @@ class FreeCadBridge {
420
622
  const latest = this.latest
421
623
  if (latest) await writeFile(join(dir, 'scenes', `${latest.id}.json`), JSON.stringify(latest.scene), 'utf8')
422
624
  const pointer = {
423
- runtime: this.status(),
625
+ runtime: { ...this.status(), version: this.kernelVersion || '' },
424
626
  latest: latest ? { id: latest.id, title: latest.title, at: latest.at } : null,
425
627
  // Newest first, trimmed: the panel's model switcher reads this list.
426
628
  history: this.history.slice(0, 30),
@@ -855,10 +1057,58 @@ def describe(path):
855
1057
  * `kind:'features'` model document — so a typed list and an edited-and-rebuilt
856
1058
  * one cannot drift apart.
857
1059
  */
858
- const featuresScript = (ops, exportPath) => `${PRELUDE}
1060
+ /**
1061
+ * Bump whenever the emitter's meaning changes: the BREP cache is keyed by
1062
+ * (version, op-chain), so a stale entry from an older emitter would silently
1063
+ * resurrect wrong geometry.
1064
+ */
1065
+ const EMITTER_VERSION = 'e1'
1066
+
1067
+ /** One hash per prefix: hashes[i] = ops[0..i] applied. Skip markers reuse the
1068
+ * previous hash, so toggling a suppressed feature does not invalidate
1069
+ * anything upstream of it. */
1070
+ function chainHashes(ops) {
1071
+ const out = []
1072
+ let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).digest('hex').slice(0, 16)
1073
+ for (const op of Array.isArray(ops) ? ops : []) {
1074
+ if (op && op.kind === '__skip__') { out.push(h); continue }
1075
+ const bare = { ...op }
1076
+ delete bare._id
1077
+ delete bare._label
1078
+ h = crypto.createHash('sha1').update(h).update(JSON.stringify(bare)).digest('hex').slice(0, 16)
1079
+ out.push(h)
1080
+ }
1081
+ return out
1082
+ }
1083
+
1084
+ function brepCacheDir() { return join(FreeCadBridge.dataDir, 'cache') }
1085
+
1086
+ /** Content-addressed BREP snapshots are cheap to keep and cheap to prune:
1087
+ * drop them oldest-first once the directory grows past a cap. */
1088
+ function pruneBrepCache(dir, { maxFiles = 400, maxAgeDays = 14 } = {}) {
1089
+ let names = []
1090
+ try { names = readdirSync(dir).filter((n) => /^f_[0-9a-f]{16}\.brep$/.test(n)) } catch { return 0 }
1091
+ const now = Date.now()
1092
+ const kept = []
1093
+ for (const n of names) {
1094
+ try {
1095
+ const st = statSync(join(dir, n))
1096
+ if (now - st.mtimeMs > maxAgeDays * 86400_000) rmSync(join(dir, n), { force: true })
1097
+ else kept.push({ n, at: st.mtimeMs })
1098
+ } catch {}
1099
+ }
1100
+ kept.sort((a, b) => b.at - a.at)
1101
+ let dropped = 0
1102
+ for (const { n } of kept.slice(maxFiles)) { try { rmSync(join(dir, n), { force: true }); dropped += 1 } catch {} }
1103
+ return dropped
1104
+ }
1105
+
1106
+ const featuresScript = (ops, exportPath, opts = {}) => `${PRELUDE}
859
1107
  import os
860
1108
  _OPS = json.loads(${JSON.stringify(JSON.stringify(Array.isArray(ops) ? ops : []))})
861
1109
  _EXPORT = ${exportPath ? JSON.stringify(exportPath) : 'None'}
1110
+ _CACHE = json.loads(${JSON.stringify(JSON.stringify(opts.cache && opts.cache.hashes ? { dir: opts.cache.dir, hashes: opts.cache.hashes } : null))})
1111
+ _RESUME = json.loads(${JSON.stringify(JSON.stringify(opts.resume && opts.resume.brep ? { index: opts.resume.index, brep: opts.resume.brep } : null))})
862
1112
 
863
1113
  def _v3(x, d=(0.0, 0.0, 0.0)):
864
1114
  if not x:
@@ -869,9 +1119,28 @@ def _dir(x, d=(0.0, 0.0, 1.0)):
869
1119
  v = _v3(x, d)
870
1120
  return v if v.Length > 1e-9 else _v3(d, (0.0, 0.0, 1.0))
871
1121
 
872
- def _prim(op):
1122
+ def _anchor(_spec, _cur):
1123
+ # A feature can hang off a face instead of absolute coordinates:
1124
+ # "at": {"ref": {"axis":"Z","mode":"aligned","dir":"+","type":"plane"},
1125
+ # "offset": [10, 0, 0]}
1126
+ # The point is the face's centre plus the offset in world axes, so changing
1127
+ # the thickness upstream moves the hole with the face instead of leaving it
1128
+ # floating at the old Z.
1129
+ if not isinstance(_spec, dict) or "ref" not in _spec:
1130
+ return None
1131
+ if _cur is None:
1132
+ raise RuntimeError("at.ref 需要前面至少有一个已建好的实体")
1133
+ _hits = _sel(_cur, "face", _spec.get("ref") or {})
1134
+ if not _hits:
1135
+ raise RuntimeError("at.ref 没有选中任何面:%s" % json.dumps(_spec.get("ref"), ensure_ascii=False))
1136
+ _off = _spec.get("offset")
1137
+ return _center_of(_hits[0]) + (_v3(_off) if _off else Vector(0.0, 0.0, 0.0))
1138
+
1139
+ def _prim(op, _cur=None):
873
1140
  k = op.get("kind")
874
- at = _v3(op.get("at"))
1141
+ _at_spec = op.get("at")
1142
+ _anchored = _anchor(_at_spec, _cur) if isinstance(_at_spec, dict) else None
1143
+ at = _anchored if _anchored is not None else _v3(_at_spec)
875
1144
  if k == "box":
876
1145
  s = op.get("size") or [10, 10, 10]
877
1146
  return Part.makeBox(float(s[0]), float(s[1]), float(s[2]), at)
@@ -936,6 +1205,20 @@ def _match_dir(_d, _ax, _mode, _sign):
936
1205
  return _c > 0.999 if _sign != "-" else _c < -0.999
937
1206
 
938
1207
 
1208
+ def _core_of(s):
1209
+ # A shape read back from a BREP cache is a Compound, and Compound has no
1210
+ # CenterOfMass (only Solid does) — use the lone solid when there is one and
1211
+ # the bounding box otherwise. It only has to be a point *inside* the body.
1212
+ try:
1213
+ if len(s.Solids) == 1:
1214
+ return s.Solids[0].CenterOfMass
1215
+ except Exception:
1216
+ pass
1217
+ try:
1218
+ return s.BoundBox.Center
1219
+ except Exception:
1220
+ return Vector(0.0, 0.0, 0.0)
1221
+
939
1222
  def _center_of(_it):
940
1223
  _b = _it.BoundBox
941
1224
  return Vector((_b.XMin + _b.XMax) / 2.0, (_b.YMin + _b.YMax) / 2.0, (_b.ZMin + _b.ZMax) / 2.0)
@@ -1002,14 +1285,31 @@ def _sel(_shape, _kind, _spec):
1002
1285
  _shape = None
1003
1286
  _errors = []
1004
1287
  _executed = 0
1288
+ _start = 0
1289
+ # Incremental recompute: resume from the deepest cached prefix instead of
1290
+ # replaying the whole chain. The cache is content-addressed by the op chain,
1291
+ # so an entry is only used when every upstream feature is byte-identical.
1292
+ if _RESUME and os.path.exists(_RESUME["brep"]):
1293
+ try:
1294
+ _cached = Part.Shape()
1295
+ _cached.read(_RESUME["brep"])
1296
+ if _cached.isValid() and not _cached.isNull():
1297
+ _shape = _cached
1298
+ _start = int(_RESUME["index"])
1299
+ _executed = _start
1300
+ except Exception as _e:
1301
+ _shape = None
1302
+ _start = 0
1005
1303
  for _idx, _op in enumerate(_OPS):
1304
+ if _idx < _start:
1305
+ continue
1006
1306
  _k = _op.get("kind")
1007
1307
  if _k == "__skip__":
1008
1308
  continue
1009
1309
  _snap = _shape
1010
1310
  try:
1011
1311
  if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
1012
- _s = _prim(_op)
1312
+ _s = _prim(_op, _shape)
1013
1313
  _shape = _s if _shape is None else _shape.fuse(_s)
1014
1314
  elif _k in ("fuse", "cut", "common"):
1015
1315
  # A U-shaped wall is one feature, not two: with takes a list, and
@@ -1018,7 +1318,7 @@ for _idx, _op in enumerate(_OPS):
1018
1318
  if not isinstance(_ws, (list, tuple)):
1019
1319
  _ws = [_ws]
1020
1320
  for _w in _ws:
1021
- _s = _prim(_w)
1321
+ _s = _prim(_w, _shape)
1022
1322
  _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
1023
1323
  elif _k == "fillet":
1024
1324
  _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
@@ -1047,7 +1347,7 @@ for _idx, _op in enumerate(_OPS):
1047
1347
  # stored orientation can point inward; cutting inward would
1048
1348
  # remove nothing (the interior is already hollow), and
1049
1349
  # cutting both ways would punch a hole clean through.
1050
- _away = _center_of(_f) - _shape.CenterOfMass
1350
+ _away = _center_of(_f) - _core_of(_shape)
1051
1351
  if _dot(_nrm, _away) < 0:
1052
1352
  _nrm = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
1053
1353
  # Cut the wall itself: start a hair outside the plane and go
@@ -1106,6 +1406,15 @@ for _idx, _op in enumerate(_OPS):
1106
1406
  })
1107
1407
  break
1108
1408
  _executed = _idx + 1
1409
+ if _CACHE and _idx < len(_CACHE.get("hashes") or []):
1410
+ try:
1411
+ _p = os.path.join(_CACHE["dir"], "f_%s.brep" % _CACHE["hashes"][_idx])
1412
+ if not os.path.exists(_p):
1413
+ _tmp = "%s.tmp%d" % (_p, os.getpid())
1414
+ _shape.exportBrep(_tmp)
1415
+ os.replace(_tmp, _p)
1416
+ except Exception:
1417
+ pass
1109
1418
 
1110
1419
  if _shape is None:
1111
1420
  raise RuntimeError(_errors[0]["message"] if _errors else "ops 为空:至少给一个图元")
@@ -1114,6 +1423,8 @@ scene = _shape
1114
1423
  __out = {
1115
1424
  "ok": True,
1116
1425
  "features": len(_OPS),
1426
+ "cached": _start,
1427
+ "computed": max(0, _executed - _start),
1117
1428
  "volume": round(_shape.Volume, 3),
1118
1429
  "area": round(_shape.Area, 3),
1119
1430
  "faces": len(_shape.Faces),
@@ -1375,6 +1686,26 @@ __out = {
1375
1686
  },
1376
1687
  })
1377
1688
 
1689
+ tool({
1690
+ name: 'cad_studio_doctor',
1691
+ description: 'Environment self-check for CAD Studio: reports every prerequisite (FreeCAD/OCCT kernel, data directory, disk space, model directory) with what is wrong, what to do about it, and which capabilities are currently available. Run this before blaming a modelling failure on the model.',
1692
+ parameters: {
1693
+ type: 'object',
1694
+ properties: {},
1695
+ additionalProperties: false,
1696
+ },
1697
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: renderDoctor(value) }] },
1698
+ execute: async () => {
1699
+ const diag = diagnose(bridge, bridge.getConfig())
1700
+ return {
1701
+ ready: diag.ready,
1702
+ kernel: diag.kernel.available ? [diag.kernel.binary, diag.kernel.version].filter(Boolean).join(' · ') : '',
1703
+ checks: diag.checks.map((c) => `${c.ok ? 'ok' : (c.required ? 'FAIL' : 'warn')} ${c.label}: ${c.detail}${c.fix ? ` — ${c.fix}` : ''}`),
1704
+ capabilities: diag.capabilities,
1705
+ }
1706
+ },
1707
+ })
1708
+
1378
1709
  tool({
1379
1710
  name: 'cad_studio_setup',
1380
1711
  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.',
@@ -1808,13 +2139,13 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
1808
2139
  assembly: { type: 'string', description: 'Assembly label for cad_studio_joint / cad_studio_drive / cad_studio_explode (defaults to the title).' },
1809
2140
  joints: {
1810
2141
  type: 'array',
1811
- description: 'Joints to declare up front: [{id?, instance, type:"revolute"|"linear", axis?, origin?, value?, min?, max?}]. Rotating about the instance centre is the default; pass origin for a hinge.',
2142
+ description: 'Joints to declare up front: [{id?, instance, type:"revolute"|"linear"|"cylindrical"|"planar"|"ball", axis?, origin?, value?, min?, max?}]. Rotating about the instance centre is the default; pass origin for a hinge.',
1812
2143
  items: {
1813
2144
  type: 'object',
1814
2145
  properties: {
1815
2146
  id: { type: 'string' },
1816
2147
  instance: { type: 'string' },
1817
- type: { type: 'string', enum: ['revolute', 'linear'] },
2148
+ type: { type: 'string', enum: ['revolute', 'linear', 'cylindrical', 'planar', 'ball'] },
1818
2149
  axis: { type: 'array', items: { type: 'number' } },
1819
2150
  origin: { type: 'array', items: { type: 'number' } },
1820
2151
  value: { type: 'number' },
@@ -1986,7 +2317,7 @@ if _TARGET:
1986
2317
  assembly: { type: 'string', description: 'Assembly id (asm-1) or its label. Default: newest.' },
1987
2318
  joint: { type: 'string', description: 'Joint id for remove.' },
1988
2319
  instance: { type: 'string', description: 'Instance name the joint moves (set).' },
1989
- type: { type: 'string', enum: ['revolute', 'linear'], description: 'Default: revolute.' },
2320
+ type: { type: 'string', enum: ['revolute', 'linear', 'cylindrical', 'planar', 'ball'], description: 'Default: revolute. cylindrical rotates and holds a fixed slide; planar/ball drive one number too (documented limitation).' },
1990
2321
  axis: { type: 'array', items: { type: 'number' }, description: 'Rotation/slide axis in world space. Default [0,0,1] revolute / [1,0,0] linear.' },
1991
2322
  origin: { type: 'array', items: { type: 'number' }, description: 'Point the rotation axis passes through. Default: the instance centre.' },
1992
2323
  value: { type: 'number', description: 'Current value in degrees (revolute) or mm (linear).' },
@@ -2149,10 +2480,20 @@ if _TARGET:
2149
2480
  // name so every caller keeps working. Reading an old file migrates it.
2150
2481
  if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
2151
2482
  doc.schema = 2
2483
+ // Named dimensions/expressions (schema 2): only finite numbers survive.
2484
+ doc.vars = doc.vars && typeof doc.vars === 'object' && !Array.isArray(doc.vars)
2485
+ ? Object.fromEntries(Object.entries(doc.vars).filter(([, v]) => Number.isFinite(v)))
2486
+ : {}
2152
2487
  doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
2153
2488
  doc.undo = Array.isArray(doc.undo) ? doc.undo : []
2154
2489
  doc.redo = Array.isArray(doc.redo) ? doc.redo : []
2155
- for (const f of doc.features) if (f && typeof f === 'object' && typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
2490
+ for (const f of doc.features) {
2491
+ if (!f || typeof f !== 'object') continue
2492
+ if (typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
2493
+ // Older docs picked up a stray params.suppressed from a normalizer bug;
2494
+ // it changed the op hash for no geometric reason, so drop it on read.
2495
+ if (f.params && typeof f.params === 'object' && 'suppressed' in f.params) delete f.params.suppressed
2496
+ }
2156
2497
  return doc
2157
2498
  }
2158
2499
 
@@ -2206,12 +2547,13 @@ if _TARGET:
2206
2547
  if (stopAtSuppressed) ops.push({ kind: '__skip__', _id: f.id, _label: f.label || '' })
2207
2548
  continue
2208
2549
  }
2209
- ops.push({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' })
2550
+ const where = `特征 ${f.id}${f.label ? `(${f.label})` : ''} ${f.kind}`
2551
+ ops.push({ kind: f.kind, ...resolveParams(f.params ?? {}, doc.vars, where), _id: f.id, _label: f.label || '' })
2210
2552
  }
2211
2553
  return ops
2212
2554
  }
2213
2555
 
2214
- const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
2556
+ const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled', 'suppressed']
2215
2557
 
2216
2558
  /**
2217
2559
  * Accept both shapes: `{kind:'box', params:{size:…}}` and the flatter
@@ -2242,31 +2584,39 @@ if _TARGET:
2242
2584
  if (!cond) throw new Error(`${where}:${hint}`)
2243
2585
  }
2244
2586
  const tool = (v) => v && typeof v === 'object' && ['box', 'cylinder', 'sphere', 'cone', 'torus', 'extrude', 'revolve'].includes(String(v.kind))
2245
- const withs = params.with
2246
- if (kind === 'box') need(triple(params.size) && params.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
2247
- else if (kind === 'cylinder') need(pos(params.r) && pos(params.h), '需要 r>0 与 h>0')
2248
- else if (kind === 'sphere') need(pos(params.r), '需要 r>0')
2249
- else if (kind === 'cone') need(num(params.r1) && num(params.r2) && pos(params.h), '需要 r1 / r2 / h>0')
2250
- else if (kind === 'torus') need(pos(params.r1) && pos(params.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
2587
+ // Expressions are legal in the document, numbers at validation time.
2588
+ let probe = params
2589
+ try { probe = resolveParams(params, doc.vars, where) } catch (error) { throw new Error(`${where}:${error.message}`) }
2590
+ // `at` is either a point or an anchor on a face ({ref, offset}).
2591
+ if (probe.at && typeof params.at === 'object' && !Array.isArray(probe.at)) {
2592
+ need(probe.at.ref && typeof params.at.ref === 'object', 'at.ref 需要一个面选择器(如 {axis:"Z",mode:"aligned",dir:"+",type:"plane"})')
2593
+ need(probe.at.offset === undefined || triple(probe.at.offset), 'at.offset 需要 [x,y,z]')
2594
+ }
2595
+ const withs = probe.with
2596
+ if (kind === 'box') need(triple(probe.size) && probe.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
2597
+ else if (kind === 'cylinder') need(pos(probe.r) && pos(probe.h), '需要 r>0 与 h>0')
2598
+ else if (kind === 'sphere') need(pos(probe.r), '需要 r>0')
2599
+ else if (kind === 'cone') need(num(probe.r1) && num(probe.r2) && pos(probe.h), '需要 r1 / r2 / h>0')
2600
+ else if (kind === 'torus') need(pos(probe.r1) && pos(probe.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
2251
2601
  else if (kind === 'extrude') {
2252
- const points = Array.isArray(params.points) ? params.points : []
2602
+ const points = Array.isArray(probe.points) ? probe.points : []
2253
2603
  need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
2254
2604
  need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
2255
- need(pos(params.h) || triple(params.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
2605
+ need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
2256
2606
  } else if (kind === 'revolve') {
2257
- const points = Array.isArray(params.points) ? params.points : []
2607
+ const points = Array.isArray(probe.points) ? probe.points : []
2258
2608
  need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
2259
2609
  } else if (kind === 'fuse' || kind === 'cut' || kind === 'common') {
2260
2610
  const list = Array.isArray(withs) ? withs : withs ? [withs] : []
2261
2611
  need(list.length > 0, `需要 with 子图元({kind:"box",size:[…]},或用数组一次减/并多个)`)
2262
2612
  need(list.every(tool), 'with 里的每一项都要是图元(box/cylinder/sphere/cone/torus/extrude/revolve),且带 kind')
2263
- } else if (kind === 'fillet') need(pos(params.r), '需要 r>0')
2264
- else if (kind === 'chamfer') need(pos(params.d), '需要 d>0')
2265
- else if (kind === 'shell') need(pos(params.t), '需要 t>0(壁厚)')
2266
- else if (kind === 'pattern_linear') need(triple(params.delta) && num(params.count) && params.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
2267
- else if (kind === 'pattern_circular') need(num(params.count) && params.count >= 2, '需要 count>=2')
2268
- else if (kind === 'translate') need(triple(params.v), '需要 v:[dx,dy,dz]')
2269
- else if (kind === 'rotate') need(num(params.deg), '需要 deg(角度)')
2613
+ } else if (kind === 'fillet') need(pos(probe.r), '需要 r>0')
2614
+ else if (kind === 'chamfer') need(pos(probe.d), '需要 d>0')
2615
+ else if (kind === 'shell') need(pos(probe.t), '需要 t>0(壁厚)')
2616
+ else if (kind === 'pattern_linear') need(triple(probe.delta) && num(probe.count) && probe.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
2617
+ else if (kind === 'pattern_circular') need(num(probe.count) && probe.count >= 2, '需要 count>=2')
2618
+ else if (kind === 'translate') need(triple(probe.v), '需要 v:[dx,dy,dz]')
2619
+ else if (kind === 'rotate') need(num(probe.deg), '需要 deg(角度)')
2270
2620
  return {
2271
2621
  id,
2272
2622
  kind,
@@ -2285,6 +2635,15 @@ if _TARGET:
2285
2635
  * Per-node status for the panel and for the caller: ok / failed / blocked /
2286
2636
  * skipped. Derived from what the kernel actually executed, not guessed.
2287
2637
  */
2638
+ // True when this step hangs off a face (`at.ref`) instead of absolute XYZ.
2639
+ const anchoredOn = (params) => {
2640
+ if (!params || typeof params !== 'object') return false
2641
+ const has = (v) => Boolean(v && typeof v === 'object' && v.ref)
2642
+ if (has(params.at)) return true
2643
+ const w = params.with
2644
+ return Array.isArray(w) ? w.some((x) => has(x?.at)) : has(w?.at)
2645
+ }
2646
+
2288
2647
  const graphView = (doc, out) => {
2289
2648
  const list = Array.isArray(doc.features) ? doc.features : []
2290
2649
  const errors = Array.isArray(out?.errors) ? out.errors : []
@@ -2305,13 +2664,54 @@ if _TARGET:
2305
2664
  if (executed !== null && i >= executed) { why = `因为 ${f.id} 没有执行`; return { ...base, status: 'blocked', message: why } }
2306
2665
  return { ...base, status: 'ok', message: '' }
2307
2666
  })
2308
- return { tip: doc.tip ?? null, nodes }
2667
+ // Dependencies are a chain, not a secret: features are evaluated in order
2668
+ // and each one consumes the shape the previous one produced. Saying so
2669
+ // out loud is what lets the panel answer "what breaks if I change this?"
2670
+ // without inventing a graph we do not have.
2671
+ const withDeps = nodes.map((n, i) => ({
2672
+ ...n,
2673
+ dependsOn: i > 0 ? [String(nodes[i - 1].id)] : [],
2674
+ dependents: i + 1 < nodes.length ? [String(nodes[i + 1].id)] : [],
2675
+ // An anchored primitive (`at.ref`) also follows the face it names, which
2676
+ // is the only non-sequential edge we support today.
2677
+ anchored: anchoredOn(list[i]?.params),
2678
+ }))
2679
+ return { tip: doc.tip ?? null, nodes: withDeps }
2309
2680
  }
2310
2681
 
2311
2682
  const rebuild = async (doc, dir, { note } = {}) => {
2312
2683
  const isFeatures = doc.kind === 'features'
2684
+ // Incremental recompute (DESIGN §5.3): hash the op chain once, find the
2685
+ // deepest BREP prefix already on disk, and let the kernel start there.
2686
+ // A rebuild of an unchanged document skips the kernel entirely.
2687
+ let cache = null
2688
+ let resume = null
2689
+ let hashes = []
2690
+ if (isFeatures) {
2691
+ const ops = featureOps(doc)
2692
+ hashes = chainHashes(ops)
2693
+ const cacheDir = brepCacheDir()
2694
+ try { await mkdir(cacheDir, { recursive: true }) } catch {}
2695
+ cache = { dir: cacheDir, hashes }
2696
+ for (let k = hashes.length - 1; k >= 0; k -= 1) {
2697
+ const candidate = join(cacheDir, `f_${hashes[k]}.brep`)
2698
+ if (existsSync(candidate)) { resume = { index: k + 1, brep: candidate }; break }
2699
+ }
2700
+ const fullHash = hashes[hashes.length - 1] ?? ''
2701
+ const keep = doc.stats?.sceneId && bridge.scenes?.has(doc.stats.sceneId)
2702
+ if (fullHash && keep && doc.stats?.hash === fullHash) {
2703
+ // Nothing changed and the scene is still live: no kernel run at all.
2704
+ return {
2705
+ ok: true, evaluated: true, cached: hashes.length, computed: 0, name: doc.name, dir,
2706
+ graph: graphView(doc, { errors: [], executed: hashes.length }),
2707
+ errors: [], run: doc.run, params: doc.params, volume: doc.stats.volume,
2708
+ triangles: doc.stats.triangles, sceneId: doc.stats.sceneId, bounds: doc.stats.bounds,
2709
+ note: doc.note, revalidated: true,
2710
+ }
2711
+ }
2712
+ }
2313
2713
  const code = isFeatures
2314
- ? featuresScript(featureOps(doc))
2714
+ ? featuresScript(featureOps(doc), null, { cache, resume })
2315
2715
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
2316
2716
  const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
2317
2717
  doc.run = (doc.run ?? 0) + 1
@@ -2334,6 +2734,8 @@ if _TARGET:
2334
2734
  bounds: out.bounds ?? null,
2335
2735
  sceneId,
2336
2736
  at: doc.updatedAt,
2737
+ hash: hashes[hashes.length - 1] ?? '',
2738
+ cached: out.cached ?? 0,
2337
2739
  }
2338
2740
  if (note) doc.note = note
2339
2741
  // The scene was published before the kernel reported which nodes failed, so
@@ -2342,15 +2744,23 @@ if _TARGET:
2342
2744
  const scene = sceneId ? bridge.scenes?.get(sceneId) : null
2343
2745
  if (scene) {
2344
2746
  scene.graph = graph
2747
+ scene.cache = { cached: out.cached ?? 0, computed: out.computed ?? null, of: hashes.length }
2345
2748
  try { await bridge.persist() } catch {}
2346
2749
  }
2347
2750
  await writeModel(doc, dir)
2751
+ if (isFeatures && hashes.length) {
2752
+ // Cheap housekeeping, off the hot path: a 400-file / 14-day cap keeps the
2753
+ // cache from growing without bound in a long-lived install.
2754
+ try { pruneBrepCache(brepCacheDir()) } catch {}
2755
+ }
2348
2756
  return {
2349
2757
  ok: true,
2350
2758
  evaluated: !(Array.isArray(out.errors) && out.errors.length > 0),
2351
2759
  name: doc.name,
2352
2760
  dir,
2353
2761
  graph,
2762
+ cached: out.cached ?? 0,
2763
+ computed: out.computed ?? null,
2354
2764
  errors: Array.isArray(out.errors) ? out.errors : [],
2355
2765
  run: doc.run,
2356
2766
  params: doc.params,
@@ -2530,6 +2940,10 @@ if _TARGET:
2530
2940
  triangles: doc.stats?.triangles ?? null,
2531
2941
  sceneId: doc.stats?.sceneId ?? '',
2532
2942
  run: doc.run,
2943
+ // How much of the chain came from the BREP cache vs the kernel this time.
2944
+ cached: result.cached ?? doc.stats?.cached ?? 0,
2945
+ computed: result.computed ?? null,
2946
+ revalidated: result.revalidated === true,
2533
2947
  }
2534
2948
  }
2535
2949
 
@@ -2612,7 +3026,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2612
3026
  kind: doc.kind,
2613
3027
  params: doc.params,
2614
3028
  ...(typeof doc.script === 'string' ? { script: doc.script } : {}),
2615
- ...(doc.kind === 'features' ? { features: publicFeatures(doc) } : {}),
3029
+ ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {} } : {}),
2616
3030
  runs: doc.run ?? 0,
2617
3031
  updatedAt: doc.updatedAt ?? '',
2618
3032
  stats: doc.stats ?? null,
@@ -2637,6 +3051,9 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2637
3051
  name: key,
2638
3052
  kind: 'features',
2639
3053
  features: [],
3054
+ // Vars must exist before the first feature is validated: dimensions
3055
+ // are allowed to be expressions over them.
3056
+ vars: normalizeVars(args.vars),
2640
3057
  params: args.params && typeof args.params === 'object' ? args.params : {},
2641
3058
  run: 0,
2642
3059
  createdAt: new Date().toISOString(),
@@ -2670,6 +3087,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2670
3087
 
2671
3088
  if (action === 'update') {
2672
3089
  const doc = await readModel(args.name, dir)
3090
+ if (args.vars !== undefined) doc.vars = normalizeVars(args.vars, doc.vars)
2673
3091
  const before = {
2674
3092
  script: doc.script,
2675
3093
  params: JSON.parse(JSON.stringify(doc.params)),
@@ -2753,10 +3171,14 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2753
3171
  try {
2754
3172
  const parsed = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
2755
3173
  const setup = setupStatus(bridge, { withVersion: false })
2756
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: parsed.latest ?? null, lastSession: parsed.lastSession ?? '', assemblies: parsed.assemblies ?? [], running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
3174
+ const diag = diagnose(bridge, resolved)
3175
+ diag.checks = diag.checks.map((c) => (c.id === 'kernel' ? { ...c, detail: runtime.available ? [runtime.binary, runtime.version].filter(Boolean).join(' · ') : c.detail } : c))
3176
+ return send(200, JSON.stringify({ runtime, setup, diag, config: { autoOpen: resolved.autoOpen }, latest: parsed.latest ?? null, lastSession: parsed.lastSession ?? '', assemblies: parsed.assemblies ?? [], running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
2757
3177
  } catch {
2758
3178
  const setup = setupStatus(bridge, { withVersion: false })
2759
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
3179
+ const diag = diagnose(bridge, resolved)
3180
+ diag.checks = diag.checks.map((c) => (c.id === 'kernel' ? { ...c, detail: runtime.available ? [runtime.binary, runtime.version].filter(Boolean).join(' · ') : c.detail } : c))
3181
+ return send(200, JSON.stringify({ runtime, setup, diag, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
2760
3182
  }
2761
3183
  }
2762
3184
  if (url.pathname === `${ROUTE_PREFIX}/scenes`) {
@@ -2781,6 +3203,10 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2781
3203
  try { return JSON.parse(raw) } catch { return null }
2782
3204
  }
2783
3205
 
3206
+ if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
3207
+ bridge.refresh()
3208
+ return send(200, JSON.stringify(diagnose(bridge, resolved)))
3209
+ }
2784
3210
  if (url.pathname === `${ROUTE_PREFIX}/setup`) {
2785
3211
  // The panel's "install FreeCAD" button; same code path as the tool so
2786
3212
  // both report identical fields.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {