dsh-macro-memory 0.0.0-stage → 0.4.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 (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +506 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +502 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +442 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +160 -0
  16. package/lib/macro/defs/remember.js +411 -0
  17. package/lib/macro/defs/search.js +871 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/supersede.js +197 -0
  33. package/lib/macro/tokencost.js +90 -0
  34. package/lib/macro/tools.js +67 -0
  35. package/package.json +54 -4
  36. package/vendor/VENDOR.json +23 -0
  37. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  38. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  39. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  40. package/vendor/dsh-memory-nebula/README.md +253 -0
  41. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  42. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  43. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  44. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  50. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  51. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  52. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  53. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  54. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  55. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  56. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  57. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  58. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  59. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  60. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  61. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  62. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  63. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  64. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  65. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  66. package/vendor/dsh-memory-nebula/lib/host/recall.js +524 -0
  67. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  68. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  69. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  70. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  71. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  72. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  73. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  74. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  75. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  76. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  77. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  78. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  79. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  80. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  81. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  82. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  83. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  84. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  85. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  86. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  87. package/vendor/dsh-memory-nebula/package.json +87 -0
  88. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  89. package/vendor/meow-memory/LICENSE +21 -0
  90. package/vendor/meow-memory/README.en.md +192 -0
  91. package/vendor/meow-memory/README.md +174 -0
  92. package/vendor/meow-memory/README.pt-br.md +180 -0
  93. package/vendor/meow-memory/cordis.patch.yml +7 -0
  94. package/vendor/meow-memory/lib/client.js +3344 -0
  95. package/vendor/meow-memory/lib/client.js.map +7 -0
  96. package/vendor/meow-memory/lib/index.js +9802 -0
  97. package/vendor/meow-memory/lib/index.js.map +7 -0
  98. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  101. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  102. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  103. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  104. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  105. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  106. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  107. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  108. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  109. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  119. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  120. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  123. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  124. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  125. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  126. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  127. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  128. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  129. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  130. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  131. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  132. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,1883 @@
1
+ /* 宏记忆 · 星图 · 星系视图(WebGL,零依赖,真三维)
2
+ *
3
+ * 两副「三维透镜」,共用一个渲染器:
4
+ * layout = 'cluster' —— 三维力导向星系。簇心给弱引力、边给弹簧、节点互相排斥,
5
+ * 结构由真实连接决定;重要度越高的记忆越贴簇核。
6
+ * layout = 'spiral' —— 时间螺旋星系。半径 = 记忆年龄(新的从中心长出来),
7
+ * 每个工作区一条旋臂,越重要的越薄。
8
+ *
9
+ * 这一版是**真三维**:真正的投影矩阵、真正的深度缓冲、真正的球面着色。
10
+ * - 相机有位置和目标点,绕目标旋转;滚轮沿视线推进;中键/右键平移目标点。
11
+ * - 节点是面向相机的小球(billboard + 法线着色),开深度测试,近的挡住远的。
12
+ * - 连线是三维空间里的线段,同样吃深度,会在球后面被挡住。
13
+ * - 远处自动压暗(雾),近处亮 —— 靠几何而不是靠后期发光来表现纵深。
14
+ *
15
+ * 交互:左键点星=详情 / 左键拖=转视角 / 中键右键拖=平移 / 滚轮=推进 / 双击=复位
16
+ */
17
+ (function () {
18
+ 'use strict'
19
+ /** 中文即源文:英文模式查 i18n.js 的表,查不到就原样返回中文。 */
20
+ const T = (zh, vars) => (window.NebulaI18n ? window.NebulaI18n.t(zh, vars) : zh)
21
+
22
+ const LEVEL_COLOR = {
23
+ soul: '#ffd88a',
24
+ user: '#7ff0c8',
25
+ project: '#6cc8ff',
26
+ lesson: '#ff9f7a',
27
+ topic: '#c39bff',
28
+ fact: '#9fb6cc',
29
+ rules: '#ff8fb0',
30
+ source: '#8ce0ff',
31
+ }
32
+ const TYPE_COLOR = {
33
+ explicit: [1.0, 0.85, 0.54],
34
+ project: [0.42, 0.78, 1.0],
35
+ entity: [0.5, 0.94, 0.78],
36
+ keyword: [0.76, 0.61, 1.0],
37
+ semantic: [0.47, 0.88, 0.71],
38
+ hebbian: [1.0, 0.64, 0.42],
39
+ mentions: [0.55, 0.88, 1.0],
40
+ }
41
+ const TAU = Math.PI * 2
42
+ const LAYOUT_VERSION = 'v7'
43
+
44
+ function hexToRgb(hex) {
45
+ const h = String(hex || '#9fb6cc').replace('#', '')
46
+ const v = h.length === 3 ? h.split('').map((c) => c + c).join('') : h
47
+ const n = parseInt(v, 16)
48
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]
49
+ }
50
+
51
+ function hashString(s) {
52
+ let h = 2166136261
53
+ for (let i = 0; i < s.length; i++) {
54
+ h ^= s.charCodeAt(i)
55
+ h = Math.imul(h, 16777619)
56
+ }
57
+ return (h >>> 0) / 4294967295
58
+ }
59
+
60
+ function clamp(v, a, b) {
61
+ return v < a ? a : v > b ? b : v
62
+ }
63
+
64
+ // ---------- 4x4 矩阵(列主序,直接喂 GL)----------
65
+ function mat4() {
66
+ return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
67
+ }
68
+
69
+ function multiply(out, a, b) {
70
+ for (let c = 0; c < 4; c++) {
71
+ for (let r = 0; r < 4; r++) {
72
+ out[c * 4 + r] =
73
+ a[0 * 4 + r] * b[c * 4 + 0] +
74
+ a[1 * 4 + r] * b[c * 4 + 1] +
75
+ a[2 * 4 + r] * b[c * 4 + 2] +
76
+ a[3 * 4 + r] * b[c * 4 + 3]
77
+ }
78
+ }
79
+ return out
80
+ }
81
+
82
+ function perspective(out, fovy, aspect, near, far) {
83
+ const f = 1 / Math.tan(fovy / 2)
84
+ out.fill(0)
85
+ out[0] = f / aspect
86
+ out[5] = f
87
+ out[10] = (far + near) / (near - far)
88
+ out[11] = -1
89
+ out[14] = (2 * far * near) / (near - far)
90
+ return out
91
+ }
92
+
93
+ /** 视图矩阵:相机在目标点外的球面上,看向目标点 */
94
+ function lookAtTarget(out, yaw, pitch, dist, tx, ty, tz) {
95
+ const cy = Math.cos(yaw)
96
+ const sy = Math.sin(yaw)
97
+ const cp = Math.cos(pitch)
98
+ const sp = Math.sin(pitch)
99
+ // 相机位置(绕目标点的球面)
100
+ const ex = tx + dist * cp * sy
101
+ const ey = ty + dist * sp
102
+ const ez = tz + dist * cp * cy
103
+ // 手写 lookAt
104
+ let zx = ex - tx, zy = ey - ty, zz = ez - tz
105
+ let len = Math.hypot(zx, zy, zz) || 1
106
+ zx /= len; zy /= len; zz /= len
107
+ let xx = zz * 0 - zy * 0 + (0 * zz - 1 * zy) // 用 up=(0,1,0) 交叉
108
+ xx = 1 * zz - 0 * zy
109
+ let xy = 0 * zx - 0 * zz
110
+ let xz = 0 * zy - 1 * zx
111
+ len = Math.hypot(xx, xy, xz) || 1
112
+ xx /= len; xy /= len; xz /= len
113
+ const yx = zy * xz - zz * xy
114
+ const yy = zz * xx - zx * xz
115
+ const yz = zx * xy - zy * xx
116
+ out[0] = xx; out[1] = yx; out[2] = zx; out[3] = 0
117
+ out[4] = xy; out[5] = yy; out[6] = zy; out[7] = 0
118
+ out[8] = xz; out[9] = yz; out[10] = zz; out[11] = 0
119
+ out[12] = -(xx * ex + xy * ey + xz * ez)
120
+ out[13] = -(yx * ex + yy * ey + yz * ez)
121
+ out[14] = -(zx * ex + zy * ey + zz * ez)
122
+ out[15] = 1
123
+ return out
124
+ }
125
+
126
+ /* ---------- 纯函数:Node 里能直接 require 出来测 ---------- */
127
+
128
+ /**
129
+ * 局部图:从 id 出发沿边走 depth 跳,返回 id 集合(含它自己)。
130
+ * id 空或 depth <= 0 返回 null —— 意思是「不裁剪」,而不是「空图」。
131
+ * 只读边表,不碰 state:同一个函数在面板里是视图过滤,在探针里是纯计算。
132
+ */
133
+ function neighborhoodIds(edges, id, depth) {
134
+ const d = Number(depth) || 0
135
+ if (!id || d <= 0) return null
136
+ const adj = new Map()
137
+ for (const e of edges || []) {
138
+ if (!e || e.a == null || e.b == null) continue
139
+ if (!adj.has(e.a)) adj.set(e.a, [])
140
+ if (!adj.has(e.b)) adj.set(e.b, [])
141
+ adj.get(e.a).push(e.b)
142
+ adj.get(e.b).push(e.a)
143
+ }
144
+ const seen = new Set([id])
145
+ let frontier = [id]
146
+ for (let step = 0; step < d && frontier.length; step += 1) {
147
+ const next = []
148
+ for (const cur of frontier) {
149
+ for (const nb of adj.get(cur) || []) {
150
+ if (seen.has(nb)) continue
151
+ seen.add(nb)
152
+ next.push(nb)
153
+ }
154
+ }
155
+ frontier = next
156
+ }
157
+ return seen
158
+ }
159
+
160
+ /** 引力的四个默认值。界面滑杆给的就是真单位,这里只负责夹上限。 */
161
+ const FORCE_BASE = { repulse: 6200, springRest: 90, clusterPull: 0.02, damping: 0.86 }
162
+
163
+ /**
164
+ * 把界面给的四个数收敛成合法的力常数。
165
+ * 越界不报错、夹回来:滑杆的边界已经写死了,这里防的是手改 localStorage 或者旧版本存的值。
166
+ */
167
+ function forceParams(ui) {
168
+ const u = ui || {}
169
+ const num = (v, lo, hi, dft) => {
170
+ // null / 空串不算 0:Number(null) 是 0,落到夹取下限就等于「把阻尼拧到底」,不是默认
171
+ if (v === null || v === undefined || v === '') return dft
172
+ const n = Number(v)
173
+ if (!Number.isFinite(n)) return dft
174
+ return Math.min(hi, Math.max(lo, n))
175
+ }
176
+ return {
177
+ repulse: num(u.repulse, 1200, 20000, FORCE_BASE.repulse),
178
+ springRest: num(u.springRest, 30, 200, FORCE_BASE.springRest),
179
+ clusterPull: num(u.clusterPull, 0, 0.08, FORCE_BASE.clusterPull),
180
+ damping: num(u.damping, 0.6, 0.96, FORCE_BASE.damping),
181
+ }
182
+ }
183
+
184
+ /**
185
+ * 标签透明度:近处 1、远处 0,中间线性。
186
+ * Obsidian 的 text fade threshold 也是一段曲线而不是开关 —— 离散阈值会在缩放时「啪」地跳一下。
187
+ */
188
+ function labelAlpha(dist, near, far) {
189
+ const d = Number(dist)
190
+ const n = Number(near)
191
+ const f = Number(far)
192
+ if (!Number.isFinite(d)) return 0
193
+ if (!Number.isFinite(n) || !Number.isFinite(f) || f <= n) return d <= n ? 1 : 0
194
+ if (d <= n) return 1
195
+ if (d >= f) return 0
196
+ return (f - d) / (f - n)
197
+ }
198
+
199
+ function create(canvas, labelCanvas, opts) {
200
+ opts = opts || {}
201
+ // 三维一帧最多画这么多:再多就不是「星空」,是一团发光的雾,
202
+ // 帧率也保不住(力导向每一步要过全部节点 + 全部边)。
203
+ // 超出时按「重要度 → 度数 → id」取样,取样之外的记忆仍然在 2D 星云里全量可见。
204
+ const BALL_LIMIT = 18000
205
+ // 取样后力导向的迭代上限也压低:5 万条时 320 轮等于让浏览器算一分钟。
206
+ const FORCE_ITER_BIG = 90
207
+ // 每帧问一次 gl.getError() 会强制同步等 GPU(实测占绘制路径 3.7% 的自身耗时),
208
+ // 只在 ?glcheck=1 时打开,平时这条热路径上不问。
209
+ const glCheck = /[?&]glcheck=1(?:&|$)/.test(window.location.search)
210
+ const gl = canvas.getContext('webgl', {
211
+ alpha: true,
212
+ antialias: true,
213
+ premultipliedAlpha: false,
214
+ depth: true,
215
+ })
216
+ if (!gl) throw new Error('WebGL context unavailable')
217
+ const lctx = labelCanvas ? labelCanvas.getContext('2d') : null
218
+
219
+ const listeners = { select: [], hover: [] }
220
+ function emit(evt, payload) {
221
+ for (const fn of listeners[evt] || []) fn(payload)
222
+ }
223
+
224
+ const state = {
225
+ active: false,
226
+ layout: 'cluster',
227
+ nodes: [],
228
+ edges: [],
229
+ byId: new Map(),
230
+ clusters: [],
231
+ graph: null,
232
+ hover: null,
233
+ selected: null,
234
+ highlightSet: null,
235
+ // 局部图:null = 全图;Set = 只看这几条(点一颗星、N 跳以内)
236
+ local: null,
237
+ localId: null,
238
+ pathIds: null,
239
+ pathEdges: null,
240
+ pulse: new Map(),
241
+ filter: { ws: null, levels: null, types: null, minW: 0, minImp: 0 },
242
+ timeCut: 0, // 时间回放:只显示 createdAt <= timeCut 的记忆(0 = 不过滤)
243
+ // 标签窗口:相机距离 <= labelNear 全亮、>= labelFar 全灭,中间线性淡出
244
+ labelNear: 1100,
245
+ labelFar: 1900,
246
+ pad: { left: 16, right: 16, top: 76, bottom: 48 },
247
+ cam: { yaw: 0.62, pitch: 0.28, dist: 2400, tx: 0, ty: 0, tz: 0, panX: 0, panY: 0 },
248
+ inertia: { yaw: 0, pitch: 0 },
249
+ target: null,
250
+ size: { w: 1, h: 1, dpr: 1 },
251
+ drag: null,
252
+ // 系统开了「减少动态效果」就不自动转:一直转的星空对前庭敏感的人是负担
253
+ spin: !(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches),
254
+ autoFit: false,
255
+ force: { running: false, alpha: 0, iter: 0, maxIter: 320 },
256
+ spiral: { maxAge: 1, rings: [], arms: [] },
257
+ proj: mat4(),
258
+ view: mat4(),
259
+ }
260
+
261
+ // ---------- shaders ----------
262
+ function compile(type, src) {
263
+ const sh = gl.createShader(type)
264
+ gl.shaderSource(sh, src)
265
+ gl.compileShader(sh)
266
+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
267
+ throw new Error('shader: ' + gl.getShaderInfoLog(sh))
268
+ }
269
+ return sh
270
+ }
271
+ function program(vsSrc, fsSrc) {
272
+ const p = gl.createProgram()
273
+ gl.attachShader(p, compile(gl.VERTEX_SHADER, vsSrc))
274
+ gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fsSrc))
275
+ gl.linkProgram(p)
276
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
277
+ throw new Error('program: ' + gl.getProgramInfoLog(p))
278
+ }
279
+ return p
280
+ }
281
+
282
+ // 球:三维世界坐标 → 点精灵。片元里用 gl_PointCoord 造球面法线,
283
+ // 参与深度测试(近的挡住远的),但不引入四边形索引,稳。
284
+ const ballProg = program(
285
+ `attribute vec3 aCenter; attribute vec3 aColor;
286
+ attribute float aSize; attribute float aAlpha; attribute float aShape;
287
+ uniform mat4 uProj; uniform mat4 uView; uniform vec2 uPan; uniform float uPxScale;
288
+ varying vec3 vColor; varying float vAlpha; varying float vFog; varying float vShape;
289
+ void main() {
290
+ vec4 mv = uView * vec4(aCenter, 1.0);
291
+ vec4 clip = uProj * mv;
292
+ clip.xy += uPan * clip.w;
293
+ gl_Position = clip;
294
+ float px = (aSize * uPxScale) / max(1.0, -mv.z);
295
+ // 来源节点(菱形)给一个更高的最小像素,远远看也能认出它不是记忆
296
+ gl_PointSize = clamp(px * (aShape > 0.5 ? 1.75 : 1.35), aShape > 0.5 ? 3.5 : 1.5, 18.0);
297
+ vColor = aColor;
298
+ vAlpha = aAlpha;
299
+ vShape = aShape;
300
+ vFog = clamp((-mv.z - 2200.0) / 6000.0, 0.0, 0.72);
301
+ }`,
302
+ `precision mediump float;
303
+ varying vec3 vColor; varying float vAlpha; varying float vFog; varying float vShape;
304
+ void main() {
305
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
306
+ c.y = -c.y;
307
+ // aShape = 1 时用 L1 距离造菱形(来源节点:技能 / MCP / 插件)
308
+ float rc = length(c);
309
+ float rd = (abs(c.x) + abs(c.y)) * 0.78;
310
+ float r = mix(rc, rd, step(0.5, vShape));
311
+ if (r > 1.0) discard;
312
+ // 光点:核心一点白热,外面一圈很淡的晕;菱形核心更实,像个小宝石
313
+ float core = exp(-r * r * 5.5);
314
+ float halo = pow(max(0.0, 1.0 - r), 2.4) * 0.42;
315
+ vec3 col = vColor * (1.0 + 0.45 * core);
316
+ float a = (core * 0.92 + halo * 0.80) * vAlpha * (1.0 - vFog * 0.45);
317
+ gl_FragColor = vec4(col, a);
318
+ }`
319
+ )
320
+ const bLoc = {
321
+ center: gl.getAttribLocation(ballProg, 'aCenter'),
322
+ color: gl.getAttribLocation(ballProg, 'aColor'),
323
+ size: gl.getAttribLocation(ballProg, 'aSize'),
324
+ alpha: gl.getAttribLocation(ballProg, 'aAlpha'),
325
+ shape: gl.getAttribLocation(ballProg, 'aShape'),
326
+ proj: gl.getUniformLocation(ballProg, 'uProj'),
327
+ view: gl.getUniformLocation(ballProg, 'uView'),
328
+ pan: gl.getUniformLocation(ballProg, 'uPan'),
329
+ pxScale: gl.getUniformLocation(ballProg, 'uPxScale'),
330
+ }
331
+
332
+ // 连线:三维线段,吃深度,远处淡
333
+ const wireProg = program(
334
+ `attribute vec3 aPos; attribute vec4 aColor;
335
+ uniform mat4 uProj; uniform mat4 uView; uniform vec2 uPan;
336
+ varying vec4 vColor;
337
+ void main() {
338
+ vec4 mv = uView * vec4(aPos, 1.0);
339
+ vec4 clip = uProj * mv;
340
+ clip.xy += uPan * clip.w;
341
+ gl_Position = clip;
342
+ float fog = clamp((-mv.z - 1400.0) / 6000.0, 0.0, 0.8);
343
+ vColor = vec4(aColor.rgb, aColor.a * (1.0 - fog * 0.75));
344
+ }`,
345
+ `precision mediump float; varying vec4 vColor;
346
+ void main() { gl_FragColor = vColor; }`
347
+ )
348
+ const wLoc = {
349
+ pos: gl.getAttribLocation(wireProg, 'aPos'),
350
+ color: gl.getAttribLocation(wireProg, 'aColor'),
351
+ proj: gl.getUniformLocation(wireProg, 'uProj'),
352
+ view: gl.getUniformLocation(wireProg, 'uView'),
353
+ pan: gl.getUniformLocation(wireProg, 'uPan'),
354
+ }
355
+
356
+ const ballBuf = {
357
+ center: gl.createBuffer(),
358
+ corner: gl.createBuffer(),
359
+ color: gl.createBuffer(),
360
+ size: gl.createBuffer(),
361
+ alpha: gl.createBuffer(),
362
+ shape: gl.createBuffer(),
363
+ }
364
+ const wireBuf = { pos: gl.createBuffer(), color: gl.createBuffer() }
365
+ const ballIdx = gl.createBuffer()
366
+
367
+ // ---------- layout: cluster (force directed) ----------
368
+ function seedClusterCenters() {
369
+ const counts = new Map()
370
+ for (const n of state.nodes) counts.set(n.cluster, (counts.get(n.cluster) || 0) + 1)
371
+ for (const c of state.clusters) c._n = counts.get(c.id) || 1
372
+ const order = state.clusters.slice().sort((a, b) => b._n - a._n)
373
+ const golden = Math.PI * (3 - Math.sqrt(5))
374
+ order.forEach((c, i) => {
375
+ const y = 1 - (i / Math.max(1, order.length - 1)) * 2
376
+ const ring = Math.sqrt(Math.max(0, 1 - y * y))
377
+ const th = golden * i
378
+ const shell = 780 + (i === 0 ? 0 : 110)
379
+ c._rad = 62 + Math.sqrt(c._n) * 10.5
380
+ c._cx = Math.cos(th) * ring * shell
381
+ c._cy = y * shell * 0.78
382
+ c._cz = Math.sin(th) * ring * shell
383
+ })
384
+ }
385
+
386
+ function seedClusterNodes() {
387
+ const byCluster = new Map(state.clusters.map((c) => [c.id, c]))
388
+ for (const n of state.nodes) {
389
+ const c = byCluster.get(n.cluster) || { _cx: 0, _cy: 0, _cz: 0, _rad: 220 }
390
+ const r1 = hashString(n.id)
391
+ const r2 = hashString(n.id + 'y')
392
+ const r3 = hashString(n.id + 'z')
393
+ const imp = clamp(n.importance || 1, 1, 4)
394
+ const depth = 1 - (imp - 1) / 3
395
+ const r = c._rad * (1.08 - 0.82 * depth) * (0.55 + 0.65 * Math.sqrt(r1))
396
+ const phi = r2 * TAU
397
+ const cosT = 2 * r3 - 1
398
+ const sinT = Math.sqrt(Math.max(0, 1 - cosT * cosT))
399
+ n.x3 = c._cx + Math.cos(phi) * sinT * r
400
+ n.y3 = c._cy + cosT * r * 0.85
401
+ n.z3 = c._cz + Math.sin(phi) * sinT * r
402
+ n.vx = 0
403
+ n.vy = 0
404
+ n.vz = 0
405
+ }
406
+ }
407
+
408
+ function buildOctree(nodes) {
409
+ let minX = Infinity, minY = Infinity, minZ = Infinity
410
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity
411
+ for (const n of nodes) {
412
+ if (n.x3 < minX) minX = n.x3
413
+ if (n.y3 < minY) minY = n.y3
414
+ if (n.z3 < minZ) minZ = n.z3
415
+ if (n.x3 > maxX) maxX = n.x3
416
+ if (n.y3 > maxY) maxY = n.y3
417
+ if (n.z3 > maxZ) maxZ = n.z3
418
+ }
419
+ const cx = (minX + maxX) / 2
420
+ const cy = (minY + maxY) / 2
421
+ const cz = (minZ + maxZ) / 2
422
+ const half = Math.max(maxX - minX, maxY - minY, maxZ - minZ, 1) / 2 + 1
423
+ const root = { x: cx, y: cy, z: cz, half, mass: 0, comx: 0, comy: 0, comz: 0, kids: null, items: [] }
424
+
425
+ function cellFor(node, n) {
426
+ const h = node.half / 2
427
+ const i = (n.x3 >= node.x ? 4 : 0) + (n.y3 >= node.y ? 2 : 0) + (n.z3 >= node.z ? 1 : 0)
428
+ return {
429
+ i,
430
+ cell: {
431
+ x: node.x + (n.x3 >= node.x ? h : -h),
432
+ y: node.y + (n.y3 >= node.y ? h : -h),
433
+ z: node.z + (n.z3 >= node.z ? h : -h),
434
+ half: h,
435
+ mass: 0,
436
+ comx: 0,
437
+ comy: 0,
438
+ comz: 0,
439
+ kids: null,
440
+ items: [],
441
+ },
442
+ }
443
+ }
444
+
445
+ function insert(node, n, depth) {
446
+ node.mass += 1
447
+ node.comx += n.x3
448
+ node.comy += n.y3
449
+ node.comz += n.z3
450
+ if (!node.kids) {
451
+ node.items.push(n)
452
+ if (node.items.length > 6 && depth < 14) {
453
+ const bucket = node.items
454
+ node.items = []
455
+ node.kids = new Array(8).fill(null)
456
+ for (const m of bucket) {
457
+ const { i, cell } = cellFor(node, m)
458
+ if (!node.kids[i]) node.kids[i] = cell
459
+ insert(node.kids[i], m, depth + 1)
460
+ }
461
+ }
462
+ return
463
+ }
464
+ const { i, cell } = cellFor(node, n)
465
+ if (!node.kids[i]) node.kids[i] = cell
466
+ insert(node.kids[i], n, depth + 1)
467
+ }
468
+
469
+ for (const n of nodes) insert(root, n, 0)
470
+ return root
471
+ }
472
+
473
+ const FORCE = {
474
+ theta: 0.9,
475
+ repulse: 6200,
476
+ spring: 0.02,
477
+ springRest: 90,
478
+ crossClusterSpring: 0.15,
479
+ clusterPull: 0.02,
480
+ centerPull: 0.0002,
481
+ maxStep: 16,
482
+ damping: 0.86,
483
+ }
484
+
485
+ // 布局的三种力拆成三段,每段都能按时间预算中途停下。
486
+ // 为什么拆:五万条(取样 1.8 万)时「一轮迭代」≈ 26ms,一帧里硬跑 6 轮就是 230ms,
487
+ // 用户看到的是「切过去先卡一下」。拆开之后一轮可以跨几帧完成,帧率保住,总工作量不变。
488
+ function forceRepel(nodes, root, from, deadline) {
489
+ const theta2 = FORCE.theta * FORCE.theta
490
+ let i = from
491
+ for (; i < nodes.length; i++) {
492
+ if ((i & 31) === 0 && i > from && performance.now() > deadline) break
493
+ const n = nodes[i]
494
+ let fx = 0, fy = 0, fz = 0
495
+ const stack = [root]
496
+ while (stack.length) {
497
+ const cell = stack.pop()
498
+ if (!cell.mass) continue
499
+ const dx = n.x3 - cell.comx / cell.mass
500
+ const dy = n.y3 - cell.comy / cell.mass
501
+ const dz = n.z3 - cell.comz / cell.mass
502
+ const d2 = dx * dx + dy * dy + dz * dz + 1
503
+ const far = (cell.half * cell.half) / d2 < theta2
504
+ if (far) {
505
+ const f = (FORCE.repulse * cell.mass) / d2
506
+ const inv = 1 / Math.sqrt(d2)
507
+ fx += dx * inv * f
508
+ fy += dy * inv * f
509
+ fz += dz * inv * f
510
+ } else {
511
+ for (const m of cell.items) {
512
+ if (m === n) continue
513
+ const ax = n.x3 - m.x3
514
+ const ay = n.y3 - m.y3
515
+ const az = n.z3 - m.z3
516
+ const a2 = ax * ax + ay * ay + az * az + 1
517
+ const f = FORCE.repulse / a2
518
+ const inv = 1 / Math.sqrt(a2)
519
+ fx += ax * inv * f
520
+ fy += ay * inv * f
521
+ fz += az * inv * f
522
+ }
523
+ if (cell.kids) for (const k of cell.kids) if (k) stack.push(k)
524
+ }
525
+ }
526
+ n._fx = fx
527
+ n._fy = fy
528
+ n._fz = fz
529
+ }
530
+ return i
531
+ }
532
+
533
+ function forceSprings(keep, from, deadline) {
534
+ const byId = state.byId
535
+ const edges = state.edges
536
+ let i = from
537
+ for (; i < edges.length; i++) {
538
+ if ((i & 255) === 0 && i > from && performance.now() > deadline) break
539
+ const e = edges[i]
540
+ // 取样之外的边不参与受力:它们的另一端根本没画出来,算了也是白算
541
+ if (keep && !(keep.has(e.a) && keep.has(e.b))) continue
542
+ const a = byId.get(e.a)
543
+ const b = byId.get(e.b)
544
+ if (!a || !b) continue
545
+ const dx = b.x3 - a.x3
546
+ const dy = b.y3 - a.y3
547
+ const dz = b.z3 - a.z3
548
+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz) + 1e-3
549
+ const rest = FORCE.springRest * (1.35 - 0.55 * (e.w || 0.4))
550
+ let k = (FORCE.spring * (0.35 + (e.w || 0.4)) * (d - rest)) / d
551
+ if (a.cluster !== b.cluster) k *= FORCE.crossClusterSpring
552
+ if (Math.abs(k) > 9) k = (k > 0 ? 1 : -1) * 9
553
+ const fx = dx * k
554
+ const fy = dy * k
555
+ const fz = dz * k
556
+ a._fx += fx
557
+ a._fy += fy
558
+ a._fz += fz
559
+ b._fx -= fx
560
+ b._fy -= fy
561
+ b._fz -= fz
562
+ }
563
+ return i
564
+ }
565
+
566
+ function forcePull(nodes, from, deadline) {
567
+ const centers = new Map(state.clusters.map((c) => [c.id, c]))
568
+ let i = from
569
+ for (; i < nodes.length; i++) {
570
+ if ((i & 63) === 0 && i > from && performance.now() > deadline) break
571
+ const n = nodes[i]
572
+ const c = centers.get(n.cluster)
573
+ if (c) {
574
+ n._fx += (c._cx - n.x3) * FORCE.clusterPull
575
+ n._fy += (c._cy - n.y3) * FORCE.clusterPull
576
+ n._fz += (c._cz - n.z3) * FORCE.clusterPull
577
+ }
578
+ n._fx -= n.x3 * FORCE.centerPull
579
+ n._fy -= n.y3 * FORCE.centerPull
580
+ n._fz -= n.z3 * FORCE.centerPull
581
+ }
582
+ return i
583
+ }
584
+
585
+ function forceApply(nodes, alpha) {
586
+ for (const n of nodes) {
587
+ let dx = n._fx * alpha
588
+ let dy = n._fy * alpha
589
+ let dz = n._fz * alpha
590
+ const len = Math.sqrt(dx * dx + dy * dy + dz * dz)
591
+ if (len > FORCE.maxStep) {
592
+ const s = FORCE.maxStep / len
593
+ dx *= s
594
+ dy *= s
595
+ dz *= s
596
+ }
597
+ n.vx = (n.vx || 0) * FORCE.damping + dx
598
+ n.vy = (n.vy || 0) * FORCE.damping + dy
599
+ n.vz = (n.vz || 0) * FORCE.damping + dz
600
+ n.x3 += n.vx
601
+ n.y3 += n.vy
602
+ n.z3 += n.vz
603
+ if (!isFinite(n.x3) || !isFinite(n.y3) || !isFinite(n.z3)) {
604
+ n.x3 = n.vx = 0
605
+ n.y3 = n.vy = 0
606
+ n.z3 = n.vz = 0
607
+ }
608
+ }
609
+ }
610
+
611
+ function cacheKey() {
612
+ const g = state.graph || {}
613
+ return 'nb3d:' + LAYOUT_VERSION + ':' + (g.sig || '') + ':' + state.layout + ':' + state.nodes.length
614
+ }
615
+
616
+ function saveLayout(nodes) {
617
+ try {
618
+ const arr = nodes.map((n) => [Math.round(n.x3), Math.round(n.y3), Math.round(n.z3)])
619
+ localStorage.setItem(cacheKey(), JSON.stringify(arr))
620
+ } catch (_) {}
621
+ }
622
+
623
+ function loadLayout(nodes) {
624
+ try {
625
+ const raw = localStorage.getItem(cacheKey())
626
+ if (!raw) return false
627
+ const arr = JSON.parse(raw)
628
+ if (!Array.isArray(arr) || arr.length !== nodes.length) return false
629
+ nodes.forEach((n, i) => {
630
+ n.x3 = arr[i][0]
631
+ n.y3 = arr[i][1]
632
+ n.z3 = arr[i][2]
633
+ n.vx = n.vy = n.vz = 0
634
+ })
635
+ return true
636
+ } catch (_) {
637
+ return false
638
+ }
639
+ }
640
+
641
+ // ---------- layout: spiral (time) ----------
642
+ function layoutSpiral() {
643
+ const now = Date.now()
644
+ let maxAge = 1
645
+ for (const n of state.nodes) {
646
+ const t = Number(n.createdAt) || now
647
+ n._age = Math.max(0, now - t)
648
+ if (n._age > maxAge) maxAge = n._age
649
+ }
650
+ const Rmax = 1000
651
+ const R0 = 110
652
+ const arms = state.clusters.length || 1
653
+ const baseAngle = new Map()
654
+ state.clusters.forEach((c, i) => baseAngle.set(c.id, (i / arms) * TAU))
655
+
656
+ for (const n of state.nodes) {
657
+ const t = Math.pow(clamp(n._age / maxAge, 0, 1), 0.75)
658
+ const r = R0 + t * Rmax
659
+ const swirl = 1.55 * Math.PI * (r / Rmax)
660
+ const arm = baseAngle.get(n.cluster) || 0
661
+ const jitter = (hashString(n.id) - 0.5) * 0.34 * (0.4 + t)
662
+ const ang = arm + swirl + jitter
663
+ const rr = r * (1 + (hashString(n.id + 'r') - 0.5) * 0.05)
664
+ const imp = clamp(n.importance || 1, 1, 4)
665
+ const thick = 18 + 58 * (1 - (imp - 1) / 3)
666
+ n.x3 = Math.cos(ang) * rr
667
+ n.z3 = Math.sin(ang) * rr
668
+ n.y3 = (hashString(n.id + 'y') - 0.5) * 2 * thick
669
+ n.vx = n.vy = n.vz = 0
670
+ }
671
+
672
+ // 年龄环:跨度小的时候按小时给(这个库里的记忆只横跨两三天,
673
+ // 只画「1 天前」会让整张盘看起来没有时间信息)
674
+ const hour = 3600000
675
+ const day = 86400000
676
+ const STEPS = [1, 3, 6, 12, 24, 48, 72, 168, 336, 720, 2160, 8760]
677
+ const rings = []
678
+ for (const h of STEPS) {
679
+ const age = h * hour
680
+ if (age > maxAge * 1.06) continue
681
+ const t = Math.pow(clamp(age / maxAge, 0, 1), 0.75)
682
+ rings.push({
683
+ age,
684
+ r: R0 + t * Rmax,
685
+ text: h < 24 ? h + T(' 小时前') : h < 48 ? T('1 天前') : Math.round(h / 24) + T(' 天前'),
686
+ })
687
+ }
688
+ rings.sort((a, b) => a.r - b.r)
689
+ state.spiral = {
690
+ maxAge,
691
+ rings: rings.slice(-5),
692
+ arms: state.clusters.map((c) => ({
693
+ id: c.id,
694
+ label: c.title || c.label || c.id,
695
+ angle: baseAngle.get(c.id) || 0,
696
+ color: c.color,
697
+ })),
698
+ }
699
+ }
700
+
701
+ function prepareNodes() {
702
+ for (const n of state.nodes) {
703
+ const imp = clamp(n.importance || 1, 1, 4)
704
+ n.heat = clamp(n.heat || 0.4, 0.1, 1.4)
705
+ n.rgb = hexToRgb(n.color || LEVEL_COLOR[n.level] || '#9fb6cc')
706
+ // 世界单位半径:重要度是主项(heat 先夹住,否则个别节点会变成巨球)
707
+ n.rWorld = 13 + imp * 5 + n.heat * 7
708
+ }
709
+ computeDrawBudget()
710
+ }
711
+
712
+ // 大库的「画哪些」:超过上限就按重要度取样,并且只在一处决定(visible 统一查它),
713
+ // 这样点、线、拾取、标签看到的是同一批节点,不会出现「点得到看不见的星」。
714
+ function computeDrawBudget() {
715
+ const total = state.nodes.length
716
+ if (total <= BALL_LIMIT) {
717
+ state.drawSet = null
718
+ state.budget = { limit: BALL_LIMIT, total, shown: total, sampled: false }
719
+ return
720
+ }
721
+ const idx = new Array(total)
722
+ for (let i = 0; i < total; i += 1) idx[i] = i
723
+ const ns = state.nodes
724
+ idx.sort((i, j) => {
725
+ const a = ns[i]
726
+ const b = ns[j]
727
+ const di = (b.importance || 1) - (a.importance || 1)
728
+ if (di) return di
729
+ const dd = (b.degree || 0) - (a.degree || 0)
730
+ if (dd) return dd
731
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
732
+ })
733
+ const keep = new Set()
734
+ for (let i = 0; i < BALL_LIMIT; i += 1) keep.add(ns[idx[i]].id)
735
+ state.drawSet = keep
736
+ // 取样之外的边也先筛掉:每帧打包顶点时不用再对 15 万条边各查两次 Set
737
+ state.drawEdges = state.edges.filter((e) => keep.has(e.a) && keep.has(e.b))
738
+ state.budget = { limit: BALL_LIMIT, total, shown: BALL_LIMIT, sampled: true, edges: state.drawEdges.length }
739
+ }
740
+
741
+ function layout() {
742
+ prepareNodes()
743
+ if (state.layout === 'spiral') {
744
+ state.force.running = false
745
+ layoutSpiral()
746
+ return
747
+ }
748
+ seedClusterCenters()
749
+ if (loadLayout(state.nodes)) {
750
+ state.force.running = false
751
+ return
752
+ }
753
+ seedClusterNodes()
754
+ state.forceNodes = state.drawSet ? state.nodes.filter((n) => state.drawSet.has(n.id)) : null
755
+ state.force.maxIter = state.drawSet ? FORCE_ITER_BIG : 320
756
+ state.force.running = true
757
+ state.force.alpha = 0.9
758
+ state.force.iter = 0
759
+ // 增量布局的游标:phase 0=斥力 1=弹簧 2=向心,cursor 是当前段推进到哪
760
+ state.force.phase = 0
761
+ state.force.cursor = 0
762
+ state.force.root = null
763
+ state.autoFit = true
764
+ }
765
+
766
+ // ---------- 投影:JS 侧镜像同一套矩阵(给标签和拾取用)----------
767
+ const tmp = [0, 0, 0, 0]
768
+ function project(x, y, z, out) {
769
+ const cam = state.cam
770
+ const v = state.view
771
+ const p = state.proj
772
+ // 视图变换
773
+ const vx = v[0] * x + v[4] * y + v[8] * z + v[12]
774
+ const vy = v[1] * x + v[5] * y + v[9] * z + v[13]
775
+ const vz = v[2] * x + v[6] * y + v[10] * z + v[14]
776
+ // 投影变换
777
+ const cx = p[0] * vx + p[8] * vz
778
+ const cy2 = p[5] * vy + p[9] * vz
779
+ const cw = -vz
780
+ const ndcX = cx / (cw || 1)
781
+ const ndcY = cy2 / (cw || 1)
782
+ const pan = panNdc()
783
+ out[0] = (ndcX + pan[0] * 1) * 0.5 * state.size.w + state.size.w * 0.5
784
+ out[1] = state.size.h * 0.5 - (ndcY + pan[1] * 1) * 0.5 * state.size.h
785
+ out[2] = -vz
786
+ out[3] = p[5] * state.size.h * 0.5
787
+ return out
788
+ }
789
+
790
+ function panNdc() {
791
+ const cam = state.cam
792
+ return [(cam.panX / state.size.w) * 2, (-cam.panY / state.size.h) * 2]
793
+ }
794
+
795
+ function visible(n) {
796
+ const f = state.filter
797
+ if (n.hidden || !n.rgb) return false
798
+ // 取样之外的不画、也不参与拾取:省下来的不只是绘制,还有每帧的顶点打包
799
+ if (state.drawSet && !state.drawSet.has(n.id)) return false
800
+ if (state.timeCut && (Number(n.createdAt) || 0) > state.timeCut) return false
801
+ // 局部图只收画布上的东西:检索、计数、导出都走别的口,不受它影响
802
+ if (state.local && !state.local.has(n.id)) return false
803
+ // 工作区筛选的键是 chip 上的 ws 名(带空格,如 'Liberty Of Code'),
804
+ // 而 n.cluster 是压掉空格的 id('LibertyOfCode')。早先只比 cluster,
805
+ // 于是「只留一个工作区」在 3D 里会把整张图筛空。两个都认。
806
+ if (f.ws && !f.ws.has(n.ws) && !f.ws.has(n.cluster)) return false
807
+ if (f.levels && !f.levels.has(n.level)) return false
808
+ if (f.providers && !f.providers.has(n.provider || 'meow-memory')) return false
809
+ if (f.minImp && (n.importance || 0) < f.minImp) return false
810
+ return true
811
+ }
812
+
813
+ function visibleEdge(e) {
814
+ const f = state.filter
815
+ if (f.types && !f.types.has(e.t)) return false
816
+ if (f.minW && (e.w || 0) < f.minW) return false
817
+ const a = state.byId.get(e.a)
818
+ const b = state.byId.get(e.b)
819
+ if (!a || !b) return false
820
+ return visible(a) && visible(b)
821
+ }
822
+
823
+ // ---------- draw ----------
824
+ function updateMatrices() {
825
+ const { w, h } = state.size
826
+ perspective(state.proj, (52 * Math.PI) / 180, Math.max(0.2, w / h), 1, 12000)
827
+ lookAtTarget(state.view, state.cam.yaw, state.cam.pitch, state.cam.dist, state.cam.tx, state.cam.ty, state.cam.tz)
828
+ }
829
+
830
+ const cornerQuad = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1])
831
+
832
+ function drawScene() {
833
+ updateMatrices()
834
+ const hl = state.highlightSet
835
+ const pan = panNdc()
836
+
837
+ // 顶点数据只在「布局/筛选/高亮/脉冲」变化时重建;相机怎么转都不用重传,
838
+ // 这是把 3D 从 35fps 拉到接近 60fps 的关键。
839
+ let pulseAlive = 0
840
+ for (const v of state.pulse.values()) if (v > 0.002) pulseAlive += 1
841
+ if (!state.cache || state.cacheDirty || state.force.running || pulseAlive) {
842
+ const wp = []
843
+ const wc = []
844
+ const edgeList = state.force.running ? [] : state.drawEdges || state.edges
845
+ for (const e of edgeList) {
846
+ if (!visibleEdge(e)) continue
847
+ const a = state.byId.get(e.a)
848
+ const b = state.byId.get(e.b)
849
+ const dim = hl ? (hl.has(e.a) && hl.has(e.b) ? 1 : 0.55) : 1
850
+ const base = TYPE_COLOR[e.t] || [0.6, 0.7, 0.9]
851
+ // 螺旋盘里 3000 条线横穿盘面会把中心糊成一片,压暗一点
852
+ // (0.42 时几乎看不见连线,只剩光点;0.58 能看清"谁连着谁",又不糊)
853
+ const spiralDim = state.layout === 'spiral' ? 0.58 : 1
854
+ const onPath =
855
+ state.pathEdges &&
856
+ state.pathEdges.has(e.a < e.b ? e.a + '|' + e.b : e.b + '|' + e.a)
857
+ const alpha = onPath
858
+ ? 0.95
859
+ : clamp((0.06 + 0.30 * (e.w || 0.3)) * dim * spiralDim, 0.02, 0.62)
860
+ // 区块点亮:两端都亮到 85% 才让这条线出现,否则会先有线后有点
861
+ const rMin = Math.min(a.reveal == null ? 1 : a.reveal, b.reveal == null ? 1 : b.reveal)
862
+ if (rMin < 0.85) continue
863
+ const ea = alpha * Math.min(1, (rMin - 0.85) / 0.15)
864
+ wp.push(a.x3, a.y3, a.z3, b.x3, b.y3, b.z3)
865
+ if (onPath) wc.push(1.0, 0.85, 0.55, ea, 1.0, 0.85, 0.55, ea)
866
+ else wc.push(base[0], base[1], base[2], ea, base[0], base[1], base[2], ea)
867
+ }
868
+ const ccx = []
869
+ const ccol = []
870
+ const csz = []
871
+ const cal = []
872
+ const csh = []
873
+ for (const n of state.nodes) {
874
+ if (!visible(n)) continue
875
+ // 区块点亮:还没亮起来的不画,正在亮的从小长到正常大小
876
+ const rev = n.reveal == null ? 1 : n.reveal
877
+ if (rev <= 0.02) continue
878
+ const pulse = state.pulse.get(n.id)
879
+ const boost = pulse && pulse > 0 ? 1 + 0.5 * pulse : 1
880
+ const onPath = state.pathIds && state.pathIds.has(n.id)
881
+ const dim = hl ? (hl.has(n.id) ? 1 : 0.72) : 1
882
+ const focusBoost = hl && hl.has(n.id) ? 1.25 : 1
883
+ ccx.push(n.x3, n.y3, n.z3)
884
+ // 证据链上的节点染成暖金色,和 2D 的编号圈对应
885
+ if (onPath) ccol.push(1.0, 0.85, 0.55)
886
+ else ccol.push(n.rgb[0], n.rgb[1], n.rgb[2])
887
+ csz.push(
888
+ n.rWorld * boost * focusBoost * (n.level === 'source' ? 1.15 : 1) * (onPath ? 2.2 : 1) * (0.55 + 0.45 * rev),
889
+ )
890
+ cal.push((onPath ? 1 : dim) * rev)
891
+ csh.push(n.level === 'source' ? 1 : 0)
892
+ }
893
+ state.cache = {
894
+ wp,
895
+ wc,
896
+ ccx,
897
+ ccol,
898
+ csz,
899
+ cal,
900
+ csh,
901
+ ballCount: ccx.length / 3,
902
+ }
903
+ state.cacheDirty = false
904
+ }
905
+ const { wp, wc, ccx, ccol, csz, cal, csh, ballCount } = state.cache
906
+
907
+ gl.useProgram(wireProg)
908
+ gl.bindBuffer(gl.ARRAY_BUFFER, wireBuf.pos)
909
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(wp), gl.DYNAMIC_DRAW)
910
+ gl.enableVertexAttribArray(wLoc.pos)
911
+ gl.vertexAttribPointer(wLoc.pos, 3, gl.FLOAT, false, 0, 0)
912
+ gl.bindBuffer(gl.ARRAY_BUFFER, wireBuf.color)
913
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(wc), gl.DYNAMIC_DRAW)
914
+ gl.enableVertexAttribArray(wLoc.color)
915
+ gl.vertexAttribPointer(wLoc.color, 4, gl.FLOAT, false, 0, 0)
916
+ gl.uniformMatrix4fv(wLoc.proj, false, state.proj)
917
+ gl.uniformMatrix4fv(wLoc.view, false, state.view)
918
+ gl.uniform2f(wLoc.pan, pan[0], pan[1])
919
+ gl.enable(gl.BLEND)
920
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE)
921
+ gl.depthMask(false)
922
+ gl.drawArrays(gl.LINES, 0, wp.length / 3)
923
+ gl.depthMask(true)
924
+
925
+ // 光点
926
+ gl.useProgram(ballProg)
927
+ gl.bindBuffer(gl.ARRAY_BUFFER, ballBuf.center)
928
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(ccx), gl.DYNAMIC_DRAW)
929
+ gl.enableVertexAttribArray(bLoc.center)
930
+ gl.vertexAttribPointer(bLoc.center, 3, gl.FLOAT, false, 0, 0)
931
+ gl.bindBuffer(gl.ARRAY_BUFFER, ballBuf.color)
932
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(ccol), gl.DYNAMIC_DRAW)
933
+ gl.enableVertexAttribArray(bLoc.color)
934
+ gl.vertexAttribPointer(bLoc.color, 3, gl.FLOAT, false, 0, 0)
935
+ gl.bindBuffer(gl.ARRAY_BUFFER, ballBuf.size)
936
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(csz), gl.DYNAMIC_DRAW)
937
+ gl.enableVertexAttribArray(bLoc.size)
938
+ gl.vertexAttribPointer(bLoc.size, 1, gl.FLOAT, false, 0, 0)
939
+ gl.bindBuffer(gl.ARRAY_BUFFER, ballBuf.alpha)
940
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(cal), gl.DYNAMIC_DRAW)
941
+ gl.enableVertexAttribArray(bLoc.alpha)
942
+ gl.vertexAttribPointer(bLoc.alpha, 1, gl.FLOAT, false, 0, 0)
943
+ gl.bindBuffer(gl.ARRAY_BUFFER, ballBuf.shape)
944
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(csh), gl.DYNAMIC_DRAW)
945
+ gl.enableVertexAttribArray(bLoc.shape)
946
+ gl.vertexAttribPointer(bLoc.shape, 1, gl.FLOAT, false, 0, 0)
947
+ gl.uniformMatrix4fv(bLoc.proj, false, state.proj)
948
+ gl.uniformMatrix4fv(bLoc.view, false, state.view)
949
+ gl.uniform2f(bLoc.pan, pan[0], pan[1])
950
+ gl.uniform1f(bLoc.pxScale, state.proj[5] * state.size.h * 0.5)
951
+ // 光点用普通混合(不是加色):加色在密集区会把所有颜色叠成一片白,
952
+ // 层级色就白给了。普通混合下核心仍是亮的,边缘保留色相,区块看得出是「哪一层」。
953
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
954
+ gl.depthMask(false)
955
+ gl.drawArrays(gl.POINTS, 0, ballCount)
956
+ state.lastDraw = {
957
+ balls: ballCount,
958
+ verts: ccx.length / 3,
959
+ // gl.getError() 是同步停顿:以前每帧问一次,采样里占 3.7% 的自身耗时。
960
+ // 只在真正需要排查时问(url 加 ?glcheck=1),平时返回 0。
961
+ err: glCheck ? gl.getError() : 0,
962
+ sample: ccx.length ? [ccx[0], ccx[1], ccx[2], csz[0]] : null,
963
+ }
964
+ state.drawCount = (state.drawCount || 0) + 1
965
+
966
+ gl.disableVertexAttribArray(bLoc.size)
967
+ gl.disableVertexAttribArray(bLoc.alpha)
968
+ gl.disableVertexAttribArray(bLoc.shape)
969
+ }
970
+
971
+ function draw() {
972
+ const cw = canvas.width
973
+ const ch = canvas.height
974
+ if (!cw || !ch) return
975
+ const t0 = performance.now()
976
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
977
+ gl.viewport(0, 0, cw, ch)
978
+ gl.clearColor(0, 0, 0, 0)
979
+ gl.clearDepth(1)
980
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
981
+ if (/(\?|&)flat=1/.test(location.search)) gl.disable(gl.DEPTH_TEST)
982
+ else gl.enable(gl.DEPTH_TEST)
983
+ gl.depthFunc(gl.LEQUAL)
984
+ drawScene()
985
+ gl.disable(gl.BLEND)
986
+ drawLabels()
987
+ // 一帧的真实主线程耗时(含顶点打包;不含浏览器合成)。用来盯大库的三维预算。
988
+ state.lastDrawMs = Math.round((performance.now() - t0) * 10) / 10
989
+ }
990
+
991
+ // ---------- labels ----------
992
+ function roundRect(c, x, y, w, h, r) {
993
+ c.beginPath()
994
+ c.moveTo(x + r, y)
995
+ c.arcTo(x + w, y, x + w, y + h, r)
996
+ c.arcTo(x + w, y + h, x, y + h, r)
997
+ c.arcTo(x, y + h, x, y, r)
998
+ c.arcTo(x, y, x + w, y, r)
999
+ c.closePath()
1000
+ }
1001
+
1002
+ function drawLabels() {
1003
+ if (!lctx) return
1004
+ const { w, h, dpr } = state.size
1005
+ lctx.setTransform(dpr, 0, 0, dpr, 0, 0)
1006
+ lctx.clearRect(0, 0, w, h)
1007
+ if (state.layout === 'spiral') drawSpiralLabels()
1008
+ else drawClusterLabels()
1009
+ drawFocusLabel()
1010
+ drawNodeLabels()
1011
+ }
1012
+
1013
+
1014
+ /**
1015
+ * 节点自己的名字:鼠标指到的那颗永远写出来,其余按「重要度 → 度数」取前 14 颗,
1016
+ * 并且只在放大到一定距离之内才出现(alpha 随距离淡出)。
1017
+ * 为什么不是全画:三万颗星星每颗配一行字,画面就成了一片字。
1018
+ */
1019
+ function drawNodeLabels() {
1020
+ if (!lctx) return
1021
+ const { w, h } = state.size
1022
+ const focus = state.hover || state.selected
1023
+ const alpha = labelAlpha(state.cam.dist, state.labelNear, state.labelFar)
1024
+ const cands = []
1025
+ let rank = 0
1026
+ if (alpha > 0.02) {
1027
+ const pool = state.nodes.filter(visible)
1028
+ pool.sort((a, b) => (b.importance || 0) - (a.importance || 0) || (b.degree || 0) - (a.degree || 0))
1029
+ for (const n of pool) {
1030
+ if (rank >= 14) break
1031
+ rank += 1
1032
+ cands.push(n)
1033
+ }
1034
+ }
1035
+ if (focus) {
1036
+ const f = state.byId.get(focus)
1037
+ if (f && cands.indexOf(f) < 0) cands.push(f)
1038
+ }
1039
+ if (!cands.length) return
1040
+ lctx.textAlign = 'center'
1041
+ lctx.font = '500 11px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1042
+ const taken = []
1043
+ for (const n of cands) {
1044
+ if (!visible(n)) continue
1045
+ const a = n.id === focus ? 1 : alpha
1046
+ if (a <= 0.02) continue
1047
+ project(n.x3, n.y3, n.z3, tmp)
1048
+ if (tmp[2] <= 1) continue
1049
+ const x = tmp[0]
1050
+ const y = tmp[1] - (tmp[3] || 0) * 0.9 - 10
1051
+ if (x < 8 || x > w - 8 || y < 64 || y > h - 20) continue
1052
+ const text = clipLabel(n.label || n.title || n.id)
1053
+ const tw = lctx.measureText(text).width
1054
+ if (taken.some((t) => Math.abs(t.x - x) < (t.w + tw) / 2 + 8 && Math.abs(t.y - y) < 13)) continue
1055
+ taken.push({ x, y, w: tw })
1056
+ lctx.globalAlpha = a
1057
+ lctx.fillStyle = 'rgba(4,6,12,0.55)'
1058
+ roundRect(lctx, x - tw / 2 - 6, y - 6, tw + 12, 15, 7)
1059
+ lctx.fill()
1060
+ lctx.fillStyle = n.id === focus ? '#ffffff' : n.color || '#9fd4ff'
1061
+ lctx.fillText(text, x, y + 5)
1062
+ lctx.globalAlpha = 1
1063
+ }
1064
+ }
1065
+
1066
+ function clipLabel(text) {
1067
+ const s = String(text || '')
1068
+ return s.length > 18 ? s.slice(0, 17) + '…' : s
1069
+ }
1070
+
1071
+ function drawClusterLabels() {
1072
+ const { w, h } = state.size
1073
+ lctx.textAlign = 'center'
1074
+ lctx.font = '500 11px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1075
+ const box = new Map()
1076
+ for (const n of state.nodes) {
1077
+ // 走 visible(),不要只看 n.hidden——3D 的筛选状态在 state.filter 里,
1078
+ // 全筛掉时还画簇名,画面就会「没有记忆」却挂着一圈名字。
1079
+ if (!visible(n)) continue
1080
+ project(n.x3, n.y3, n.z3, tmp)
1081
+ if (tmp[2] <= 1) continue
1082
+ const b = box.get(n.cluster) || { minX: 1e9, maxX: -1e9, minY: 1e9, maxY: -1e9, n: 0 }
1083
+ b.minX = Math.min(b.minX, tmp[0])
1084
+ b.maxX = Math.max(b.maxX, tmp[0])
1085
+ b.minY = Math.min(b.minY, tmp[1])
1086
+ b.maxY = Math.max(b.maxY, tmp[1])
1087
+ b.n += 1
1088
+ box.set(n.cluster, b)
1089
+ }
1090
+ const taken = []
1091
+ const cx0 = w / 2
1092
+ const cy0 = h / 2
1093
+ const R = Math.min(w, h) * 0.42
1094
+ const items = []
1095
+ for (const c of state.clusters) {
1096
+ const b = box.get(c.id)
1097
+ if (!b || b.n < 3) continue
1098
+ items.push({
1099
+ c,
1100
+ mx: (b.minX + b.maxX) / 2,
1101
+ my: (b.minY + b.maxY) / 2,
1102
+ text: String(c.title || c.label || c.id).toUpperCase(),
1103
+ })
1104
+ }
1105
+ // 标签不压在星团里:从画面中心朝星团方向推到外圈,再用一条细引导线连回去
1106
+ for (const it of items) {
1107
+ const tw = lctx.measureText(it.text).width
1108
+ let dx = it.mx - cx0
1109
+ let dy = it.my - cy0
1110
+ const len = Math.hypot(dx, dy) || 1
1111
+ dx /= len
1112
+ dy /= len
1113
+ let lx = cx0 + dx * R
1114
+ let ly = cy0 + dy * R
1115
+ lx = clamp(lx, tw / 2 + 18, w - tw / 2 - 18)
1116
+ ly = clamp(ly, 74, h - 34)
1117
+ let guard = 0
1118
+ while (taken.some((t) => Math.abs(t.x - lx) < (t.w + tw) / 2 + 10 && Math.abs(t.y - ly) < 22) && guard < 14) {
1119
+ ly += 24
1120
+ if (ly > h - 34) ly = 74
1121
+ guard += 1
1122
+ }
1123
+ taken.push({ x: lx, y: ly, w: tw })
1124
+
1125
+ lctx.strokeStyle = 'rgba(140,170,215,0.16)'
1126
+ lctx.lineWidth = 1
1127
+ lctx.beginPath()
1128
+ lctx.moveTo(it.mx, it.my)
1129
+ lctx.lineTo(lx, ly)
1130
+ lctx.stroke()
1131
+
1132
+ lctx.fillStyle = 'rgba(4,6,12,0.6)'
1133
+ roundRect(lctx, lx - tw / 2 - 8, ly - 13, tw + 16, 19, 9)
1134
+ lctx.fill()
1135
+ lctx.fillStyle = it.c.color || '#6cc8ff'
1136
+ lctx.globalAlpha = 0.92
1137
+ lctx.fillText(it.text, lx, ly)
1138
+ lctx.globalAlpha = 1
1139
+ }
1140
+ }
1141
+
1142
+ function drawSpiralLabels() {
1143
+ const { w, h } = state.size
1144
+ const sp = state.spiral
1145
+ if (!sp) return
1146
+ lctx.font = '500 10.5px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1147
+ const labelAngle = 2.35
1148
+ let ringIdx = 0
1149
+ for (const ring of sp.rings || []) {
1150
+ const steps = 120
1151
+ lctx.beginPath()
1152
+ for (let i = 0; i <= steps; i++) {
1153
+ const a = (i / steps) * TAU
1154
+ project(Math.cos(a) * ring.r, 0, Math.sin(a) * ring.r, tmp)
1155
+ if (i === 0) lctx.moveTo(tmp[0], tmp[1])
1156
+ else lctx.lineTo(tmp[0], tmp[1])
1157
+ }
1158
+ lctx.strokeStyle = 'rgba(120,160,210,0.16)'
1159
+ lctx.lineWidth = 1
1160
+ lctx.stroke()
1161
+
1162
+ // 标签错开摆,别全挤在同一条半径上被星盘盖住
1163
+ const ang = labelAngle + (ringIdx % 3) * 2.1
1164
+ project(Math.cos(ang) * ring.r, 0, Math.sin(ang) * ring.r, tmp)
1165
+ ringIdx += 1
1166
+ const label = ring.text || ring.d + T(' 天前')
1167
+ lctx.textAlign = 'left'
1168
+ const tw = lctx.measureText(label).width
1169
+ // 标签不丢:贴边就夹回视口,别因为投影出界整条都不画
1170
+ const lx = clamp(tmp[0], 24, w - tw - 20)
1171
+ const ly = clamp(tmp[1], 56, h - 24)
1172
+ lctx.fillStyle = 'rgba(4,6,12,0.62)'
1173
+ roundRect(lctx, lx - 5, ly - 12, tw + 10, 16, 7)
1174
+ lctx.fill()
1175
+ lctx.fillStyle = 'rgba(178,206,236,0.9)'
1176
+ lctx.fillText(label, lx, ly)
1177
+ }
1178
+
1179
+ project(0, 0, 0, tmp)
1180
+ lctx.textAlign = 'center'
1181
+ lctx.fillStyle = 'rgba(255,236,190,0.9)'
1182
+ lctx.fillText(T('最近'), tmp[0], tmp[1] + 4)
1183
+
1184
+ lctx.textAlign = 'center'
1185
+ const taken = []
1186
+ const swirl = 1.4 * Math.PI
1187
+ for (const arm of sp.arms || []) {
1188
+ const r = 1085
1189
+ const a = arm.angle + swirl
1190
+ project(Math.cos(a) * r, 0, Math.sin(a) * r, tmp)
1191
+ const text = String(arm.label || '').toUpperCase()
1192
+ if (!text) continue
1193
+ const tw = lctx.measureText(text).width
1194
+ const x = clamp(tmp[0], tw / 2 + 16, w - tw / 2 - 16)
1195
+ const y = clamp(tmp[1], 62, h - 30)
1196
+ if (taken.some((t) => Math.abs(t.x - x) < (t.w + tw) / 2 + 10 && Math.abs(t.y - y) < 22)) continue
1197
+ taken.push({ x, y, w: tw })
1198
+ lctx.fillStyle = 'rgba(4,6,12,0.55)'
1199
+ roundRect(lctx, x - tw / 2 - 7, y - 12, tw + 14, 17, 8)
1200
+ lctx.fill()
1201
+ lctx.fillStyle = arm.color || '#6cc8ff'
1202
+ lctx.globalAlpha = 0.9
1203
+ lctx.fillText(text, x, y)
1204
+ lctx.globalAlpha = 1
1205
+ }
1206
+ }
1207
+
1208
+ function drawFocusLabel() {
1209
+ const { w, h } = state.size
1210
+ for (const [id, strong] of [
1211
+ [state.selected, true],
1212
+ [state.hover, false],
1213
+ ]) {
1214
+ if (!id) continue
1215
+ const n = state.byId.get(id)
1216
+ if (!n || n.hidden) continue
1217
+ project(n.x3, n.y3, n.z3, tmp)
1218
+ if (tmp[2] <= 1) continue
1219
+ const rad = clamp((n.rWorld * tmp[3]) / tmp[2], 6, 30)
1220
+ lctx.beginPath()
1221
+ lctx.arc(tmp[0], tmp[1], rad + 5, 0, TAU)
1222
+ lctx.strokeStyle = strong ? 'rgba(255,224,150,0.95)' : 'rgba(220,235,255,0.55)'
1223
+ lctx.lineWidth = strong ? 1.6 : 1
1224
+ lctx.stroke()
1225
+
1226
+ const text = String(n.title || n.label || n.id).slice(0, 40)
1227
+ lctx.font = '500 11.5px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1228
+ const tw = lctx.measureText(text).width
1229
+ const x = clamp(tmp[0], tw / 2 + 16, w - tw / 2 - 16)
1230
+ const y = clamp(tmp[1] - rad - 12, 60, h - 24)
1231
+ lctx.fillStyle = 'rgba(4,6,12,0.72)'
1232
+ roundRect(lctx, x - tw / 2 - 8, y - 13, tw + 16, 19, 9)
1233
+ lctx.fill()
1234
+ lctx.fillStyle = strong ? '#ffe6a8' : '#dfeaff'
1235
+ lctx.textAlign = 'center'
1236
+ lctx.fillText(text, x, y)
1237
+ }
1238
+ }
1239
+
1240
+ // ---------- loop ----------
1241
+ let raf = 0
1242
+ // ---------- 区块点亮(3D 版) ----------
1243
+ // 2D 是「按空间网格逐格亮」,3D 没有网格可切,改成按簇分波:
1244
+ // 大簇先亮、簇内重要的先亮,后面的簇错开 110ms,整体 1.6 秒长出来。
1245
+ function startReveal() {
1246
+ const order = state.clusters
1247
+ .slice()
1248
+ .sort((a, b) => (b.size || 0) - (a.size || 0))
1249
+ .map((c) => c.id)
1250
+ const idxOf = new Map(order.map((id, i) => [id, i]))
1251
+ const delay = new Map()
1252
+ for (const n of state.nodes) {
1253
+ const ci = idxOf.has(n.cluster) ? idxOf.get(n.cluster) : order.length
1254
+ n.reveal = 0
1255
+ delay.set(n.id, ci * 110 + Math.min(220, (4 - Math.min(4, n.importance || 1)) * 40))
1256
+ }
1257
+ state.reveal = { t0: performance.now(), delay, duration: 240, done: false }
1258
+ state.cacheDirty = true
1259
+ state.needDraw = true
1260
+ return true
1261
+ }
1262
+
1263
+ function pumpReveal(now) {
1264
+ const rv = state.reveal
1265
+ if (!rv || rv.done) return
1266
+ let shown = 0
1267
+ let total = 0
1268
+ const t = now - rv.t0
1269
+ for (const n of state.nodes) {
1270
+ if (!visible(n)) continue
1271
+ total += 1
1272
+ const d = rv.delay.get(n.id) || 0
1273
+ const v = Math.max(0, Math.min(1, (t - d) / rv.duration))
1274
+ if (v !== n.reveal) {
1275
+ n.reveal = v
1276
+ state.cacheDirty = true
1277
+ }
1278
+ if (v >= 0.98) shown += 1
1279
+ }
1280
+ state.needDraw = true
1281
+ if (total && shown >= total) rv.done = true
1282
+ state.growth = { done: rv.done, shown, total }
1283
+ }
1284
+
1285
+ function tick() {
1286
+ raf = requestAnimationFrame(tick)
1287
+ if (!state.active) return
1288
+ const now = performance.now()
1289
+ pumpReveal(now)
1290
+ const cam = state.cam
1291
+ if (state.target) {
1292
+ cam.yaw += (state.target.yaw - cam.yaw) * 0.14
1293
+ cam.pitch += (state.target.pitch - cam.pitch) * 0.14
1294
+ cam.dist += (state.target.dist - cam.dist) * 0.14
1295
+ cam.tx += (state.target.tx - cam.tx) * 0.14
1296
+ cam.ty += (state.target.ty - cam.ty) * 0.14
1297
+ cam.tz += (state.target.tz - cam.tz) * 0.14
1298
+ if (Math.abs(state.target.dist - cam.dist) < 0.5) state.target = null
1299
+ } else if (state.drag ? false : state.inertia && (state.inertia.yaw || state.inertia.pitch)) {
1300
+ // 松手后的惯性:拖一下会顺着刚才的方向再滑一小段
1301
+ cam.yaw += state.inertia.yaw
1302
+ cam.pitch = clamp(cam.pitch + state.inertia.pitch, -1.35, 1.35)
1303
+ state.inertia.yaw *= 0.92
1304
+ state.inertia.pitch *= 0.92
1305
+ if (Math.abs(state.inertia.yaw) < 0.0004 && Math.abs(state.inertia.pitch) < 0.0004) {
1306
+ state.inertia.yaw = 0
1307
+ state.inertia.pitch = 0
1308
+ }
1309
+ } else if (state.spin && !state.drag) {
1310
+ cam.yaw += 0.0004
1311
+ }
1312
+
1313
+ if (state.force.running) {
1314
+ const f = state.force
1315
+ const simNodes = state.forceNodes || state.nodes
1316
+ const keep = state.forceNodes ? state.drawSet : null
1317
+ // 每帧最多 10ms 推进布局:一轮迭代可以跨几帧跑完,帧率不再被布局按住。
1318
+ // 10 而不是 16:收敛期还要留出发射顶点/投影的余量,实测中位帧间隔 12ms。
1319
+ const deadline = performance.now() + 10
1320
+ while (f.iter < f.maxIter && performance.now() < deadline) {
1321
+ if (f.phase === 0) {
1322
+ if (!f.root) {
1323
+ const tOct = performance.now()
1324
+ f.root = buildOctree(simNodes)
1325
+ // 八叉树每轮都要重建:它多贵决定了「收敛总共要多久」,记下来免得靠猜
1326
+ const tm = state.timing || (state.timing = { octreeTotal: 0, octreeBuilds: 0, octreeMax: 0 })
1327
+ const dt = performance.now() - tOct
1328
+ tm.octreeTotal += dt
1329
+ tm.octreeBuilds += 1
1330
+ if (dt > tm.octreeMax) tm.octreeMax = Math.round(dt)
1331
+ }
1332
+ f.cursor = forceRepel(simNodes, f.root, f.cursor, deadline)
1333
+ if (f.cursor >= simNodes.length) { f.phase = 1; f.cursor = 0 }
1334
+ } else if (f.phase === 1) {
1335
+ f.cursor = forceSprings(keep, f.cursor, deadline)
1336
+ if (f.cursor >= state.edges.length) { f.phase = 2; f.cursor = 0 }
1337
+ } else {
1338
+ f.cursor = forcePull(simNodes, f.cursor, deadline)
1339
+ if (f.cursor >= simNodes.length) {
1340
+ forceApply(simNodes, f.alpha)
1341
+ f.alpha *= 0.986
1342
+ f.iter += 1
1343
+ f.phase = 0
1344
+ f.cursor = 0
1345
+ f.root = null
1346
+ }
1347
+ }
1348
+ }
1349
+ if (f.iter >= f.maxIter || f.alpha < 0.02) {
1350
+ state.force.running = false
1351
+ // 收敛期为了省顶点上传不画连线,收完这一帧必须重画一次把它们补回来
1352
+ state.needDraw = true
1353
+ saveLayout(state.nodes)
1354
+ if (state.autoFit) {
1355
+ state.autoFit = false
1356
+ api.fit()
1357
+ }
1358
+ }
1359
+ }
1360
+
1361
+ for (const [id, v] of state.pulse) {
1362
+ const nv = v - 0.035
1363
+ if (nv <= 0) state.pulse.delete(id)
1364
+ else state.pulse.set(id, nv)
1365
+ }
1366
+
1367
+ // 只在「真的会变」的时候重画:静止时不再 60fps 空转(省电、也让风扇安静)
1368
+ const inertiaOn = !state.drag && state.inertia && (state.inertia.yaw || state.inertia.pitch)
1369
+ const moving =
1370
+ !!state.target || !!inertiaOn || (state.spin && !state.drag) || state.force.running || !!state.drag || state.pulse.size > 0
1371
+ if (moving || state.cacheDirty || state.needDraw) {
1372
+ // 收敛期把「算」和「画」解耦:布局一动,每帧都要重传 1.8 万个顶点(约 24ms),
1373
+ // 每帧都画等于把整个帧预算花在上传上,力场只能挤到 8ms、90 轮拖到十几秒。
1374
+ // 收敛中每 3 帧画一次,省下的时间全给力场;停下来那一帧一定画。
1375
+ let skip = false
1376
+ if (state.force.running && !state.cacheDirty && !state.needDraw && state.pulse.size === 0 && !state.drag) {
1377
+ state.settleTick = (state.settleTick || 0) + 1
1378
+ skip = state.settleTick % 4 !== 0
1379
+ } else {
1380
+ state.settleTick = 0
1381
+ }
1382
+ if (!skip) {
1383
+ state.needDraw = false
1384
+ draw()
1385
+ }
1386
+ }
1387
+ }
1388
+
1389
+ function start() {
1390
+ if (!raf) raf = requestAnimationFrame(tick)
1391
+ }
1392
+
1393
+ function resize() {
1394
+ const rect = canvas.getBoundingClientRect()
1395
+ // 和 2D 一样:隐藏时 rect 是 0,别把 WebGL 画布写成 0×0(激活时会再量一次)
1396
+ if (rect.width < 2 || rect.height < 2) return false
1397
+ const dpr = Math.min(2, window.devicePixelRatio || 1)
1398
+ state.size = { w: rect.width, h: rect.height, dpr }
1399
+ canvas.width = Math.round(state.size.w * dpr)
1400
+ canvas.height = Math.round(state.size.h * dpr)
1401
+ if (labelCanvas) {
1402
+ labelCanvas.width = canvas.width
1403
+ labelCanvas.height = canvas.height
1404
+ }
1405
+ state.needDraw = true
1406
+ }
1407
+
1408
+ // ---------- picking & pointer ----------
1409
+ function pick(sx, sy) {
1410
+ let best = null
1411
+ let bestScore = Infinity
1412
+ for (const n of state.nodes) {
1413
+ if (!visible(n)) continue
1414
+ project(n.x3, n.y3, n.z3, tmp)
1415
+ if (tmp[2] <= 1) continue
1416
+ const d = Math.hypot(tmp[0] - sx, tmp[1] - sy)
1417
+ const rpx = (n.rWorld * tmp[3]) / tmp[2]
1418
+ const tol = clamp(rpx + 7, 8, 26)
1419
+ if (d > tol) continue
1420
+ const score = d + tmp[2] * 0.02
1421
+ if (score < bestScore) {
1422
+ bestScore = score
1423
+ best = n
1424
+ }
1425
+ }
1426
+ return best
1427
+ }
1428
+
1429
+ function pos(ev) {
1430
+ const rect = canvas.getBoundingClientRect()
1431
+ return [ev.clientX - rect.left, ev.clientY - rect.top]
1432
+ }
1433
+
1434
+ canvas.addEventListener('pointerdown', (ev) => {
1435
+ const [sx, sy] = pos(ev)
1436
+ const panOnly = ev.button !== 0
1437
+ if (panOnly) ev.preventDefault()
1438
+ try {
1439
+ canvas.setPointerCapture(ev.pointerId)
1440
+ } catch (_) {}
1441
+ const n = panOnly ? null : pick(sx, sy)
1442
+ state.drag = {
1443
+ type: n ? 'node' : panOnly ? 'pan' : 'orbit',
1444
+ sx,
1445
+ sy,
1446
+ button: ev.button,
1447
+ moved: false,
1448
+ yaw: state.cam.yaw,
1449
+ pitch: state.cam.pitch,
1450
+ panX: state.cam.panX,
1451
+ panY: state.cam.panY,
1452
+ }
1453
+ canvas.style.cursor = 'grabbing'
1454
+ })
1455
+
1456
+ // 中键的默认动作是「自动滚动」,不挡住的话画面会跟着方向键图标乱跑
1457
+ canvas.addEventListener(
1458
+ 'mousedown',
1459
+ (ev) => {
1460
+ if (ev.button === 1 || ev.button === 2) ev.preventDefault()
1461
+ },
1462
+ { passive: false }
1463
+ )
1464
+ canvas.addEventListener('auxclick', (ev) => {
1465
+ if (ev.button === 1) ev.preventDefault()
1466
+ })
1467
+ canvas.addEventListener('contextmenu', (ev) => ev.preventDefault())
1468
+
1469
+ canvas.addEventListener('pointermove', (ev) => {
1470
+ const [sx, sy] = pos(ev)
1471
+ const drag = state.drag
1472
+ if (drag) {
1473
+ const dx = sx - drag.sx
1474
+ const dy = sy - drag.sy
1475
+ if (!drag.moved && Math.hypot(dx, dy) > 4) drag.moved = true
1476
+ state.target = null
1477
+ if (drag.type === 'pan') {
1478
+ // 平移用「上一帧位置」算增量:拿按下点到当前的累计位移去 += 会指数放大,
1479
+ // 手一抖画面就飞出去了(之前就是这个问题)。
1480
+ const px = sx - (drag.lx === undefined ? drag.sx : drag.lx)
1481
+ const py = sy - (drag.ly === undefined ? drag.sy : drag.ly)
1482
+ drag.lx = sx
1483
+ drag.ly = sy
1484
+ const cam = state.cam
1485
+ const cy = Math.cos(cam.yaw)
1486
+ const sy2 = Math.sin(cam.yaw)
1487
+ const cp = Math.cos(cam.pitch)
1488
+ const sp = Math.sin(cam.pitch)
1489
+ const right = [cy, 0, -sy2]
1490
+ const up = [-sp * sy2, cp, -sp * cy]
1491
+ const s = (2 * cam.dist * Math.tan((26 * Math.PI) / 180)) / Math.max(1, state.size.h)
1492
+ cam.tx += (-px * right[0] + py * up[0]) * s
1493
+ cam.ty += (-px * right[1] + py * up[1]) * s
1494
+ cam.tz += (-px * right[2] + py * up[2]) * s
1495
+ } else {
1496
+ const ny = drag.yaw - dx * 0.0055
1497
+ const np = clamp(drag.pitch + dy * 0.0045, -1.35, 1.35)
1498
+ // 记录这一帧转了多少,松手后当惯性用(阻尼在 tick 里衰减)
1499
+ state.inertia.yaw = ny - state.cam.yaw
1500
+ state.inertia.pitch = np - state.cam.pitch
1501
+ state.cam.yaw = ny
1502
+ state.cam.pitch = np
1503
+ }
1504
+ return
1505
+ }
1506
+ const n = pick(sx, sy)
1507
+ canvas.style.cursor = n ? 'pointer' : 'grab'
1508
+ const id = n ? n.id : null
1509
+ if (id !== state.hover) {
1510
+ state.hover = id
1511
+ // 悬停即预览这条记忆的邻居:边提亮、无关的压暗(和 2D 一致)
1512
+ if (!state.pinnedHighlight) api.highlight(id)
1513
+ emit('hover', n ? { id, x: sx, y: sy } : null)
1514
+ }
1515
+ })
1516
+
1517
+ canvas.addEventListener('pointerup', (ev) => {
1518
+ const drag = state.drag
1519
+ const [sx, sy] = pos(ev)
1520
+ const moved = drag && (drag.moved || Math.hypot(sx - drag.sx, sy - drag.sy) > 4)
1521
+ const button = drag ? drag.button : ev.button
1522
+ state.drag = null
1523
+ canvas.style.cursor = 'grab'
1524
+ if (!drag || button !== 0 || moved) return
1525
+ const n = pick(sx, sy)
1526
+ if (n && ev.shiftKey && state.selected && state.selected !== n.id) {
1527
+ emit('path', { from: state.selected, to: n.id })
1528
+ return
1529
+ }
1530
+ api.select(n ? n.id : null)
1531
+ emit('select', n ? n.id : null)
1532
+ })
1533
+
1534
+ canvas.addEventListener(
1535
+ 'wheel',
1536
+ (ev) => {
1537
+ ev.preventDefault()
1538
+ state.cam.dist = clamp(state.cam.dist * Math.exp(ev.deltaY * 0.0012), 180, 9000)
1539
+ },
1540
+ { passive: false }
1541
+ )
1542
+
1543
+ canvas.addEventListener('dblclick', () => api.fit())
1544
+
1545
+ // ---------- API ----------
1546
+ const api = {
1547
+ load(graph, keepView) {
1548
+ state.graph = graph
1549
+ state.clusters = (graph.clusters || []).map((c) => ({ ...c }))
1550
+ state.nodes = (graph.nodes || []).map((n) => ({ ...n }))
1551
+ state.edges = graph.edges || []
1552
+ state.byId = new Map(state.nodes.map((n) => [n.id, n]))
1553
+ state.highlightSet = null
1554
+ state.cacheDirty = true
1555
+ layout()
1556
+ startReveal()
1557
+ if (!keepView) api.fit()
1558
+ return api
1559
+ },
1560
+
1561
+ setLayout(mode) {
1562
+ const next = mode === 'spiral' ? 'spiral' : 'cluster'
1563
+ if (next === state.layout && state.nodes.length) return api
1564
+ state.layout = next
1565
+ state.cacheDirty = true
1566
+ layout()
1567
+ api.fit()
1568
+ return api
1569
+ },
1570
+
1571
+ setFilter(f) {
1572
+ const next = { ws: null, levels: null, types: null, providers: null, minW: 0, minImp: 0 }
1573
+ if (f && f.ws && f.ws.size) next.ws = f.ws
1574
+ if (f && f.levels && f.levels.size) next.levels = f.levels
1575
+ if (f && f.types && f.types.size) next.types = f.types
1576
+ if (f && f.providers && f.providers.size) next.providers = f.providers
1577
+ next.minW = (f && f.minW) || 0
1578
+ next.minImp = (f && f.minImp) || 0
1579
+ state.filter = next
1580
+ state.cacheDirty = true
1581
+ return api
1582
+ },
1583
+
1584
+ /**
1585
+ * 立刻画一帧。导出 PNG 用:WebGL 的绘制缓冲默认不保留,
1586
+ * 等 rAF 之后再去 drawImage 只会拿到一张空画布——必须在同一个同步任务里画完就取。
1587
+ */
1588
+ paintNow() {
1589
+ draw()
1590
+ return api
1591
+ },
1592
+
1593
+ /** 和 2D 同名:筛完还剩多少条。左栏那句「隐藏 N 条」在 3D 里也要说真话。 */
1594
+ visibleNodes() {
1595
+ return state.nodes.filter(visible)
1596
+ },
1597
+
1598
+ visibleEdges() {
1599
+ return state.edges.filter(visibleEdge)
1600
+ },
1601
+
1602
+ /**
1603
+ * 局部图:只看 id 周围 depth 跳以内。
1604
+ * depth <= 0 或没有 id 就是「恢复全图」——和 Obsidian 的 local graph 一样是个视图开关,
1605
+ * 检索结果、计数、导出都不受影响(那些走 visibleNodes() 之外的路径)。
1606
+ */
1607
+ setLocal(id, depth) {
1608
+ state.local = neighborhoodIds(state.edges, id, depth)
1609
+ state.localId = state.local ? id : null
1610
+ state.cacheDirty = true
1611
+ state.needDraw = true
1612
+ return api
1613
+ },
1614
+
1615
+ /** 局部图当前裁多少人:面板上那句「只看 N 条」用它,不自己再算一遍。 */
1616
+ localInfo() {
1617
+ return state.local ? { id: state.localId, count: state.local.size } : null
1618
+ },
1619
+
1620
+ /**
1621
+ * 引力四个参数(真单位:斥力 / 弹簧长度 / 项目向心 / 阻尼)。
1622
+ * 改完必须丢掉这份缓存布局重新收敛——否则滑杆动了,画面上一点变化都没有,
1623
+ * 人会以为这功能是坏的。
1624
+ */
1625
+ setForce(ui) {
1626
+ const p = forceParams(ui)
1627
+ FORCE.repulse = p.repulse
1628
+ FORCE.springRest = p.springRest
1629
+ FORCE.clusterPull = p.clusterPull
1630
+ FORCE.damping = p.damping
1631
+ try {
1632
+ localStorage.removeItem(cacheKey())
1633
+ } catch (err) {
1634
+ /* 隐私模式里 localStorage 会抛:缓存丢不掉就照旧,至少参数已经生效 */
1635
+ }
1636
+ state.cacheDirty = true
1637
+ layout()
1638
+ api.fit()
1639
+ return api
1640
+ },
1641
+
1642
+ /** 时间回放:传 0 或 null 表示解除时间闸门。 */
1643
+ setTimeCut(ms) {
1644
+ const v = Number(ms) || 0
1645
+ if (state.timeCut === v) return api
1646
+ state.timeCut = v
1647
+ state.cacheDirty = true
1648
+ state.needDraw = true
1649
+ return api
1650
+ },
1651
+
1652
+ /** pinned=true 表示这次高亮来自搜索/选中,鼠标移开也不该被清掉 */
1653
+ highlight(id, pinned) {
1654
+ state.pinnedHighlight = !!pinned
1655
+ if (!id) {
1656
+ state.highlightSet = null
1657
+ } else {
1658
+ const set = new Set([id])
1659
+ for (const e of state.edges) {
1660
+ if (e.a === id) set.add(e.b)
1661
+ else if (e.b === id) set.add(e.a)
1662
+ }
1663
+ state.highlightSet = set
1664
+ }
1665
+ state.cacheDirty = true
1666
+ return api
1667
+ },
1668
+
1669
+ /** 高亮一条证据链;传 null 清掉。与 2D 的 setPath 同构。 */
1670
+ setPath(ids) {
1671
+ if (!ids || ids.length < 2) {
1672
+ state.pathIds = null
1673
+ state.pathEdges = null
1674
+ } else {
1675
+ state.pathIds = new Set(ids)
1676
+ const edges = new Set()
1677
+ for (let i = 0; i + 1 < ids.length; i += 1) {
1678
+ const a = ids[i]
1679
+ const b = ids[i + 1]
1680
+ edges.add(a < b ? a + '|' + b : b + '|' + a)
1681
+ }
1682
+ state.pathEdges = edges
1683
+ }
1684
+ state.cacheDirty = true
1685
+ return api
1686
+ },
1687
+
1688
+ select(id) {
1689
+ state.selected = id
1690
+ state.needDraw = true
1691
+ return api
1692
+ },
1693
+
1694
+ open(id) {
1695
+ api.select(id)
1696
+ emit('select', id)
1697
+ return api
1698
+ },
1699
+
1700
+ focusNode(id, zoom) {
1701
+ const n = state.byId.get(id)
1702
+ if (!n) return api
1703
+ state.target = {
1704
+ yaw: state.cam.yaw,
1705
+ pitch: state.cam.pitch,
1706
+ dist: zoom ? Math.max(420, 2200 / zoom) : 1400,
1707
+ tx: n.x3,
1708
+ ty: n.y3,
1709
+ tz: n.z3,
1710
+ }
1711
+ return api
1712
+ },
1713
+
1714
+ /** 键盘行走用:把镜头平移到这颗星,距离(缩放)不动。 */
1715
+ centerOn(id) {
1716
+ const n = state.byId.get(id)
1717
+ if (!n) return api
1718
+ state.target = {
1719
+ yaw: state.cam.yaw,
1720
+ pitch: state.cam.pitch,
1721
+ dist: state.cam.dist,
1722
+ tx: n.x3,
1723
+ ty: n.y3,
1724
+ tz: n.z3,
1725
+ }
1726
+ return api
1727
+ },
1728
+
1729
+ /**
1730
+ * 键盘加号/减号用:推近/拉远一档。
1731
+ * 限位跟滚轮同一套(180–9000),并且要清掉补间目标,否则下一帧会被拉回去。
1732
+ */
1733
+ zoomBy(factor) {
1734
+ const f = Number(factor)
1735
+ if (!f || !isFinite(f) || f <= 0) return api
1736
+ const next = clamp(state.cam.dist / f, 180, 9000)
1737
+ if (next === state.cam.dist) return api
1738
+ state.target = null
1739
+ state.cam.dist = next
1740
+ state.needDraw = true
1741
+ return api
1742
+ },
1743
+
1744
+ fit() {
1745
+ state.target = null
1746
+ let maxR = 0
1747
+ for (const n of state.nodes) {
1748
+ if (n.hidden) continue
1749
+ const d = Math.sqrt(n.x3 * n.x3 + n.y3 * n.y3 + n.z3 * n.z3) + (n.rWorld || 4) * 2
1750
+ if (d > maxR) maxR = d
1751
+ }
1752
+ const pad = state.pad || {}
1753
+ const usableH = Math.max(200, state.size.h - (pad.top || 0) - (pad.bottom || 0))
1754
+ const usableW = Math.max(240, state.size.w - (pad.left || 0) - (pad.right || 0))
1755
+ const fovy = (52 * Math.PI) / 180
1756
+ const halfH = Math.tan(fovy / 2)
1757
+ const needH = maxR / (halfH * 0.86)
1758
+ const needW = maxR / (halfH * (usableW / usableH) * 0.86)
1759
+ const need = Math.max(needH, needW, 600)
1760
+ state.cam.tx = 0
1761
+ state.cam.ty = 0
1762
+ state.cam.tz = 0
1763
+ state.cam.panX = 0
1764
+ state.cam.panY = 0
1765
+ state.cam.dist = clamp(need, 600, 9000)
1766
+ state.cam.yaw = state.layout === 'spiral' ? 0.9 : 0.62
1767
+ state.cam.pitch = state.layout === 'spiral' ? 0.56 : 0.28
1768
+ state.needDraw = true
1769
+ return api
1770
+ },
1771
+
1772
+ pulseFrom(ids, spread) {
1773
+ const list = Array.isArray(ids) ? ids : [ids]
1774
+ for (const id of list.slice(0, 24)) state.pulse.set(id, spread ? 0.9 : 1.2)
1775
+ return api
1776
+ },
1777
+
1778
+ setPadding(p) {
1779
+ state.pad = Object.assign({ left: 16, right: 16, top: 76, bottom: 48 }, p || {})
1780
+ state.needDraw = true
1781
+ return api
1782
+ },
1783
+
1784
+ setSpin(flag) {
1785
+ state.spin = !!flag
1786
+ return api
1787
+ },
1788
+
1789
+ setActive(flag) {
1790
+ state.active = !!flag
1791
+ if (flag) {
1792
+ resize()
1793
+ start()
1794
+ }
1795
+ return api
1796
+ },
1797
+
1798
+ resize,
1799
+
1800
+ on(evt, fn) {
1801
+ ;(listeners[evt] || (listeners[evt] = [])).push(fn)
1802
+ return api
1803
+ },
1804
+
1805
+ get mode() {
1806
+ return 'space'
1807
+ },
1808
+
1809
+ screenOf(id) {
1810
+ const n = state.byId.get(id)
1811
+ if (!n || !visible(n)) return null
1812
+ project(n.x3, n.y3, n.z3, tmp)
1813
+ return { x: tmp[0], y: tmp[1], r: (n.rWorld * tmp[3]) / tmp[2] }
1814
+ },
1815
+
1816
+ /** 与 2D 同名的进度口:顶部「正在生长…」进度条在 3D 里也走它 */
1817
+ progress() {
1818
+ return state.growth || { done: true, shown: 0, total: 0 }
1819
+ },
1820
+
1821
+ debug() {
1822
+ let sampleId = null
1823
+ for (const n of state.nodes) {
1824
+ if (!visible(n)) continue
1825
+ const p = api.screenOf(n.id)
1826
+ if (!p) continue
1827
+ if (p.x > 380 && p.x < state.size.w - 120 && p.y > 120 && p.y < state.size.h - 90) {
1828
+ sampleId = n.id
1829
+ break
1830
+ }
1831
+ }
1832
+ const rs = []
1833
+ for (const n of state.nodes) {
1834
+ if (!visible(n)) continue
1835
+ project(n.x3, n.y3, n.z3, tmp)
1836
+ if (tmp[2] <= 1) continue
1837
+ rs.push((n.rWorld * tmp[3]) / tmp[2])
1838
+ }
1839
+ rs.sort((a, b) => a - b)
1840
+ return {
1841
+ mode: 'space',
1842
+ layout: state.layout,
1843
+ nodes: state.nodes.length,
1844
+ edges: state.edges.length,
1845
+ cam: { ...state.cam },
1846
+ size: { ...state.size },
1847
+ selected: state.selected,
1848
+ sampleId,
1849
+ rpx: rs.length ? { min: +rs[0].toFixed(2), med: +rs[Math.floor(rs.length / 2)].toFixed(2), max: +rs[rs.length - 1].toFixed(2) } : null,
1850
+ lastDraw: state.lastDraw || null,
1851
+ drawMs: state.lastDrawMs == null ? null : state.lastDrawMs,
1852
+ // 三维的绘制预算:sampled=true 表示这张图只画了重要度前 limit 条
1853
+ budget: state.budget || null,
1854
+ drawCount: state.drawCount || 0,
1855
+ force: { running: state.force.running, iter: state.force.iter, alpha: +state.force.alpha.toFixed(3), phase: state.force.phase || 0, cursor: state.force.cursor || 0, timing: state.timing || null },
1856
+ spin: !!state.spin,
1857
+ // 诊断用:当前真正「可见」的点/线数——时间回放、筛选、隐藏都只改这一层,
1858
+ // 探针量这里就能确认闸门有没有生效,不必去数像素。
1859
+ visible: (() => {
1860
+ let vn = 0
1861
+ for (const n of state.nodes) if (visible(n)) vn++
1862
+ let ve = 0
1863
+ for (const e of state.edges) if (visibleEdge(e)) ve++
1864
+ return { nodes: vn, edges: ve }
1865
+ })(),
1866
+ spiral:
1867
+ state.layout === 'spiral'
1868
+ ? { maxAgeDays: Math.round(state.spiral.maxAge / 86400000), rings: state.spiral.rings.length, arms: state.spiral.arms.length }
1869
+ : null,
1870
+ }
1871
+ },
1872
+ }
1873
+
1874
+ window.addEventListener('resize', () => {
1875
+ if (state.active) resize()
1876
+ })
1877
+
1878
+ window.__nebula3d = api
1879
+ return api
1880
+ }
1881
+
1882
+ window.NebulaSpace = { create, LEVEL_COLOR, TYPE_COLOR, neighborhoodIds, forceParams, labelAlpha, FORCE_BASE }
1883
+ })()