dsh-cad-studio 0.16.0 → 0.18.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 (3) hide show
  1. package/README.md +2 -0
  2. package/index.js +112 -13
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -23,6 +23,8 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
23
23
  | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
24
24
  | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
25
25
  | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
26
+ | 草图约束 | `equal`(等长)、`symmetric`(三点对称,需 `c` 点)、`angle`(**单位是度**,内部转弧度并在求解后重测);`distance` 是两点距离、`distance_x/y` 是该点的绝对坐标 |
27
+ | 草图 + 放样/扫掠 | 草图存在文档里(`cad_studio_doc {action:"create", kind:"features", sketches:{S1:{geometry:[…],constraints:[…]}}, features:[{kind:"extrude",sketch:"S1",h:10}]}`);`loft` 用 `sections:[{sketch:"S1"},{sketch:"S2",at:[0,0,40]}]`,`sweep` 用 `path:[[x,y,z],…]`。改草图会重建(草图进了缓存哈希,不会命中旧 BREP) |
26
28
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
27
29
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
28
30
  | 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
package/index.js CHANGED
@@ -1163,9 +1163,12 @@ const EMITTER_VERSION = 'e1'
1163
1163
  /** One hash per prefix: hashes[i] = ops[0..i] applied. Skip markers reuse the
1164
1164
  * previous hash, so toggling a suppressed feature does not invalidate
1165
1165
  * anything upstream of it. */
1166
- function chainHashes(ops) {
1166
+ function chainHashes(ops, seed = '') {
1167
1167
  const out = []
1168
- let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).digest('hex').slice(0, 16)
1168
+ // `seed` carries everything the op list does not spell out — currently the
1169
+ // document's sketches. Without it, editing a sketch leaves the chain hash
1170
+ // unchanged and the BREP cache happily serves the old geometry.
1171
+ let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).update(String(seed)).digest('hex').slice(0, 16)
1169
1172
  for (const op of Array.isArray(ops) ? ops : []) {
1170
1173
  if (op && op.kind === '__skip__') { out.push(h); continue }
1171
1174
  const bare = { ...op }
@@ -1245,6 +1248,7 @@ _SK_CONSTRAINT = {
1245
1248
  "tangent": ("Tangent", "pair"), "distance_x": ("DistanceX", "size"),
1246
1249
  "distance_y": ("DistanceY", "size"), "radius": ("Radius", "size_one"),
1247
1250
  "angle": ("Angle", "size_pair"), "distance": ("Distance", "ab2v"),
1251
+ "equal": ("Equal", "pair"), "symmetric": ("Symmetric", "sym3"),
1248
1252
  }
1249
1253
 
1250
1254
  def _sketch(name):
@@ -1294,8 +1298,13 @@ def _sketch(name):
1294
1298
  elif form == "ab2v":
1295
1299
  sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 2)), float(v)))
1296
1300
  dims.append((c, fc, (gi(c["a"]), int(c.get("pa", 1))), (gi(c["b"]), int(c.get("pb", 2))), float(v)))
1301
+ elif form == "sym3":
1302
+ sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 1)), gi(c.get("c")), int(c.get("pc", 1))))
1297
1303
  else:
1298
- sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"]), float(v)))
1304
+ # Angle is documented in degrees because that is what a human types;
1305
+ # the solver wants radians.
1306
+ _sent = math.radians(float(v)) if fc == "Angle" else float(v)
1307
+ sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"]), _sent))
1299
1308
  dims.append((c, fc, (gi(c["a"]), None), (gi(c["b"]), None), float(v)))
1300
1309
  rc = sk.solve()
1301
1310
  if rc < 0:
@@ -1312,6 +1321,16 @@ def _sketch(name):
1312
1321
  elif fc in ("DistanceX", "DistanceY"):
1313
1322
  p = _pt(ref1)
1314
1323
  got = p.x if fc == "DistanceX" else p.y
1324
+ elif fc == "Equal":
1325
+ got = 1.0 if abs(sk.Geometry[ref1[0]].length() - sk.Geometry[ref2[0]].length()) <= 1e-6 else 0.0
1326
+ want = 1.0
1327
+ elif fc == "Angle":
1328
+ _a = sk.Geometry[ref1[0]]
1329
+ _b = sk.Geometry[ref2[0]]
1330
+ _va = _a.EndPoint - _a.StartPoint
1331
+ _vb = _b.EndPoint - _b.StartPoint
1332
+ _cos = max(-1.0, min(1.0, _va.dot(_vb) / (_va.Length * _vb.Length)))
1333
+ got = math.degrees(math.acos(_cos))
1315
1334
  else:
1316
1335
  continue
1317
1336
  if abs(got - want) > 1e-6:
@@ -1397,6 +1416,40 @@ def _prim(op, _cur=None):
1397
1416
  ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
1398
1417
  ang = float(op.get("angle", 360.0))
1399
1418
  return Part.Face(Part.makePolygon(ps + [ps[0]])).revolve(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), ang)
1419
+ if k == "loft":
1420
+ # Sections are sketches (or their wires) placed at different heights:
1421
+ # lofting two coplanar wires is degenerate on this kernel (Volume 0),
1422
+ # which is exactly what a mis-specified loft would look like.
1423
+ _sections = op.get("sections")
1424
+ if not isinstance(_sections, list) or len(_sections) < 2:
1425
+ raise RuntimeError("loft 需要至少两个 sections,例如 [{\\\"sketch\\\":\\\"S1\\\"},{\\\"sketch\\\":\\\"S2\\\",\\\"at\\\":[0,0,40]}]")
1426
+ _wires = []
1427
+ for _sec in _sections:
1428
+ _w = _sketch(str(_sec.get("sketch"))) if isinstance(_sec, dict) and _sec.get("sketch") else None
1429
+ if _w is None:
1430
+ raise RuntimeError("loft 的每个 section 都要有 sketch 名字")
1431
+ _at = _v3(_sec.get("at"), (0.0, 0.0, 0.0))
1432
+ if _at.Length > 1e-9:
1433
+ _w = _w.translated(_at)
1434
+ _wires.append(_w)
1435
+ _lofted = Part.makeLoft(_wires, True)
1436
+ if abs(_lofted.Volume) < 1e-9 and len(_wires) > 1:
1437
+ _z = [round(w.BoundBox.ZMin, 3) for w in _wires]
1438
+ raise RuntimeError("loft 得到零体积:所有截面在同一平面上(z=%s)。给 section 加 at:[0,0,z] 把它们分层" % str(_z))
1439
+ return _lofted
1440
+ if k == "sweep":
1441
+ _prof = _sketch(str(op["sketch"])) if op.get("sketch") else None
1442
+ if _prof is None:
1443
+ raise RuntimeError("sweep 需要 sketch(截面轮廓)")
1444
+ _pts = op.get("path")
1445
+ if not isinstance(_pts, list) or len(_pts) < 2:
1446
+ raise RuntimeError("sweep 需要 path:至少两个点 [[x,y,z], ...]")
1447
+ _path = Part.makePolygon([_v3(p) for p in _pts])
1448
+ _tr = int(op.get("transition", 2))
1449
+ _swept = Part.Wire(_path).makePipeShell([Part.Wire(_prof)], True, bool(op.get("frenet", False)), _tr)
1450
+ if abs(_swept.Volume) < 1e-9:
1451
+ raise RuntimeError("sweep 得到零体积:检查 path 是否退化(所有点共线)")
1452
+ return _swept
1400
1453
  raise RuntimeError("未知图元:" + str(k))
1401
1454
 
1402
1455
  # ---- sub-shape selectors -------------------------------------------------
@@ -1538,7 +1591,7 @@ for _idx, _op in enumerate(_OPS):
1538
1591
  continue
1539
1592
  _snap = _shape
1540
1593
  try:
1541
- if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
1594
+ if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve", "loft", "sweep"):
1542
1595
  _s = _prim(_op, _shape)
1543
1596
  _shape = _s if _shape is None else _shape.fuse(_s)
1544
1597
  elif _k in ("fuse", "cut", "common"):
@@ -2625,7 +2678,7 @@ else:
2625
2678
  // A list of ops applied in order. `run` stays the escape hatch; this is the
2626
2679
  // path for "60×40×20 的盒子挖个 φ16 通孔、倒 2mm 圆角".
2627
2680
 
2628
- const FEATURE_KINDS = ['box', 'cylinder', 'sphere', 'cone', 'torus', 'hole', 'extrude', 'revolve', 'fuse', 'cut', 'common', 'fillet', 'chamfer', 'shell', 'pattern_linear', 'pattern_circular', 'translate', 'rotate', 'mirror']
2681
+ const FEATURE_KINDS = ['box', 'cylinder', 'sphere', 'cone', 'torus', 'hole', 'extrude', 'revolve', 'loft', 'sweep', 'fuse', 'cut', 'common', 'fillet', 'chamfer', 'shell', 'pattern_linear', 'pattern_circular', 'translate', 'rotate', 'mirror']
2629
2682
 
2630
2683
  tool({
2631
2684
  name: 'cad_studio_feature',
@@ -3029,6 +3082,7 @@ if _TARGET:
3029
3082
  // Schema 2 keeps the list under `graph.nodes`; `features` stays the in-memory
3030
3083
  // name so every caller keeps working. Reading an old file migrates it.
3031
3084
  if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
3085
+ if (!doc.sketches || typeof doc.sketches !== 'object' || Array.isArray(doc.sketches)) doc.sketches = {}
3032
3086
  doc.schema = 2
3033
3087
  // Named dimensions/expressions (schema 2): only finite numbers survive.
3034
3088
  doc.vars = doc.vars && typeof doc.vars === 'object' && !Array.isArray(doc.vars)
@@ -3109,6 +3163,29 @@ if _TARGET:
3109
3163
  * Accept both shapes: `{kind:'box', params:{size:…}}` and the flatter
3110
3164
  * `{kind:'box', size:…}` an agent tends to write.
3111
3165
  */
3166
+ // Sketches live in the same document as the features, so one file is the
3167
+ // whole model: geometry + constraints in, wires out at rebuild time.
3168
+ const normalizeSketches = (raw, base = {}) => {
3169
+ const out = { ...(base && typeof base === 'object' ? base : {}) }
3170
+ if (raw === undefined) return out
3171
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('sketches 必须是 {名字: {geometry:[…], constraints:[…]}}')
3172
+ for (const [name, sk] of Object.entries(raw)) {
3173
+ if (sk === null) { delete out[name]; continue }
3174
+ if (!sk || typeof sk !== 'object') throw new Error(`sketch ${name} 必须是对象`)
3175
+ const geometry = Array.isArray(sk.geometry) ? sk.geometry : []
3176
+ const constraints = Array.isArray(sk.constraints) ? sk.constraints : []
3177
+ if (!geometry.length) throw new Error(`sketch ${name} 的 geometry 不能为空`)
3178
+ for (const g of geometry) {
3179
+ if (!g || typeof g.type !== 'string') throw new Error(`sketch ${name} 的 geometry 每项都要有 type(line/circle/arc)`)
3180
+ }
3181
+ for (const c of constraints) {
3182
+ if (!c || typeof c.type !== 'string') throw new Error(`sketch ${name} 的 constraints 每项都要有 type`)
3183
+ }
3184
+ out[name] = { geometry, constraints }
3185
+ }
3186
+ return out
3187
+ }
3188
+
3112
3189
  const normalizeFeature = (doc, raw) => {
3113
3190
  if (!raw || typeof raw !== 'object') throw new Error('feature 必须是对象(至少给 kind)')
3114
3191
  const kind = String(raw.kind ?? '')
@@ -3149,10 +3226,29 @@ if _TARGET:
3149
3226
  else if (kind === 'cone') need(num(probe.r1) && num(probe.r2) && pos(probe.h), '需要 r1 / r2 / h>0')
3150
3227
  else if (kind === 'torus') need(pos(probe.r1) && pos(probe.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
3151
3228
  else if (kind === 'extrude') {
3152
- const points = Array.isArray(probe.points) ? probe.points : []
3153
- need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
3154
- need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
3155
- need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
3229
+ // `return` here would return from normalizeFeature itself and push
3230
+ // `undefined` into doc.features (that cost me a crash on feature.id).
3231
+ const fromSketch = typeof probe.sketch === 'string' && probe.sketch
3232
+ if (fromSketch) {
3233
+ need(pos(probe.h) || triple(probe.dir), `${where} extrude:给 sketch 时仍需要 h>0 或 dir:[dx,dy,dz]`)
3234
+ } else {
3235
+ const points = Array.isArray(probe.points) ? probe.points : []
3236
+ need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点;或给 sketch:"S1" 用文档里的草图)')
3237
+ need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
3238
+ need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
3239
+ }
3240
+ } else if (kind === 'loft') {
3241
+ const sections = probe.sections
3242
+ need(Array.isArray(sections) && sections.length >= 2, `${where} loft:需要至少两个 sections,例如 [{sketch:"S1"},{sketch:"S2",at:[0,0,40]}]`)
3243
+ for (const sec of sections) {
3244
+ need(sec && typeof sec === 'object' && typeof sec.sketch === 'string' && sec.sketch, `${where} loft:每个 section 都要有 sketch 名字`)
3245
+ if (sec.at !== undefined) need(Array.isArray(sec.at) && sec.at.length === 3 && sec.at.every((v) => Number.isFinite(v)), `${where} loft:section.at 必须是 [x,y,z]`)
3246
+ }
3247
+ } else if (kind === 'sweep') {
3248
+ need(typeof probe.sketch === 'string' && probe.sketch, `${where} sweep:需要 sketch(截面轮廓)`)
3249
+ const path = probe.path
3250
+ need(Array.isArray(path) && path.length >= 2, `${where} sweep:需要 path,至少两个点 [[x,y,z], …]`)
3251
+ for (const pt of path) need(Array.isArray(pt) && pt.length === 3 && pt.every((v) => Number.isFinite(v)), `${where} sweep:path 的每一项都必须是 [x,y,z]`)
3156
3252
  } else if (kind === 'revolve') {
3157
3253
  const points = Array.isArray(probe.points) ? probe.points : []
3158
3254
  need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
@@ -3239,7 +3335,7 @@ if _TARGET:
3239
3335
  let hashes = []
3240
3336
  if (isFeatures) {
3241
3337
  const ops = featureOps(doc)
3242
- hashes = chainHashes(ops)
3338
+ hashes = chainHashes(ops, JSON.stringify(doc.sketches ?? {}))
3243
3339
  const cacheDir = brepCacheDir()
3244
3340
  try { await mkdir(cacheDir, { recursive: true }) } catch {}
3245
3341
  cache = { dir: cacheDir, hashes }
@@ -3261,7 +3357,7 @@ if _TARGET:
3261
3357
  }
3262
3358
  }
3263
3359
  const code = isFeatures
3264
- ? featuresScript(featureOps(doc), null, { cache, resume })
3360
+ ? featuresScript(featureOps(doc), null, { cache, resume, sketches: doc.sketches })
3265
3361
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
3266
3362
  const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
3267
3363
  doc.run = (doc.run ?? 0) + 1
@@ -3336,6 +3432,7 @@ if _TARGET:
3336
3432
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
3337
3433
  note: { type: 'string', description: 'What this revision changed (kept in history).' },
3338
3434
  to: { type: 'string', description: 'For action=rename / duplicate: the new model name.' },
3435
+ sketches: { type: 'object', description: 'For kind="features": named sketches stored in the document, e.g. {S1:{geometry:[{id:"g1",type:"line",p1:[0,0,0],p2:[80,0,0]}, …],constraints:[…]}}. A feature extrudes/revolves/lofts one with {kind:"extrude",sketch:"S1"}.' },
3339
3436
  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.' },
3340
3437
  },
3341
3438
  required: ['action'],
@@ -3562,7 +3659,7 @@ if _TARGET:
3562
3659
  if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
3563
3660
  await mkdir(dirname(target), { recursive: true })
3564
3661
  const head = doc.kind === 'features'
3565
- ? featuresScript(featureOps(doc), target)
3662
+ ? featuresScript(featureOps(doc), target, { sketches: doc.sketches })
3566
3663
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
3567
3664
  const code = doc.kind === 'features'
3568
3665
  ? head
@@ -3604,7 +3701,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3604
3701
  kind: doc.kind,
3605
3702
  params: doc.params,
3606
3703
  ...(typeof doc.script === 'string' ? { script: doc.script } : {}),
3607
- ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {} } : {}),
3704
+ ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {}, sketches: doc.sketches } : {}),
3608
3705
  runs: doc.run ?? 0,
3609
3706
  updatedAt: doc.updatedAt ?? '',
3610
3707
  stats: doc.stats ?? null,
@@ -3632,6 +3729,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3632
3729
  // Vars must exist before the first feature is validated: dimensions
3633
3730
  // are allowed to be expressions over them.
3634
3731
  vars: normalizeVars(args.vars),
3732
+ sketches: normalizeSketches(args.sketches),
3635
3733
  params: args.params && typeof args.params === 'object' ? args.params : {},
3636
3734
  run: 0,
3637
3735
  createdAt: new Date().toISOString(),
@@ -3668,6 +3766,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3668
3766
  if (action === 'update') {
3669
3767
  const doc = await readModel(args.name, dir)
3670
3768
  if (args.vars !== undefined) doc.vars = normalizeVars(args.vars, doc.vars)
3769
+ if (args.sketches !== undefined) doc.sketches = normalizeSketches(args.sketches, doc.sketches)
3671
3770
  const before = {
3672
3771
  script: doc.script,
3673
3772
  params: JSON.parse(JSON.stringify(doc.params)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {