dsh-cad-studio 0.5.0 → 0.7.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.
- package/README.md +25 -0
- package/client.js +6 -2
- package/index.js +279 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -56,6 +56,31 @@ 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
|
+
|
|
72
|
+
## 增量重算
|
|
73
|
+
|
|
74
|
+
改一条特征不需要重跑整条链:每一步的 BREP 快照按「前缀哈希」缓存在 `$TMPDIR/dsh-cad-studio/cache/`,重算从最深命中的前缀恢复。
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
首次 17 条特征 354 ms
|
|
78
|
+
无改动的重建 1 ms (完全不起内核进程,revalidated: true)
|
|
79
|
+
只改最后一条 264 ms (16/17 来自缓存)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
面板的特征页头会显示 `· 缓存 16/17`。缓存按 400 文件 / 14 天淘汰;`EMITTER_VERSION` 一变即整体失效(防止旧快照复活错误几何)。
|
|
83
|
+
|
|
59
84
|
## 接口约定与踩过的坑
|
|
60
85
|
|
|
61
86
|
- **导出只走 `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
|
@@ -1749,6 +1749,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1749
1749
|
// the new scene replaces the old one in the tab being looked at.
|
|
1750
1750
|
const featureList = payload && Array.isArray(payload.features) ? payload.features : []
|
|
1751
1751
|
const featureModel = (payload && payload.model) || ''
|
|
1752
|
+
const cacheChip = payload && payload.cache && payload.cache.cached > 0 ? payload.cache : null
|
|
1752
1753
|
// A script model publishes its params (no feature list); they are editable
|
|
1753
1754
|
// the same way — one number, one rebuild of the same document.
|
|
1754
1755
|
const modelParams = payload && payload.params && typeof payload.params === 'object' ? payload.params : {}
|
|
@@ -1844,8 +1845,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1844
1845
|
for (const [key, value] of Object.entries(params || {})) {
|
|
1845
1846
|
const path = base ? [...base, key] : [key]
|
|
1846
1847
|
if (typeof value === 'number') out.push({ path, label: path.join('.'), kind: 'num', value })
|
|
1848
|
+
// Selector params are strings (axis/mode/dir/type). They must be
|
|
1849
|
+
// editable too, otherwise "dir: + -> -" needs a JSON edit.
|
|
1850
|
+
else if (typeof value === 'string') out.push({ path, label: path.join('.'), kind: 'text', value })
|
|
1847
1851
|
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 <
|
|
1852
|
+
else if (value && typeof value === 'object' && !Array.isArray(value) && path.length < 3) {
|
|
1849
1853
|
// A nested op (`cut.with` = a cylinder) is editable too: drop its
|
|
1850
1854
|
// kind (you switch shapes by replacing the feature) and expose the
|
|
1851
1855
|
// numbers that matter — r, h, at.
|
|
@@ -1927,7 +1931,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1927
1931
|
: '当前场景不是特征模型。用 cad_studio_doc create kind="features" 建一个(features 里每个 {kind,params}),就能在这里逐条改数值。')]
|
|
1928
1932
|
: [
|
|
1929
1933
|
h('div', { key: 'h', style: { ...styles.treeHint, display: 'flex', gap: 6, alignItems: 'center' } }, [
|
|
1930
|
-
h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, `${featureModel} · ${featureList.length}
|
|
1934
|
+
h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', title: cacheChip ? `本次重算:${cacheChip.cached}/${cacheChip.of} 步来自缓存` : undefined } }, `${featureModel} · ${featureList.length} 特征${cacheChip ? ` · 缓存 ${cacheChip.cached}/${cacheChip.of}` : ''}`),
|
|
1931
1935
|
h('button', {
|
|
1932
1936
|
key: 'a',
|
|
1933
1937
|
type: 'button',
|
package/index.js
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
* GET /cad-studio/client.js the panel bundle (dev-mode serving)
|
|
15
15
|
*/
|
|
16
16
|
import { spawn, spawnSync } from 'node:child_process'
|
|
17
|
-
import { existsSync } from 'node:fs'
|
|
17
|
+
import { existsSync, readdirSync, statSync, rmSync } from 'node:fs'
|
|
18
|
+
import crypto from 'node:crypto'
|
|
18
19
|
import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
|
19
20
|
import { tmpdir } from 'node:os'
|
|
20
21
|
import { fileURLToPath } from 'node:url'
|
|
@@ -855,10 +856,58 @@ def describe(path):
|
|
|
855
856
|
* `kind:'features'` model document — so a typed list and an edited-and-rebuilt
|
|
856
857
|
* one cannot drift apart.
|
|
857
858
|
*/
|
|
858
|
-
|
|
859
|
+
/**
|
|
860
|
+
* Bump whenever the emitter's meaning changes: the BREP cache is keyed by
|
|
861
|
+
* (version, op-chain), so a stale entry from an older emitter would silently
|
|
862
|
+
* resurrect wrong geometry.
|
|
863
|
+
*/
|
|
864
|
+
const EMITTER_VERSION = 'e1'
|
|
865
|
+
|
|
866
|
+
/** One hash per prefix: hashes[i] = ops[0..i] applied. Skip markers reuse the
|
|
867
|
+
* previous hash, so toggling a suppressed feature does not invalidate
|
|
868
|
+
* anything upstream of it. */
|
|
869
|
+
function chainHashes(ops) {
|
|
870
|
+
const out = []
|
|
871
|
+
let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).digest('hex').slice(0, 16)
|
|
872
|
+
for (const op of Array.isArray(ops) ? ops : []) {
|
|
873
|
+
if (op && op.kind === '__skip__') { out.push(h); continue }
|
|
874
|
+
const bare = { ...op }
|
|
875
|
+
delete bare._id
|
|
876
|
+
delete bare._label
|
|
877
|
+
h = crypto.createHash('sha1').update(h).update(JSON.stringify(bare)).digest('hex').slice(0, 16)
|
|
878
|
+
out.push(h)
|
|
879
|
+
}
|
|
880
|
+
return out
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function brepCacheDir() { return join(FreeCadBridge.dataDir, 'cache') }
|
|
884
|
+
|
|
885
|
+
/** Content-addressed BREP snapshots are cheap to keep and cheap to prune:
|
|
886
|
+
* drop them oldest-first once the directory grows past a cap. */
|
|
887
|
+
function pruneBrepCache(dir, { maxFiles = 400, maxAgeDays = 14 } = {}) {
|
|
888
|
+
let names = []
|
|
889
|
+
try { names = readdirSync(dir).filter((n) => /^f_[0-9a-f]{16}\.brep$/.test(n)) } catch { return 0 }
|
|
890
|
+
const now = Date.now()
|
|
891
|
+
const kept = []
|
|
892
|
+
for (const n of names) {
|
|
893
|
+
try {
|
|
894
|
+
const st = statSync(join(dir, n))
|
|
895
|
+
if (now - st.mtimeMs > maxAgeDays * 86400_000) rmSync(join(dir, n), { force: true })
|
|
896
|
+
else kept.push({ n, at: st.mtimeMs })
|
|
897
|
+
} catch {}
|
|
898
|
+
}
|
|
899
|
+
kept.sort((a, b) => b.at - a.at)
|
|
900
|
+
let dropped = 0
|
|
901
|
+
for (const { n } of kept.slice(maxFiles)) { try { rmSync(join(dir, n), { force: true }); dropped += 1 } catch {} }
|
|
902
|
+
return dropped
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
const featuresScript = (ops, exportPath, opts = {}) => `${PRELUDE}
|
|
859
906
|
import os
|
|
860
907
|
_OPS = json.loads(${JSON.stringify(JSON.stringify(Array.isArray(ops) ? ops : []))})
|
|
861
908
|
_EXPORT = ${exportPath ? JSON.stringify(exportPath) : 'None'}
|
|
909
|
+
_CACHE = json.loads(${JSON.stringify(JSON.stringify(opts.cache && opts.cache.hashes ? { dir: opts.cache.dir, hashes: opts.cache.hashes } : null))})
|
|
910
|
+
_RESUME = json.loads(${JSON.stringify(JSON.stringify(opts.resume && opts.resume.brep ? { index: opts.resume.index, brep: opts.resume.brep } : null))})
|
|
862
911
|
|
|
863
912
|
def _v3(x, d=(0.0, 0.0, 0.0)):
|
|
864
913
|
if not x:
|
|
@@ -900,10 +949,140 @@ def _prim(op):
|
|
|
900
949
|
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
950
|
raise RuntimeError("未知图元:" + str(k))
|
|
902
951
|
|
|
952
|
+
# ---- sub-shape selectors -------------------------------------------------
|
|
953
|
+
# Predicates over geometry, re-evaluated on every rebuild. No persistent ids:
|
|
954
|
+
# OCCT regenerates topology on each operation, so "the 7th face" is not a name.
|
|
955
|
+
# Failure is loud: an empty match raises with the spec and the item counts.
|
|
956
|
+
def _axis_of(_spec):
|
|
957
|
+
_a = _spec.get("axis", "Z")
|
|
958
|
+
if isinstance(_a, (list, tuple)):
|
|
959
|
+
return Vector(float(_a[0]), float(_a[1]), float(_a[2]))
|
|
960
|
+
_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())
|
|
961
|
+
if _v is None:
|
|
962
|
+
raise RuntimeError("选择器的 axis 只能是 X/Y/Z 或 [x,y,z]:%s" % str(_a))
|
|
963
|
+
return _v
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def _unit(_v):
|
|
967
|
+
_n = (_v.x * _v.x + _v.y * _v.y + _v.z * _v.z) ** 0.5
|
|
968
|
+
if _n < 1e-12:
|
|
969
|
+
raise RuntimeError("选择器的方向长度为 0")
|
|
970
|
+
return Vector(_v.x / _n, _v.y / _n, _v.z / _n)
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _dot(_a, _b):
|
|
974
|
+
return float(_a.x * _b.x + _a.y * _b.y + _a.z * _b.z)
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _match_dir(_d, _ax, _mode, _sign):
|
|
978
|
+
_u = _unit(_d)
|
|
979
|
+
_a = _unit(_ax)
|
|
980
|
+
_c = _dot(_u, _a)
|
|
981
|
+
if _mode == "parallel":
|
|
982
|
+
return abs(abs(_c) - 1.0) < 1e-3
|
|
983
|
+
if _mode == "perpendicular":
|
|
984
|
+
return abs(_c) < 1e-3
|
|
985
|
+
return _c > 0.999 if _sign != "-" else _c < -0.999
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def _core_of(s):
|
|
989
|
+
# A shape read back from a BREP cache is a Compound, and Compound has no
|
|
990
|
+
# CenterOfMass (only Solid does) — use the lone solid when there is one and
|
|
991
|
+
# the bounding box otherwise. It only has to be a point *inside* the body.
|
|
992
|
+
try:
|
|
993
|
+
if len(s.Solids) == 1:
|
|
994
|
+
return s.Solids[0].CenterOfMass
|
|
995
|
+
except Exception:
|
|
996
|
+
pass
|
|
997
|
+
try:
|
|
998
|
+
return s.BoundBox.Center
|
|
999
|
+
except Exception:
|
|
1000
|
+
return Vector(0.0, 0.0, 0.0)
|
|
1001
|
+
|
|
1002
|
+
def _center_of(_it):
|
|
1003
|
+
_b = _it.BoundBox
|
|
1004
|
+
return Vector((_b.XMin + _b.XMax) / 2.0, (_b.YMin + _b.YMax) / 2.0, (_b.ZMin + _b.ZMax) / 2.0)
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def _sel(_shape, _kind, _spec):
|
|
1008
|
+
if not _spec:
|
|
1009
|
+
return []
|
|
1010
|
+
if not isinstance(_spec, dict):
|
|
1011
|
+
raise RuntimeError("选择器必须是对象:%s" % str(_spec))
|
|
1012
|
+
_ax = _axis_of(_spec)
|
|
1013
|
+
_mode = _spec.get("mode", "parallel")
|
|
1014
|
+
_sign = _spec.get("dir", "+")
|
|
1015
|
+
_tol = float(_spec.get("tol", 0.5))
|
|
1016
|
+
_want = _spec.get("type")
|
|
1017
|
+
_items = list(_shape.Edges) if _kind == "edge" else list(_shape.Faces)
|
|
1018
|
+
_word = "条边" if _kind == "edge" else "个面"
|
|
1019
|
+
_out = []
|
|
1020
|
+
for _it in _items:
|
|
1021
|
+
if _want:
|
|
1022
|
+
_cls = (_it.Curve.__class__.__name__ if _kind == "edge" else _it.Surface.__class__.__name__).lower()
|
|
1023
|
+
if str(_want).lower() not in _cls:
|
|
1024
|
+
continue
|
|
1025
|
+
if _kind == "edge":
|
|
1026
|
+
try:
|
|
1027
|
+
_d = _it.tangentAt(_it.FirstParameter)
|
|
1028
|
+
except Exception:
|
|
1029
|
+
_d = getattr(_it.Curve, "Direction", None)
|
|
1030
|
+
if _d is None:
|
|
1031
|
+
continue
|
|
1032
|
+
else:
|
|
1033
|
+
try:
|
|
1034
|
+
_d = _it.normalAt(0.5, 0.5)
|
|
1035
|
+
except Exception:
|
|
1036
|
+
continue
|
|
1037
|
+
if not _match_dir(_d, _ax, _mode, _sign):
|
|
1038
|
+
continue
|
|
1039
|
+
if _spec.get("radius") is not None and _kind == "edge":
|
|
1040
|
+
_r = getattr(_it.Curve, "Radius", None)
|
|
1041
|
+
if _r is None or abs(float(_r) - float(_spec["radius"])) > _tol:
|
|
1042
|
+
continue
|
|
1043
|
+
_out.append(_it)
|
|
1044
|
+
if not _out:
|
|
1045
|
+
raise RuntimeError("选择器没有选中任何%s:%s(当前形状有 %d %s)" % (
|
|
1046
|
+
"边" if _kind == "edge" else "面", json.dumps(_spec, ensure_ascii=False), len(_items), _word))
|
|
1047
|
+
if _spec.get("near") is not None:
|
|
1048
|
+
_p = _v3(_spec["near"])
|
|
1049
|
+
_out.sort(key=lambda _it: (_center_of(_it) - _p).Length)
|
|
1050
|
+
elif _spec.get("pick") in ("max", "min"):
|
|
1051
|
+
_a = _unit(_ax)
|
|
1052
|
+
_rev = _spec["pick"] == "max"
|
|
1053
|
+
_out.sort(key=lambda _it: _dot(_center_of(_it), _a), reverse=_rev)
|
|
1054
|
+
if _spec.get("nth") is not None:
|
|
1055
|
+
_i = int(_spec["nth"])
|
|
1056
|
+
_out = _out[_i:_i + 1]
|
|
1057
|
+
elif _spec.get("pick") in ("max", "min", "near"):
|
|
1058
|
+
_out = _out[:1]
|
|
1059
|
+
if _spec.get("one") and len(_out) != 1:
|
|
1060
|
+
raise RuntimeError("选择器命中了 %d %s,但要求恰好 1 个:%s" % (
|
|
1061
|
+
len(_out), _word, json.dumps(_spec, ensure_ascii=False)))
|
|
1062
|
+
return _out
|
|
1063
|
+
|
|
1064
|
+
|
|
903
1065
|
_shape = None
|
|
904
1066
|
_errors = []
|
|
905
1067
|
_executed = 0
|
|
1068
|
+
_start = 0
|
|
1069
|
+
# Incremental recompute: resume from the deepest cached prefix instead of
|
|
1070
|
+
# replaying the whole chain. The cache is content-addressed by the op chain,
|
|
1071
|
+
# so an entry is only used when every upstream feature is byte-identical.
|
|
1072
|
+
if _RESUME and os.path.exists(_RESUME["brep"]):
|
|
1073
|
+
try:
|
|
1074
|
+
_cached = Part.Shape()
|
|
1075
|
+
_cached.read(_RESUME["brep"])
|
|
1076
|
+
if _cached.isValid() and not _cached.isNull():
|
|
1077
|
+
_shape = _cached
|
|
1078
|
+
_start = int(_RESUME["index"])
|
|
1079
|
+
_executed = _start
|
|
1080
|
+
except Exception as _e:
|
|
1081
|
+
_shape = None
|
|
1082
|
+
_start = 0
|
|
906
1083
|
for _idx, _op in enumerate(_OPS):
|
|
1084
|
+
if _idx < _start:
|
|
1085
|
+
continue
|
|
907
1086
|
_k = _op.get("kind")
|
|
908
1087
|
if _k == "__skip__":
|
|
909
1088
|
continue
|
|
@@ -922,12 +1101,44 @@ for _idx, _op in enumerate(_OPS):
|
|
|
922
1101
|
_s = _prim(_w)
|
|
923
1102
|
_shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
|
|
924
1103
|
elif _k == "fillet":
|
|
925
|
-
|
|
1104
|
+
_eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
|
|
1105
|
+
_shape = _shape.makeFillet(float(_op["r"]), _eds)
|
|
926
1106
|
elif _k == "chamfer":
|
|
927
|
-
|
|
1107
|
+
_eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
|
|
1108
|
+
_shape = _shape.makeChamfer(float(_op["d"]), _eds)
|
|
928
1109
|
elif _k == "shell":
|
|
929
1110
|
_t = float(_op["t"])
|
|
930
1111
|
_open = _op.get("open", "none")
|
|
1112
|
+
_open_faces = _sel(_shape, "face", _op.get("faces"))
|
|
1113
|
+
if _open_faces:
|
|
1114
|
+
# Hollow, then cut a prism outward from each chosen face. FreeCAD
|
|
1115
|
+
# 0.20's Part module has no makeThickSolid*; extruding the face
|
|
1116
|
+
# along its own normal is the portable equivalent and keeps the
|
|
1117
|
+
# opening exactly where the selector pointed.
|
|
1118
|
+
_hollow = _shape.makeOffsetShape(-_t, 1e-6)
|
|
1119
|
+
_shell = _shape.cut(_hollow)
|
|
1120
|
+
_far = (_shape.BoundBox.DiagonalLength or 100.0) * 2.0
|
|
1121
|
+
for _f in _open_faces:
|
|
1122
|
+
_cls = _f.Surface.__class__.__name__
|
|
1123
|
+
if _cls != "Plane":
|
|
1124
|
+
raise RuntimeError("shell 的 faces 选择器目前只支持平面(收到 %s)" % _cls)
|
|
1125
|
+
_nrm = _unit(_f.normalAt(0.5, 0.5))
|
|
1126
|
+
# Outward = away from the solid's centre of mass. A face's
|
|
1127
|
+
# stored orientation can point inward; cutting inward would
|
|
1128
|
+
# remove nothing (the interior is already hollow), and
|
|
1129
|
+
# cutting both ways would punch a hole clean through.
|
|
1130
|
+
_away = _center_of(_f) - _core_of(_shape)
|
|
1131
|
+
if _dot(_nrm, _away) < 0:
|
|
1132
|
+
_nrm = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
|
|
1133
|
+
# Cut the wall itself: start a hair outside the plane and go
|
|
1134
|
+
# inward by exactly the wall thickness. Extruding *outward*
|
|
1135
|
+
# would graze the face and remove nothing.
|
|
1136
|
+
_inn = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
|
|
1137
|
+
_pr = _f.translated(_nrm * 0.01).extrude(_inn * (_t + 0.02))
|
|
1138
|
+
_shell = _shell.cut(_pr)
|
|
1139
|
+
_shape = _shell
|
|
1140
|
+
_executed = _idx + 1
|
|
1141
|
+
continue
|
|
931
1142
|
_inner = _shape.makeOffsetShape(-_t, 1e-6)
|
|
932
1143
|
_shell = _shape.cut(_inner)
|
|
933
1144
|
if _open in ("top", "bottom"):
|
|
@@ -975,6 +1186,15 @@ for _idx, _op in enumerate(_OPS):
|
|
|
975
1186
|
})
|
|
976
1187
|
break
|
|
977
1188
|
_executed = _idx + 1
|
|
1189
|
+
if _CACHE and _idx < len(_CACHE.get("hashes") or []):
|
|
1190
|
+
try:
|
|
1191
|
+
_p = os.path.join(_CACHE["dir"], "f_%s.brep" % _CACHE["hashes"][_idx])
|
|
1192
|
+
if not os.path.exists(_p):
|
|
1193
|
+
_tmp = "%s.tmp%d" % (_p, os.getpid())
|
|
1194
|
+
_shape.exportBrep(_tmp)
|
|
1195
|
+
os.replace(_tmp, _p)
|
|
1196
|
+
except Exception:
|
|
1197
|
+
pass
|
|
978
1198
|
|
|
979
1199
|
if _shape is None:
|
|
980
1200
|
raise RuntimeError(_errors[0]["message"] if _errors else "ops 为空:至少给一个图元")
|
|
@@ -983,6 +1203,8 @@ scene = _shape
|
|
|
983
1203
|
__out = {
|
|
984
1204
|
"ok": True,
|
|
985
1205
|
"features": len(_OPS),
|
|
1206
|
+
"cached": _start,
|
|
1207
|
+
"computed": max(0, _executed - _start),
|
|
986
1208
|
"volume": round(_shape.Volume, 3),
|
|
987
1209
|
"area": round(_shape.Area, 3),
|
|
988
1210
|
"faces": len(_shape.Faces),
|
|
@@ -2021,7 +2243,13 @@ if _TARGET:
|
|
|
2021
2243
|
doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
|
|
2022
2244
|
doc.undo = Array.isArray(doc.undo) ? doc.undo : []
|
|
2023
2245
|
doc.redo = Array.isArray(doc.redo) ? doc.redo : []
|
|
2024
|
-
for (const f of doc.features)
|
|
2246
|
+
for (const f of doc.features) {
|
|
2247
|
+
if (!f || typeof f !== 'object') continue
|
|
2248
|
+
if (typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
|
|
2249
|
+
// Older docs picked up a stray params.suppressed from a normalizer bug;
|
|
2250
|
+
// it changed the op hash for no geometric reason, so drop it on read.
|
|
2251
|
+
if (f.params && typeof f.params === 'object' && 'suppressed' in f.params) delete f.params.suppressed
|
|
2252
|
+
}
|
|
2025
2253
|
return doc
|
|
2026
2254
|
}
|
|
2027
2255
|
|
|
@@ -2080,7 +2308,7 @@ if _TARGET:
|
|
|
2080
2308
|
return ops
|
|
2081
2309
|
}
|
|
2082
2310
|
|
|
2083
|
-
const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
|
|
2311
|
+
const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled', 'suppressed']
|
|
2084
2312
|
|
|
2085
2313
|
/**
|
|
2086
2314
|
* Accept both shapes: `{kind:'box', params:{size:…}}` and the flatter
|
|
@@ -2179,8 +2407,37 @@ if _TARGET:
|
|
|
2179
2407
|
|
|
2180
2408
|
const rebuild = async (doc, dir, { note } = {}) => {
|
|
2181
2409
|
const isFeatures = doc.kind === 'features'
|
|
2410
|
+
// Incremental recompute (DESIGN §5.3): hash the op chain once, find the
|
|
2411
|
+
// deepest BREP prefix already on disk, and let the kernel start there.
|
|
2412
|
+
// A rebuild of an unchanged document skips the kernel entirely.
|
|
2413
|
+
let cache = null
|
|
2414
|
+
let resume = null
|
|
2415
|
+
let hashes = []
|
|
2416
|
+
if (isFeatures) {
|
|
2417
|
+
const ops = featureOps(doc)
|
|
2418
|
+
hashes = chainHashes(ops)
|
|
2419
|
+
const cacheDir = brepCacheDir()
|
|
2420
|
+
try { await mkdir(cacheDir, { recursive: true }) } catch {}
|
|
2421
|
+
cache = { dir: cacheDir, hashes }
|
|
2422
|
+
for (let k = hashes.length - 1; k >= 0; k -= 1) {
|
|
2423
|
+
const candidate = join(cacheDir, `f_${hashes[k]}.brep`)
|
|
2424
|
+
if (existsSync(candidate)) { resume = { index: k + 1, brep: candidate }; break }
|
|
2425
|
+
}
|
|
2426
|
+
const fullHash = hashes[hashes.length - 1] ?? ''
|
|
2427
|
+
const keep = doc.stats?.sceneId && bridge.scenes?.has(doc.stats.sceneId)
|
|
2428
|
+
if (fullHash && keep && doc.stats?.hash === fullHash) {
|
|
2429
|
+
// Nothing changed and the scene is still live: no kernel run at all.
|
|
2430
|
+
return {
|
|
2431
|
+
ok: true, evaluated: true, cached: hashes.length, computed: 0, name: doc.name, dir,
|
|
2432
|
+
graph: graphView(doc, { errors: [], executed: hashes.length }),
|
|
2433
|
+
errors: [], run: doc.run, params: doc.params, volume: doc.stats.volume,
|
|
2434
|
+
triangles: doc.stats.triangles, sceneId: doc.stats.sceneId, bounds: doc.stats.bounds,
|
|
2435
|
+
note: doc.note, revalidated: true,
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2182
2439
|
const code = isFeatures
|
|
2183
|
-
? featuresScript(featureOps(doc))
|
|
2440
|
+
? featuresScript(featureOps(doc), null, { cache, resume })
|
|
2184
2441
|
: `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
|
|
2185
2442
|
const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
|
|
2186
2443
|
doc.run = (doc.run ?? 0) + 1
|
|
@@ -2203,6 +2460,8 @@ if _TARGET:
|
|
|
2203
2460
|
bounds: out.bounds ?? null,
|
|
2204
2461
|
sceneId,
|
|
2205
2462
|
at: doc.updatedAt,
|
|
2463
|
+
hash: hashes[hashes.length - 1] ?? '',
|
|
2464
|
+
cached: out.cached ?? 0,
|
|
2206
2465
|
}
|
|
2207
2466
|
if (note) doc.note = note
|
|
2208
2467
|
// The scene was published before the kernel reported which nodes failed, so
|
|
@@ -2211,14 +2470,23 @@ if _TARGET:
|
|
|
2211
2470
|
const scene = sceneId ? bridge.scenes?.get(sceneId) : null
|
|
2212
2471
|
if (scene) {
|
|
2213
2472
|
scene.graph = graph
|
|
2473
|
+
scene.cache = { cached: out.cached ?? 0, computed: out.computed ?? null, of: hashes.length }
|
|
2214
2474
|
try { await bridge.persist() } catch {}
|
|
2215
2475
|
}
|
|
2216
2476
|
await writeModel(doc, dir)
|
|
2477
|
+
if (isFeatures && hashes.length) {
|
|
2478
|
+
// Cheap housekeeping, off the hot path: a 400-file / 14-day cap keeps the
|
|
2479
|
+
// cache from growing without bound in a long-lived install.
|
|
2480
|
+
try { pruneBrepCache(brepCacheDir()) } catch {}
|
|
2481
|
+
}
|
|
2217
2482
|
return {
|
|
2218
2483
|
ok: true,
|
|
2484
|
+
evaluated: !(Array.isArray(out.errors) && out.errors.length > 0),
|
|
2219
2485
|
name: doc.name,
|
|
2220
2486
|
dir,
|
|
2221
2487
|
graph,
|
|
2488
|
+
cached: out.cached ?? 0,
|
|
2489
|
+
computed: out.computed ?? null,
|
|
2222
2490
|
errors: Array.isArray(out.errors) ? out.errors : [],
|
|
2223
2491
|
run: doc.run,
|
|
2224
2492
|
params: doc.params,
|
|
@@ -2398,6 +2666,10 @@ if _TARGET:
|
|
|
2398
2666
|
triangles: doc.stats?.triangles ?? null,
|
|
2399
2667
|
sceneId: doc.stats?.sceneId ?? '',
|
|
2400
2668
|
run: doc.run,
|
|
2669
|
+
// How much of the chain came from the BREP cache vs the kernel this time.
|
|
2670
|
+
cached: result.cached ?? doc.stats?.cached ?? 0,
|
|
2671
|
+
computed: result.computed ?? null,
|
|
2672
|
+
revalidated: result.revalidated === true,
|
|
2401
2673
|
}
|
|
2402
2674
|
}
|
|
2403
2675
|
|