dsh-cad-studio 0.13.0 → 0.15.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 +3 -0
  2. package/index.js +159 -10
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -19,6 +19,9 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴) |
20
20
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
21
21
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
22
+ | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
23
+ | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
24
+ | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
22
25
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
23
26
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
24
27
  | 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
package/index.js CHANGED
@@ -1212,6 +1212,10 @@ def _v3(x, d=(0.0, 0.0, 0.0)):
1212
1212
  return Vector(float(x[0]), float(x[1]), float(x[2]))
1213
1213
 
1214
1214
  def _dir(x, d=(0.0, 0.0, 1.0)):
1215
+ # "X"/"Y"/"Z" are accepted everywhere a direction is expected, not just
1216
+ # [x,y,z]: writing axis:'Y' is what a human means when revolving a sketch.
1217
+ if isinstance(x, str) and x.strip().upper() in ("X", "Y", "Z"):
1218
+ x = {"X": (1.0, 0.0, 0.0), "Y": (0.0, 1.0, 0.0), "Z": (0.0, 0.0, 1.0)}[x.strip().upper()]
1215
1219
  v = _v3(x, d)
1216
1220
  return v if v.Length > 1e-9 else _v3(d, (0.0, 0.0, 1.0))
1217
1221
 
@@ -1377,18 +1381,17 @@ def _prim(op, _cur=None):
1377
1381
  return body
1378
1382
  if k == "revolve":
1379
1383
  if op.get("sketch"):
1384
+ # Measured on 0.20.2: a face revolved about an axis that LIES IN its
1385
+ # plane gives a valid solid (ring: area x 2*pi*r_centroid); about an
1386
+ # axis PERPENDICULAR to its plane it gives a zero-thickness annulus
1387
+ # (Volume 0, isValid() still True). So the axis has to be explicit:
1388
+ # guessing it silently would produce 0 mm3 instead of an error.
1389
+ if op.get("axis") is None:
1390
+ raise RuntimeError("草图旋转要显式给 axis:草图平面内的轴(如 'Y' 或 [0,1,0])会扫出实体;垂直于草图平面的轴(XY 草图的 Z)扫出的是零厚度圆环")
1380
1391
  face = Part.Face(_sketch(str(op["sketch"])))
1381
1392
  rev = face.revolve(_v3(op.get("origin")), _dir(op.get("axis"), (0.0, 0.0, 1.0)), float(op.get("angle", 360.0)))
1382
- # A revolve of a face yields a shell; a full turn closes it, but only
1383
- # becomes a solid after we say so. Volume 0 means "still a shell".
1384
- if abs(rev.Volume) < 1e-9 and rev.Shells:
1385
- try:
1386
- rev = Part.makeSolid(rev.Shells[0])
1387
- except Exception:
1388
- pass
1389
1393
  if abs(rev.Volume) < 1e-9:
1390
- # Do not hand a zero-volume shell downstream: say it out loud.
1391
- raise RuntimeError("草图旋转得到的是壳体、没有闭合(需要 sewShape 缝合);先用挤出,或把草图轮廓贴住旋转轴")
1394
+ raise RuntimeError("草图旋转得到零体积:旋转轴垂直于草图平面(XY 草图 + Z 轴只会扫出零厚度圆环)。把 axis 换成草图平面内的轴,例如 axis:'Y'")
1392
1395
  return rev
1393
1396
  ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
1394
1397
  ang = float(op.get("angle", 360.0))
@@ -2374,6 +2377,79 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
2374
2377
  },
2375
2378
  })
2376
2379
 
2380
+ tool({
2381
+ name: 'cad_studio_check',
2382
+ description: 'Check a model before you export or print it: is it a valid solid, is every shell closed, how many solids/shells/faces, volume per solid, and a plain-language list of problems (零体积 / 外壳未闭合 / 几何无效 / 没有实体). Run this instead of trusting a file size.',
2383
+ parameters: {
2384
+ type: 'object',
2385
+ properties: {
2386
+ source: { type: 'string', description: 'Existing model file (STEP/IGES/BREP/STL).' },
2387
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
2388
+ minVolume: { type: 'number', description: 'Flag solids below this volume in mm3 as suspicious (default 0.001).' },
2389
+ },
2390
+ additionalProperties: false,
2391
+ },
2392
+ output: {
2393
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, problems: { type: 'array', items: { type: 'string' } } } },
2394
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2395
+ },
2396
+ execute: async ({ source, code, minVolume }) => {
2397
+ if (!source && !code) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
2398
+ const floor = Number.isFinite(minVolume) ? Number(minVolume) : 0.001
2399
+ const src = shapesFrom({ source, code })
2400
+ // Volume 0 with ShapeType "Solid" is a real failure mode on this kernel
2401
+ // (lofting two faces, revolving about an axis perpendicular to the profile),
2402
+ // so a file that opens and has faces can still be unprintable. Say it here.
2403
+ const py = `${PRELUDE}
2404
+ ${src}
2405
+ _problems = []
2406
+ _items = []
2407
+ if not _shapes:
2408
+ _problems.append("没有实体:文件里读不出任何 shape")
2409
+ for _i, _s in enumerate(_shapes):
2410
+ _vol = float(_s.Volume or 0.0)
2411
+ _shells = list(_s.Shells)
2412
+ _open = []
2413
+ for _k, _sh in enumerate(_shells):
2414
+ try:
2415
+ if not _sh.isClosed():
2416
+ _open.append(_k)
2417
+ except Exception:
2418
+ pass
2419
+ _item = {
2420
+ "index": _i,
2421
+ "type": str(_s.ShapeType),
2422
+ "volume": round(_vol, 3),
2423
+ "area": round(float(_s.Area or 0.0), 3),
2424
+ "solids": len(_s.Solids),
2425
+ "shells": len(_shells),
2426
+ "faces": len(_s.Faces),
2427
+ "edges": len(_s.Edges),
2428
+ "valid": bool(_s.isValid()),
2429
+ "closed": not _open,
2430
+ }
2431
+ _items.append(_item)
2432
+ _tag = "shape #%d" % _i
2433
+ if abs(_vol) <= ${JSON.stringify(floor)}:
2434
+ _problems.append("%s 体积为零(%.6f mm3):面在,实体不在" % (_tag, _vol))
2435
+ if not _item["valid"]:
2436
+ _problems.append("%s 几何无效(OCC isValid=false),后续布尔/导出可能失败" % _tag)
2437
+ if len(_s.Solids) == 0:
2438
+ _problems.append("%s 没有实体(只有面/壳)" % _tag)
2439
+ if _open:
2440
+ _problems.append("%s 有 %d 个外壳未闭合:不是水密体,打印/布尔会漏" % (_tag, len(_open)))
2441
+ __out = {
2442
+ "ok": len(_problems) == 0,
2443
+ "checked": len(_items),
2444
+ "volume": round(sum(float(x.Volume or 0.0) for x in _shapes), 3),
2445
+ "problems": _problems,
2446
+ "solids": _items,
2447
+ }
2448
+ `
2449
+ return bridge.run(py, { title: 'check', publishHint: false })
2450
+ },
2451
+ })
2452
+
2377
2453
  tool({
2378
2454
  name: 'cad_studio_section',
2379
2455
  description: `Cross-section of a solid: slice it with a plane and report closed loops, area and perimeter; optionally write the outline as SVG (for laser/CNC nesting). Axis is X/Y/Z, at is the plane offset in mm.`,
@@ -3176,13 +3252,14 @@ if _TARGET:
3176
3252
  parameters: {
3177
3253
  type: 'object',
3178
3254
  properties: {
3179
- action: { type: 'string', enum: ['list', 'show', 'create', 'update', 'revert', 'delete'], description: 'list / show / create / update / revert / delete' },
3255
+ action: { type: 'string', enum: ['list', 'show', 'create', 'update', 'revert', 'delete', 'rename', 'duplicate'], description: 'list / show / create / update / revert / delete / rename / duplicate' },
3180
3256
  name: { type: 'string', description: 'Model name (中英文/数字/下划线/连字符).' },
3181
3257
  script: { type: 'string', description: 'FreeCAD Python source; reads params from `P`, binds the result to `scene`. Required for create unless kind is "features".' },
3182
3258
  kind: { type: 'string', enum: ['script', 'features'], description: 'script (default): a Python script + params. features: a declarative feature list you can edit one feature at a time (see cad_studio_features).' },
3183
3259
  features: { type: 'array', items: { type: 'object' }, description: 'For kind="features": the initial feature list, each {kind, label?, params?} (flat params such as {kind:"box", size:[60,40,20]} also work).' },
3184
3260
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
3185
3261
  note: { type: 'string', description: 'What this revision changed (kept in history).' },
3262
+ to: { type: 'string', description: 'For action=rename / duplicate: the new model name.' },
3186
3263
  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.' },
3187
3264
  },
3188
3265
  required: ['action'],
@@ -3589,6 +3666,78 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3589
3666
  return { ok: true, name: key, deleted: true, dir }
3590
3667
  }
3591
3668
 
3669
+ if (action === 'rename') {
3670
+ const key = checkName(args.name)
3671
+ const to = checkName(args.to ?? args.newName)
3672
+ if (to === key) return { ok: true, name: key, renamed: false, dir }
3673
+ const from = modelFile(key, dir)
3674
+ const dest = modelFile(to, dir)
3675
+ const existing = await readModel(key, dir).catch(() => { throw new Error(`没有这个模型:${key}`) })
3676
+ try { await readModel(to, dir); throw new Error(`目标名字已被占用:${to}`) } catch (err) { if (/已被占用/.test(String(err.message))) throw err }
3677
+ // The name lives inside the JSON too, so rewrite the document under the
3678
+ // new name instead of copying bytes: a byte copy would keep `name: old`
3679
+ // inside the file and the model list would keep showing the old name.
3680
+ const bytes = await readFile(from)
3681
+ existing.name = to
3682
+ await writeModel(existing, dir)
3683
+ await unlink(from).catch(() => {})
3684
+ const doc = await readModel(to, dir)
3685
+ const row = bridge.history.find((h) => h.docKey === `model:${key}` || h.title === key)
3686
+ if (row) {
3687
+ row.title = to
3688
+ if (row.docKey) row.docKey = `model:${to}`
3689
+ await bridge.persist()
3690
+ }
3691
+ const restore = async (target, other) => {
3692
+ const r = bridge.history.find((h) => h.docKey === `model:${other}` || h.title === other)
3693
+ if (r) { r.title = target; if (r.docKey) r.docKey = `model:${target}`; await bridge.persist() }
3694
+ }
3695
+ bridge.journal({
3696
+ kind: 'doc',
3697
+ label: `rename ${key} → ${to}`,
3698
+ undo: async () => {
3699
+ const back = await readModel(to, dir)
3700
+ back.name = key
3701
+ await writeModel(back, dir)
3702
+ await unlink(dest).catch(() => {})
3703
+ await restore(key, to)
3704
+ return { model: key }
3705
+ },
3706
+ redo: async () => {
3707
+ const fwd = await readModel(key, dir)
3708
+ fwd.name = to
3709
+ await writeModel(fwd, dir)
3710
+ await unlink(from).catch(() => {})
3711
+ await restore(to, key)
3712
+ return { model: to }
3713
+ },
3714
+ })
3715
+ return { ok: true, name: key, to, renamed: true, kind: doc.kind, dir }
3716
+ }
3717
+
3718
+ if (action === 'duplicate') {
3719
+ const key = checkName(args.name)
3720
+ const to = checkName(args.to ?? args.newName)
3721
+ if (to === key) throw new Error('复制到自己:to 必须与 name 不同')
3722
+ const bytes = await readFile(modelFile(key, dir)).catch(() => { throw new Error(`没有这个模型:${key}`) })
3723
+ try { await readModel(to, dir); throw new Error(`目标名字已被占用:${to}`) } catch (err) { if (/已被占用/.test(String(err.message))) throw err }
3724
+ await writeFile(modelFile(to, dir), bytes)
3725
+ const doc = await readModel(to, dir)
3726
+ // A copy starts its own line: no run history, no scene pointer, and no
3727
+ // undo stack borrowed from the original.
3728
+ doc.name = to
3729
+ doc.run = 0
3730
+ doc.history = []
3731
+ doc.createdAt = new Date().toISOString()
3732
+ doc.stats = {}
3733
+ delete doc.undo
3734
+ delete doc.redo
3735
+ const result = await rebuild(doc, dir, { note: `duplicate of ${key}` })
3736
+ if (result.ok === false) return result
3737
+ await journalDocCreate(to, dir, result)
3738
+ return { ...result, name: to, kind: doc.kind, copiedFrom: key, ...(doc.kind === 'features' ? { features: publicFeatures(doc) } : {}) }
3739
+ }
3740
+
3592
3741
  throw new Error(`未知 action:${action}`)
3593
3742
  }
3594
3743
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {