dsh-cad-studio 0.14.0 → 0.16.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 +161 -9
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -20,6 +20,9 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
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
22
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
23
+ | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
24
+ | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
25
+ | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
23
26
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
24
27
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
25
28
  | 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
package/index.js CHANGED
@@ -1093,6 +1093,7 @@ print("${BEGIN}" + __json.dumps(_safe(_payload)) + "${END}", flush=True)\n`
1093
1093
  const PRELUDE = `
1094
1094
  import json, math
1095
1095
  import Part, Import, FreeCAD
1096
+ import Mesh, MeshPart # only used by cad_studio_mesh, but a missing import here fails the whole job
1096
1097
  Vector = FreeCAD.Vector
1097
1098
 
1098
1099
  def _safe(v):
@@ -1212,6 +1213,10 @@ def _v3(x, d=(0.0, 0.0, 0.0)):
1212
1213
  return Vector(float(x[0]), float(x[1]), float(x[2]))
1213
1214
 
1214
1215
  def _dir(x, d=(0.0, 0.0, 1.0)):
1216
+ # "X"/"Y"/"Z" are accepted everywhere a direction is expected, not just
1217
+ # [x,y,z]: writing axis:'Y' is what a human means when revolving a sketch.
1218
+ if isinstance(x, str) and x.strip().upper() in ("X", "Y", "Z"):
1219
+ 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
1220
  v = _v3(x, d)
1216
1221
  return v if v.Length > 1e-9 else _v3(d, (0.0, 0.0, 1.0))
1217
1222
 
@@ -1377,18 +1382,17 @@ def _prim(op, _cur=None):
1377
1382
  return body
1378
1383
  if k == "revolve":
1379
1384
  if op.get("sketch"):
1385
+ # Measured on 0.20.2: a face revolved about an axis that LIES IN its
1386
+ # plane gives a valid solid (ring: area x 2*pi*r_centroid); about an
1387
+ # axis PERPENDICULAR to its plane it gives a zero-thickness annulus
1388
+ # (Volume 0, isValid() still True). So the axis has to be explicit:
1389
+ # guessing it silently would produce 0 mm3 instead of an error.
1390
+ if op.get("axis") is None:
1391
+ raise RuntimeError("草图旋转要显式给 axis:草图平面内的轴(如 'Y' 或 [0,1,0])会扫出实体;垂直于草图平面的轴(XY 草图的 Z)扫出的是零厚度圆环")
1380
1392
  face = Part.Face(_sketch(str(op["sketch"])))
1381
1393
  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
1394
  if abs(rev.Volume) < 1e-9:
1390
- # Do not hand a zero-volume shell downstream: say it out loud.
1391
- raise RuntimeError("草图旋转得到的是壳体、没有闭合(需要 sewShape 缝合);先用挤出,或把草图轮廓贴住旋转轴")
1395
+ raise RuntimeError("草图旋转得到零体积:旋转轴垂直于草图平面(XY 草图 + Z 轴只会扫出零厚度圆环)。把 axis 换成草图平面内的轴,例如 axis:'Y'")
1392
1396
  return rev
1393
1397
  ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
1394
1398
  ang = float(op.get("angle", 360.0))
@@ -2374,6 +2378,154 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
2374
2378
  },
2375
2379
  })
2376
2380
 
2381
+ tool({
2382
+ name: 'cad_studio_check',
2383
+ 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.',
2384
+ parameters: {
2385
+ type: 'object',
2386
+ properties: {
2387
+ source: { type: 'string', description: 'Existing model file (STEP/IGES/BREP/STL).' },
2388
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
2389
+ minVolume: { type: 'number', description: 'Flag solids below this volume in mm3 as suspicious (default 0.001).' },
2390
+ },
2391
+ additionalProperties: false,
2392
+ },
2393
+ output: {
2394
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, problems: { type: 'array', items: { type: 'string' } } } },
2395
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2396
+ },
2397
+ execute: async ({ source, code, minVolume }) => {
2398
+ if (!source && !code) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
2399
+ const floor = Number.isFinite(minVolume) ? Number(minVolume) : 0.001
2400
+ const src = shapesFrom({ source, code })
2401
+ // Volume 0 with ShapeType "Solid" is a real failure mode on this kernel
2402
+ // (lofting two faces, revolving about an axis perpendicular to the profile),
2403
+ // so a file that opens and has faces can still be unprintable. Say it here.
2404
+ const py = `${PRELUDE}
2405
+ ${src}
2406
+ _problems = []
2407
+ _items = []
2408
+ if not _shapes:
2409
+ _problems.append("没有实体:文件里读不出任何 shape")
2410
+ for _i, _s in enumerate(_shapes):
2411
+ _vol = float(_s.Volume or 0.0)
2412
+ _shells = list(_s.Shells)
2413
+ _open = []
2414
+ for _k, _sh in enumerate(_shells):
2415
+ try:
2416
+ if not _sh.isClosed():
2417
+ _open.append(_k)
2418
+ except Exception:
2419
+ pass
2420
+ _item = {
2421
+ "index": _i,
2422
+ "type": str(_s.ShapeType),
2423
+ "volume": round(_vol, 3),
2424
+ "area": round(float(_s.Area or 0.0), 3),
2425
+ "solids": len(_s.Solids),
2426
+ "shells": len(_shells),
2427
+ "faces": len(_s.Faces),
2428
+ "edges": len(_s.Edges),
2429
+ "valid": bool(_s.isValid()),
2430
+ "closed": not _open,
2431
+ }
2432
+ _items.append(_item)
2433
+ _tag = "shape #%d" % _i
2434
+ if abs(_vol) <= ${JSON.stringify(floor)}:
2435
+ _problems.append("%s 体积为零(%.6f mm3):面在,实体不在" % (_tag, _vol))
2436
+ if not _item["valid"]:
2437
+ _problems.append("%s 几何无效(OCC isValid=false),后续布尔/导出可能失败" % _tag)
2438
+ if len(_s.Solids) == 0:
2439
+ _problems.append("%s 没有实体(只有面/壳)" % _tag)
2440
+ if _open:
2441
+ _problems.append("%s 有 %d 个外壳未闭合:不是水密体,打印/布尔会漏" % (_tag, len(_open)))
2442
+ __out = {
2443
+ "ok": len(_problems) == 0,
2444
+ "checked": len(_items),
2445
+ "volume": round(sum(float(x.Volume or 0.0) for x in _shapes), 3),
2446
+ "problems": _problems,
2447
+ "solids": _items,
2448
+ }
2449
+ `
2450
+ return bridge.run(py, { title: 'check', publishHint: false })
2451
+ },
2452
+ })
2453
+
2454
+ tool({
2455
+ name: 'cad_studio_mesh',
2456
+ description: 'Turn a solid into a printable mesh and clean it up: dedupe coincident points/facets, fix deformations, harmonize normals, optionally fill small holes or decimate to a facet budget, then write an STL. Reports facets/points before and after so you can see what the repair actually changed.',
2457
+ parameters: {
2458
+ type: 'object',
2459
+ properties: {
2460
+ source: { type: 'string', description: 'Existing model file (STEP/IGES/BREP/STL).' },
2461
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
2462
+ target: { type: 'string', description: 'Write the STL here (absolute path).' },
2463
+ deflection: { type: 'number', description: 'Linear deflection in mm (smaller = finer, default 0.2).' },
2464
+ angular: { type: 'number', description: 'Angular deflection in radians (default 0.5).' },
2465
+ targetSize: { type: 'integer', description: 'Decimate down to at most this many facets (optional).' },
2466
+ fillHoles: { type: 'number', description: 'Fill holes whose edges are shorter than this many mm (0 = skip, default 0).' },
2467
+ repair: { type: 'boolean', description: 'Dedupe points/facets, fix deformations, harmonize normals (default true).' },
2468
+ },
2469
+ additionalProperties: false,
2470
+ },
2471
+ output: {
2472
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, facets: { type: 'number' }, points: { type: 'number' }, bytes: { type: 'number' } } },
2473
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2474
+ },
2475
+ execute: async ({ source, code, target, deflection, angular, targetSize, fillHoles, repair }) => {
2476
+ if (!source && !code) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
2477
+ if (!target) return { ok: false, error: 'target 是必填的:STL 写到哪里' }
2478
+ const defl = Number.isFinite(deflection) ? Number(deflection) : 0.2
2479
+ const ang = Number.isFinite(angular) ? Number(angular) : 0.5
2480
+ const size = Number.isInteger(targetSize) && targetSize > 0 ? targetSize : 0
2481
+ const hole = Number.isFinite(fillHoles) ? Number(fillHoles) : 0
2482
+ const doRepair = repair !== false
2483
+ const src = shapesFrom({ source, code })
2484
+ // Meshing is a different pipeline from the BRep checks: a shape can be a
2485
+ // valid solid and still mesh into duplicated points / flipped normals.
2486
+ const py = `${PRELUDE}
2487
+ ${src}
2488
+ if not _shapes:
2489
+ __out = {"ok": False, "error": "nothing to mesh"}
2490
+ else:
2491
+ _body = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
2492
+ _m = MeshPart.meshFromShape(Shape=_body, LinearDeflection=${JSON.stringify(defl)}, AngularDeflection=${JSON.stringify(ang)}, Relative=False)
2493
+ _before = {"facets": int(_m.CountFacets), "points": int(_m.CountPoints)}
2494
+ if ${doRepair ? 'True' : 'False'}:
2495
+ _m.removeDuplicatedPoints()
2496
+ _m.removeDuplicatedFacets()
2497
+ try:
2498
+ _m.fixDeformations()
2499
+ except Exception:
2500
+ pass
2501
+ _m.harmonizeNormals()
2502
+ if ${JSON.stringify(hole)} > 0:
2503
+ _m.fillupHoles(${JSON.stringify(hole)})
2504
+ _mid = {"facets": int(_m.CountFacets), "points": int(_m.CountPoints)}
2505
+ _decimated = False
2506
+ if ${JSON.stringify(size)} and _m.CountFacets > ${JSON.stringify(size)}:
2507
+ _m.decimate(${JSON.stringify(size)})
2508
+ _decimated = True
2509
+ _m.write(${JSON.stringify(String(target))})
2510
+ import os
2511
+ _bb = _body.BoundBox
2512
+ __out = {
2513
+ "ok": True,
2514
+ "target": ${JSON.stringify(String(target))},
2515
+ "bytes": int(os.path.getsize(${JSON.stringify(String(target))})),
2516
+ "facets": int(_m.CountFacets),
2517
+ "points": int(_m.CountPoints),
2518
+ "before": _before,
2519
+ "afterRepair": _mid,
2520
+ "decimated": _decimated,
2521
+ "repaired": ${doRepair ? 'True' : 'False'},
2522
+ "bbox": [round(_bb.XLength, 2), round(_bb.YLength, 2), round(_bb.ZLength, 2)],
2523
+ }
2524
+ `
2525
+ return bridge.run(py, { title: 'mesh', publishHint: false })
2526
+ },
2527
+ })
2528
+
2377
2529
  tool({
2378
2530
  name: 'cad_studio_section',
2379
2531
  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.`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {