dsh-cad-studio 0.24.0 → 0.26.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 +262 -2
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -24,6 +24,8 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
24
24
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
25
25
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
26
26
  | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
27
+ | 拔模挤出 | `{kind:"extrude", sketch:"S1", h:20, draft:3}` 按 3° 拔模:截面按 `h*tan(3°)` 偏移后 loft 成体,正角度内收、负角度外放 |
28
+ | 展开图 | `cad_studio_unfold {source, target:"…/net.dxf"}` 把板类零件按共享边摊平成下料图(面片等距铺开,面积与模型一致;孔各自成环;圆柱/圆角等曲面报 `curvedSkipped` 而不是瞎编),可写 DXF 或 SVG |
27
29
  | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
28
30
  | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
29
31
  | 面板改草图 | 特征抽屉里点「草图 N」展开:数值约束是可编辑输入框(`distance*`/`radius`/`angle` 按度),改完立刻重解并重建;解不出来就回滚并报错 |
package/index.js CHANGED
@@ -1722,8 +1722,32 @@ def _prim(op, _cur=None):
1722
1722
  return Part.makeTorus(float(op["r1"]), float(op["r2"]), at, _dir(op.get("axis")))
1723
1723
  if k == "extrude":
1724
1724
  if op.get("sketch"):
1725
- face = Part.Face(_sketch(str(op["sketch"])))
1726
- return face.extrude(_dir(op.get("dir"), (0.0, 0.0, float(op.get("h") or 10.0))))
1725
+ wire = _sketch(str(op["sketch"]))
1726
+ vec = _dir(op.get("dir"), (0.0, 0.0, float(op.get("h") or 10.0)))
1727
+ draft = float(op.get("draft", 0.0) or 0.0)
1728
+ if abs(draft) < 1e-9:
1729
+ return Part.Face(wire).extrude(vec)
1730
+ # Draft: the section shrinks toward the far end, so the wall leans by
1731
+ # the requested angle instead of going straight up. Offsetting the
1732
+ # section in its own plane and lofting keeps the sides planar; a
1733
+ # plain extrude plus a taper would need a real BRepOffsetAPI call
1734
+ # that FreeCAD 0.20 does not expose to Python.
1735
+ if abs(draft) >= 89.0:
1736
+ raise RuntimeError("draft 需要 -89 到 89 度之间的角度")
1737
+ drop = abs(vec.Length) * math.tan(math.radians(abs(draft)))
1738
+ sign = -1.0 if draft > 0 else 1.0
1739
+ try:
1740
+ ring = wire.makeOffset2D(sign * drop, 0, False, False)
1741
+ except Exception:
1742
+ raise RuntimeError("draft 无法偏移这个截面:向内缩 %.3f mm 后没有面积了(减小角度或加大截面)" % drop)
1743
+ if ring.ShapeType != "Wire":
1744
+ raise RuntimeError("draft 无法偏移这个截面(可能是自交或太窄:需要向内缩 %.3f mm)" % drop)
1745
+ ring = ring.copy()
1746
+ ring.translate(vec)
1747
+ solid = Part.makeLoft([wire, ring], True)
1748
+ if abs(solid.Volume) < 1e-9:
1749
+ raise RuntimeError("draft 得到零体积:截面缩 %.3f mm 后已经没有面积了,减小角度" % drop)
1750
+ return solid
1727
1751
  base = float(op.get("base", 0.0))
1728
1752
  h = float(op.get("h", 0.0))
1729
1753
  # Points may be 2D (z = base) or 3D; dir replaces the +Z extrusion,
@@ -3153,6 +3177,242 @@ __out = {
3153
3177
  },
3154
3178
  })
3155
3179
 
3180
+ tool({
3181
+ name: 'cad_studio_unfold',
3182
+ description: 'Unfold a solid made of flat faces into a 2D net (板金展开): every planar face is laid flat next to the one it shares an edge with, without stretching — a net you can cut and fold. Curved faces (cylinders, fillets, bends) are reported as skipped, not invented. Writes DXF (polylines, mm) or SVG; areas are reported so a net that came out wrong is visible.',
3183
+ parameters: {
3184
+ type: 'object',
3185
+ properties: {
3186
+ source: { type: 'string', description: 'Existing model file (STEP/IGES/BREP).' },
3187
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
3188
+ target: { type: 'string', description: 'Absolute path: .dxf (polylines) or .svg (outline).' },
3189
+ deflection: { type: 'number', description: 'Curve sampling for the outline, mm (default 0.25).' },
3190
+ holes: { type: 'boolean', description: 'Include inner wires (holes) as separate closed outlines (default true).' },
3191
+ },
3192
+ additionalProperties: false,
3193
+ },
3194
+ output: {
3195
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, unfolded: { type: 'number' }, areaModel: { type: 'number' }, areaFlat: { type: 'number' }, curvedSkipped: { type: 'number' }, target: { type: 'string' } } },
3196
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3197
+ },
3198
+ execute: async ({ source, code, target, deflection = 0.25, holes = true }) => {
3199
+ if (!source && !code) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
3200
+ const absTarget = target ? String(target) : ''
3201
+ if (absTarget && !(absTarget.startsWith('/') || /^[A-Za-z]:[\\/]/.test(absTarget))) return { ok: false, error: 'target must be an absolute path' }
3202
+ const src = shapesFrom({ source, code })
3203
+ const py = `${PRELUDE}
3204
+ ${src}
3205
+ _DEFL = float(${Number.isFinite(deflection) ? deflection : 0.25})
3206
+ _HOLES = ${holes === false ? 'False' : 'True'}
3207
+ _TARGET = ${absTarget ? JSON.stringify(absTarget) : 'None'}
3208
+
3209
+ import math
3210
+ from FreeCAD import Vector as _V
3211
+
3212
+ def _k(_p):
3213
+ return (round(_p.x, 4), round(_p.y, 4), round(_p.z, 4))
3214
+
3215
+ def _ordered(_wire):
3216
+ """Vertices of a wire in traversal order (OuterWire.Vertexes is unordered)."""
3217
+ _edges = _wire.Edges
3218
+ if not _edges:
3219
+ return []
3220
+ _pts = [_edges[0].Vertexes[0].Point, _edges[0].Vertexes[-1].Point]
3221
+ _used = {0}
3222
+ while len(_used) < len(_edges):
3223
+ _tail = _pts[-1]; _found = False
3224
+ for _i, _e in enumerate(_edges):
3225
+ if _i in _used: continue
3226
+ _a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
3227
+ if _k(_a) == _k(_tail): _pts.append(_b); _used.add(_i); _found = True; break
3228
+ if _k(_b) == _k(_tail): _pts.append(_a); _used.add(_i); _found = True; break
3229
+ if not _found: break
3230
+ if len(_pts) > 1 and _k(_pts[0]) == _k(_pts[-1]): _pts.pop()
3231
+ return _pts
3232
+
3233
+ def _ordered_edges(_wire):
3234
+ """Edges of a wire in traversal order, each flagged when it runs backwards."""
3235
+ _edges = list(_wire.Edges)
3236
+ if not _edges:
3237
+ return []
3238
+ _out = [(_edges[0], False)]
3239
+ _used = {0}
3240
+ _tail = _edges[0].Vertexes[-1].Point
3241
+ while len(_used) < len(_edges):
3242
+ _found = False
3243
+ for _i, _e in enumerate(_edges):
3244
+ if _i in _used:
3245
+ continue
3246
+ _a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
3247
+ if _k(_a) == _k(_tail):
3248
+ _out.append((_e, False)); _used.add(_i); _tail = _b; _found = True; break
3249
+ if _k(_b) == _k(_tail):
3250
+ _out.append((_e, True)); _used.add(_i); _tail = _a; _found = True; break
3251
+ if not _found:
3252
+ break
3253
+ return _out
3254
+
3255
+ def _sample(_wire):
3256
+ """Outline points in traversal order: endpoints for lines, sampled arcs.
3257
+
3258
+ Wire.Edges comes back unordered, so walking them as given would splice the
3259
+ outline out of order and the shoelace area would come out wrong.
3260
+ """
3261
+ _out = []
3262
+ for _e, _rev in _ordered_edges(_wire):
3263
+ _c = _e.Curve
3264
+ _straight = isinstance(_c, Part.Line) or isinstance(_c, Part.LineSegment)
3265
+ _pts = list(_e.discretize(Deflection=_DEFL)) if not _straight else [_e.Vertexes[0].Point, _e.Vertexes[-1].Point]
3266
+ if _rev:
3267
+ _pts.reverse()
3268
+ for _p in _pts:
3269
+ if not _out or _k(_out[-1]) != _k(_p):
3270
+ _out.append(_p)
3271
+ if len(_out) > 1 and _k(_out[0]) == _k(_out[-1]):
3272
+ _out.pop()
3273
+ return _out
3274
+
3275
+ def _frame(_f):
3276
+ _n = _f.Surface.Axis.normalize()
3277
+ _c = _f.CenterOfMass
3278
+ _pts = _ordered(_f.OuterWire)
3279
+ if not _pts:
3280
+ return None
3281
+ _u = _pts[0] - _c
3282
+ _u = _u - _n * _u.dot(_n)
3283
+ if _u.Length < 1e-9:
3284
+ return None
3285
+ _u.normalize()
3286
+ return _c, _u, _n.cross(_u)
3287
+
3288
+ def _unfold(_shape):
3289
+ _faces = [_f for _f in _shape.Faces if isinstance(_f.Surface, Part.Plane)]
3290
+ _curved = len(_shape.Faces) - len(_faces)
3291
+ if not _faces:
3292
+ return {"ok": False, "error": "这个形状没有平面:展开只适用于板类零件"}
3293
+ _owner = {}
3294
+ for _fi, _f in enumerate(_faces):
3295
+ for _e in _f.Edges:
3296
+ _ka, _kb = _k(_e.Vertexes[0].Point), _k(_e.Vertexes[-1].Point)
3297
+ _owner.setdefault((_ka, _kb) if _ka <= _kb else (_kb, _ka), []).append(_fi)
3298
+ _root = max(range(len(_faces)), key=lambda i: _faces[i].Area)
3299
+ _fr = _frame(_faces[_root])
3300
+ if _fr is None:
3301
+ return {"ok": False, "error": "最大平面没有可用的局部坐标系"}
3302
+ _c, _u, _v = _fr
3303
+ def _to2(_p):
3304
+ _d = _p - _c
3305
+ return (_d.dot(_u), _d.dot(_v))
3306
+ _pos = {}
3307
+ for _p in _ordered(_faces[_root].OuterWire):
3308
+ _pos[_k(_p)] = _to2(_p)
3309
+ _polys = []
3310
+ def _rings(_f, _map3):
3311
+ # Takes a 3D point to the flat layout: the root face projects with its
3312
+ # own frame, every other face composes that with its hinge placement.
3313
+ _rs = []
3314
+ _wires = _f.Wires if _HOLES else [_f.OuterWire]
3315
+ for _w in _wires:
3316
+ _pts = _sample(_w)
3317
+ if len(_pts) >= 3:
3318
+ _rs.append([_map3(_p) for _p in _pts])
3319
+ return _rs
3320
+ _polys.extend(_rings(_faces[_root], _to2))
3321
+ _seen, _queue, _worst = {_root}, [_root], 0.0
3322
+ while _queue:
3323
+ _cur = _queue.pop(0)
3324
+ _cur2 = [_pos[_k(_p)] for _p in _ordered(_faces[_cur].OuterWire) if _k(_p) in _pos]
3325
+ if not _cur2: continue
3326
+ _cxc = sum(q[0] for q in _cur2) / len(_cur2); _cyc = sum(q[1] for q in _cur2) / len(_cur2)
3327
+ for _e in _faces[_cur].Edges:
3328
+ _a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
3329
+ _ka, _kb = _k(_a), _k(_b)
3330
+ for _nb in _owner.get((_ka, _kb) if _ka <= _kb else (_kb, _ka), []):
3331
+ if _nb in _seen: continue
3332
+ _ag, _bg = _pos.get(_ka), _pos.get(_kb)
3333
+ if _ag is None or _bg is None: continue
3334
+ _fnb = _frame(_faces[_nb])
3335
+ if _fnb is None: continue
3336
+ _cn, _un, _vn = _fnb
3337
+ def _local(_p, _cn=_cn, _un=_un, _vn=_vn):
3338
+ _d = _p - _cn
3339
+ return (_d.dot(_un), _d.dot(_vn))
3340
+ _la, _lb = _local(_a), _local(_b)
3341
+ _th = math.atan2(_bg[1] - _ag[1], _bg[0] - _ag[0]) - math.atan2(_lb[1] - _la[1], _lb[0] - _la[0])
3342
+ _ct, _st = math.cos(_th), math.sin(_th)
3343
+ def _place(q, _ag=_ag, _la=_la, _ct=_ct, _st=_st):
3344
+ _dx, _dy = q[0] - _la[0], q[1] - _la[1]
3345
+ return (_ag[0] + _ct * _dx - _st * _dy, _ag[1] + _st * _dx + _ct * _dy)
3346
+ # A hinge has exactly two ways to fold flat: pick the one that
3347
+ # puts the new face on the other side of the edge from the face
3348
+ # we are folding from (same side = the two would overlap).
3349
+ _out = _ordered(_faces[_nb].OuterWire)
3350
+ _m = [_place(_local(_p)) for _p in _out]
3351
+ _cx = sum(q[0] for q in _m) / len(_m); _cy = sum(q[1] for q in _m) / len(_m)
3352
+ _sd = (_bg[0] - _ag[0]) * (_cy - _ag[1]) - (_bg[1] - _ag[1]) * (_cx - _ag[0])
3353
+ _sc = (_bg[0] - _ag[0]) * (_cyc - _ag[1]) - (_bg[1] - _ag[1]) * (_cxc - _ag[0])
3354
+ if (_sd > 0) == (_sc > 0):
3355
+ _dhx, _dhy = _bg[0] - _ag[0], _bg[1] - _ag[1]
3356
+ _L = math.hypot(_dhx, _dhy)
3357
+ if _L < 1e-9: continue
3358
+ _dhx, _dhy = _dhx / _L, _dhy / _L
3359
+ def _mirror(q, _ag=_ag, _dhx=_dhx, _dhy=_dhy):
3360
+ _vx, _vy = q[0] - _ag[0], q[1] - _ag[1]
3361
+ _dot = _vx * _dhx + _vy * _dhy
3362
+ return (_ag[0] + 2 * _dot * _dhx - _vx, _ag[1] + 2 * _dot * _dhy - _vy)
3363
+ _place_inner = lambda q: _mirror(_place(q))
3364
+ else:
3365
+ _place_inner = _place
3366
+ _polys.extend(_rings(_faces[_nb], lambda _p, _loc=_local, _pl=_place_inner: _pl(_loc(_p))))
3367
+ _seen.add(_nb); _queue.append(_nb)
3368
+ for _p, _q in zip(_out, [_place_inner(_local(_p)) for _p in _out]):
3369
+ if _k(_p) in _pos:
3370
+ _worst = max(_worst, math.hypot(_pos[_k(_p)][0] - _q[0], _pos[_k(_p)][1] - _q[1]))
3371
+ _pos[_k(_p)] = _q
3372
+ def _area2(_m):
3373
+ return abs(sum((_m[_i][0] * _m[(_i + 1) % len(_m)][1] - _m[(_i + 1) % len(_m)][0] * _m[_i][1]) for _i in range(len(_m)))) / 2.0
3374
+ _flat = sum(_area2(_m) for _m in _polys)
3375
+ _xs = [q[0] for _m in _polys for q in _m]
3376
+ _ys = [q[1] for _m in _polys for q in _m]
3377
+ _out = {"ok": True, "faces": len(_faces), "unfolded": len(_seen), "curvedSkipped": _curved,
3378
+ "areaModel": round(_shape.Area, 3), "areaFlat": round(_flat, 3),
3379
+ "bbox": [round(min(_xs), 3), round(min(_ys), 3), round(max(_xs), 3), round(max(_ys), 3)]}
3380
+ if _TARGET:
3381
+ os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
3382
+ if _TARGET.lower().endswith(".svg"):
3383
+ _minx, _miny, _maxx, _maxy = _out["bbox"]
3384
+ _w = _maxx - _minx + 10; _h = _maxy - _miny + 10
3385
+ _parts = []
3386
+ for _m in _polys:
3387
+ _d = " ".join("%.3f,%.3f" % (q[0] - _minx + 5, _maxy - q[1] + 5) for q in _m)
3388
+ _parts.append('<polygon points="%s" fill="none" stroke="#111" stroke-width="0.3"/>' % _d)
3389
+ open(_TARGET, "w").write('<svg xmlns="http://www.w3.org/2000/svg" width="%.2fmm" height="%.2fmm" viewBox="0 0 %.2f %.2f">%s</svg>' % (_w, _h, _w, _h, "".join(_parts)))
3390
+ else:
3391
+ _wires = []
3392
+ for _m in _polys:
3393
+ _pts = [Vector(q[0], q[1], 0.0) for q in _m]
3394
+ if len(_pts) >= 3:
3395
+ _pts.append(_pts[0])
3396
+ _wires.append(Part.makePolygon(_pts))
3397
+ import importDXF
3398
+ importDXF.export([Part.makeCompound(_wires)], _TARGET)
3399
+ _out["target"] = _TARGET
3400
+ _out["bytes"] = os.path.getsize(_TARGET)
3401
+ return _out
3402
+
3403
+ _out = None
3404
+ for _s in _shapes:
3405
+ _r = _unfold(_s)
3406
+ if _r.get("ok"):
3407
+ _out = _r
3408
+ break
3409
+ _out = _r
3410
+ __out = _out
3411
+ `
3412
+ return bridge.run(py, { title: 'unfold', publishHint: false })
3413
+ },
3414
+ })
3415
+
3156
3416
  tool({
3157
3417
  name: 'cad_studio_mesh',
3158
3418
  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.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {