dsh-cad-studio 0.5.0 → 0.6.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 +13 -0
  2. package/client.js +4 -1
  3. package/index.js +134 -2
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -56,6 +56,19 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
56
56
 
57
57
  `autoOpen: 'session'` 的判据是宿主侧的两个信号:这个会话最近一次发布过场景(`lastSession`),或它拥有更早发布过的场景。也就是说——只有真正在这里建过模的对话,右栏才会自动让出位置;别的对话不受打扰。
58
58
 
59
+ ## 子形状选择器
60
+
61
+ `fillet` / `chamfer` 的 `edges`、`shell` 的 `faces` 接受**谓词**(不存 id,每次重建重新选):
62
+
63
+ ```json
64
+ {"kind": "fillet", "r": 3, "edges": {"axis": "Z", "mode": "parallel", "type": "line"}}
65
+ {"kind": "shell", "t": 2, "faces": {"axis": "Z", "mode": "aligned", "dir": "+", "type": "plane"}}
66
+ ```
67
+
68
+ 字段:`axis`(X/Y/Z 或 [x,y,z])、`mode`(`parallel` / `aligned` / `perpendicular`)、`dir`(`+`/`-`)、`type`(边 `line`/`circle`,面 `plane`/`cylinder`)、`radius`、`pick`(`max`/`min`)、`nth`、`near`(点)、`one`(要求恰好一个)、`tol`(默认 0.5 mm)。
69
+
70
+ 选不中会**报错并在面板标红**:`选择器没有选中任何边:{"axis":"Z","type":"circle"}(当前形状有 12 条边)`。设计取舍见 `docs/RESEARCH-SELECTORS.md`。
71
+
59
72
  ## 接口约定与踩过的坑
60
73
 
61
74
  - **导出只走 `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`。
package/client.js CHANGED
@@ -1844,8 +1844,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1844
1844
  for (const [key, value] of Object.entries(params || {})) {
1845
1845
  const path = base ? [...base, key] : [key]
1846
1846
  if (typeof value === 'number') out.push({ path, label: path.join('.'), kind: 'num', value })
1847
+ // Selector params are strings (axis/mode/dir/type). They must be
1848
+ // editable too, otherwise "dir: + -> -" needs a JSON edit.
1849
+ else if (typeof value === 'string') out.push({ path, label: path.join('.'), kind: 'text', value })
1847
1850
  else if (Array.isArray(value) && value.every((v) => typeof v === 'number')) out.push({ path, label: path.join('.'), kind: 'vec', value })
1848
- else if (value && typeof value === 'object' && !Array.isArray(value) && path.length < 2) {
1851
+ else if (value && typeof value === 'object' && !Array.isArray(value) && path.length < 3) {
1849
1852
  // A nested op (`cut.with` = a cylinder) is editable too: drop its
1850
1853
  // kind (you switch shapes by replacing the feature) and expose the
1851
1854
  // numbers that matter — r, h, at.
package/index.js CHANGED
@@ -900,6 +900,105 @@ def _prim(op):
900
900
  return Part.Face(Part.makePolygon(ps + [ps[0]])).revolve(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), ang)
901
901
  raise RuntimeError("未知图元:" + str(k))
902
902
 
903
+ # ---- sub-shape selectors -------------------------------------------------
904
+ # Predicates over geometry, re-evaluated on every rebuild. No persistent ids:
905
+ # OCCT regenerates topology on each operation, so "the 7th face" is not a name.
906
+ # Failure is loud: an empty match raises with the spec and the item counts.
907
+ def _axis_of(_spec):
908
+ _a = _spec.get("axis", "Z")
909
+ if isinstance(_a, (list, tuple)):
910
+ return Vector(float(_a[0]), float(_a[1]), float(_a[2]))
911
+ _v = {"X": Vector(1.0, 0.0, 0.0), "Y": Vector(0.0, 1.0, 0.0), "Z": Vector(0.0, 0.0, 1.0)}.get(str(_a).upper())
912
+ if _v is None:
913
+ raise RuntimeError("选择器的 axis 只能是 X/Y/Z 或 [x,y,z]:%s" % str(_a))
914
+ return _v
915
+
916
+
917
+ def _unit(_v):
918
+ _n = (_v.x * _v.x + _v.y * _v.y + _v.z * _v.z) ** 0.5
919
+ if _n < 1e-12:
920
+ raise RuntimeError("选择器的方向长度为 0")
921
+ return Vector(_v.x / _n, _v.y / _n, _v.z / _n)
922
+
923
+
924
+ def _dot(_a, _b):
925
+ return float(_a.x * _b.x + _a.y * _b.y + _a.z * _b.z)
926
+
927
+
928
+ def _match_dir(_d, _ax, _mode, _sign):
929
+ _u = _unit(_d)
930
+ _a = _unit(_ax)
931
+ _c = _dot(_u, _a)
932
+ if _mode == "parallel":
933
+ return abs(abs(_c) - 1.0) < 1e-3
934
+ if _mode == "perpendicular":
935
+ return abs(_c) < 1e-3
936
+ return _c > 0.999 if _sign != "-" else _c < -0.999
937
+
938
+
939
+ def _center_of(_it):
940
+ _b = _it.BoundBox
941
+ return Vector((_b.XMin + _b.XMax) / 2.0, (_b.YMin + _b.YMax) / 2.0, (_b.ZMin + _b.ZMax) / 2.0)
942
+
943
+
944
+ def _sel(_shape, _kind, _spec):
945
+ if not _spec:
946
+ return []
947
+ if not isinstance(_spec, dict):
948
+ raise RuntimeError("选择器必须是对象:%s" % str(_spec))
949
+ _ax = _axis_of(_spec)
950
+ _mode = _spec.get("mode", "parallel")
951
+ _sign = _spec.get("dir", "+")
952
+ _tol = float(_spec.get("tol", 0.5))
953
+ _want = _spec.get("type")
954
+ _items = list(_shape.Edges) if _kind == "edge" else list(_shape.Faces)
955
+ _word = "条边" if _kind == "edge" else "个面"
956
+ _out = []
957
+ for _it in _items:
958
+ if _want:
959
+ _cls = (_it.Curve.__class__.__name__ if _kind == "edge" else _it.Surface.__class__.__name__).lower()
960
+ if str(_want).lower() not in _cls:
961
+ continue
962
+ if _kind == "edge":
963
+ try:
964
+ _d = _it.tangentAt(_it.FirstParameter)
965
+ except Exception:
966
+ _d = getattr(_it.Curve, "Direction", None)
967
+ if _d is None:
968
+ continue
969
+ else:
970
+ try:
971
+ _d = _it.normalAt(0.5, 0.5)
972
+ except Exception:
973
+ continue
974
+ if not _match_dir(_d, _ax, _mode, _sign):
975
+ continue
976
+ if _spec.get("radius") is not None and _kind == "edge":
977
+ _r = getattr(_it.Curve, "Radius", None)
978
+ if _r is None or abs(float(_r) - float(_spec["radius"])) > _tol:
979
+ continue
980
+ _out.append(_it)
981
+ if not _out:
982
+ raise RuntimeError("选择器没有选中任何%s:%s(当前形状有 %d %s)" % (
983
+ "边" if _kind == "edge" else "面", json.dumps(_spec, ensure_ascii=False), len(_items), _word))
984
+ if _spec.get("near") is not None:
985
+ _p = _v3(_spec["near"])
986
+ _out.sort(key=lambda _it: (_center_of(_it) - _p).Length)
987
+ elif _spec.get("pick") in ("max", "min"):
988
+ _a = _unit(_ax)
989
+ _rev = _spec["pick"] == "max"
990
+ _out.sort(key=lambda _it: _dot(_center_of(_it), _a), reverse=_rev)
991
+ if _spec.get("nth") is not None:
992
+ _i = int(_spec["nth"])
993
+ _out = _out[_i:_i + 1]
994
+ elif _spec.get("pick") in ("max", "min", "near"):
995
+ _out = _out[:1]
996
+ if _spec.get("one") and len(_out) != 1:
997
+ raise RuntimeError("选择器命中了 %d %s,但要求恰好 1 个:%s" % (
998
+ len(_out), _word, json.dumps(_spec, ensure_ascii=False)))
999
+ return _out
1000
+
1001
+
903
1002
  _shape = None
904
1003
  _errors = []
905
1004
  _executed = 0
@@ -922,12 +1021,44 @@ for _idx, _op in enumerate(_OPS):
922
1021
  _s = _prim(_w)
923
1022
  _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
924
1023
  elif _k == "fillet":
925
- _shape = _shape.makeFillet(float(_op["r"]), _shape.Edges)
1024
+ _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
1025
+ _shape = _shape.makeFillet(float(_op["r"]), _eds)
926
1026
  elif _k == "chamfer":
927
- _shape = _shape.makeChamfer(float(_op["d"]), _shape.Edges)
1027
+ _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
1028
+ _shape = _shape.makeChamfer(float(_op["d"]), _eds)
928
1029
  elif _k == "shell":
929
1030
  _t = float(_op["t"])
930
1031
  _open = _op.get("open", "none")
1032
+ _open_faces = _sel(_shape, "face", _op.get("faces"))
1033
+ if _open_faces:
1034
+ # Hollow, then cut a prism outward from each chosen face. FreeCAD
1035
+ # 0.20's Part module has no makeThickSolid*; extruding the face
1036
+ # along its own normal is the portable equivalent and keeps the
1037
+ # opening exactly where the selector pointed.
1038
+ _hollow = _shape.makeOffsetShape(-_t, 1e-6)
1039
+ _shell = _shape.cut(_hollow)
1040
+ _far = (_shape.BoundBox.DiagonalLength or 100.0) * 2.0
1041
+ for _f in _open_faces:
1042
+ _cls = _f.Surface.__class__.__name__
1043
+ if _cls != "Plane":
1044
+ raise RuntimeError("shell 的 faces 选择器目前只支持平面(收到 %s)" % _cls)
1045
+ _nrm = _unit(_f.normalAt(0.5, 0.5))
1046
+ # Outward = away from the solid's centre of mass. A face's
1047
+ # stored orientation can point inward; cutting inward would
1048
+ # remove nothing (the interior is already hollow), and
1049
+ # cutting both ways would punch a hole clean through.
1050
+ _away = _center_of(_f) - _shape.CenterOfMass
1051
+ if _dot(_nrm, _away) < 0:
1052
+ _nrm = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
1053
+ # Cut the wall itself: start a hair outside the plane and go
1054
+ # inward by exactly the wall thickness. Extruding *outward*
1055
+ # would graze the face and remove nothing.
1056
+ _inn = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
1057
+ _pr = _f.translated(_nrm * 0.01).extrude(_inn * (_t + 0.02))
1058
+ _shell = _shell.cut(_pr)
1059
+ _shape = _shell
1060
+ _executed = _idx + 1
1061
+ continue
931
1062
  _inner = _shape.makeOffsetShape(-_t, 1e-6)
932
1063
  _shell = _shape.cut(_inner)
933
1064
  if _open in ("top", "bottom"):
@@ -2216,6 +2347,7 @@ if _TARGET:
2216
2347
  await writeModel(doc, dir)
2217
2348
  return {
2218
2349
  ok: true,
2350
+ evaluated: !(Array.isArray(out.errors) && out.errors.length > 0),
2219
2351
  name: doc.name,
2220
2352
  dir,
2221
2353
  graph,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {