@vitessce/comparative 0.0.1 → 3.9.5

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -18
  3. package/dist/OrbitControls-BwflPmLE.js +6202 -0
  4. package/dist/ReactNeuroglancer-UbR-Ehra.js +43478 -0
  5. package/dist/blosc-DKW2fp0s.js +716 -0
  6. package/dist/chunk-INHXZS53-DiyuLb3Z.js +14 -0
  7. package/dist/deflate-DFQkIOhL.js +10 -0
  8. package/dist/higlass-DHc5-L51.js +92988 -0
  9. package/dist/index-BLxG4AHN.js +3127 -0
  10. package/dist/index-DAP0IGbf.js +6178 -0
  11. package/dist/index-cJZeOqnJ.js +283191 -0
  12. package/dist/index.min.js +43 -0
  13. package/dist/jpeg-DalHlKqK.js +533 -0
  14. package/dist/lerc-Bj34z9Qs.js +1032 -0
  15. package/dist/lz4-D5NbssRf.js +640 -0
  16. package/dist/lzw-N9cMPzo2.js +84 -0
  17. package/dist/packbits-DGrkR5HU.js +24 -0
  18. package/dist/pako.esm-D68R8YXe.js +1071 -0
  19. package/dist/raw-D6zj6koi.js +9 -0
  20. package/dist/troika-three-text.esm-C-0BO8OV.js +4192 -0
  21. package/dist/webimage-D1WQPC9_.js +19 -0
  22. package/dist/zstd-DoGJTjDa.js +603 -0
  23. package/dist-tsc/BiomarkerSelect.d.ts +2 -0
  24. package/dist-tsc/BiomarkerSelect.d.ts.map +1 -0
  25. package/dist-tsc/BiomarkerSelect.js +65 -0
  26. package/dist-tsc/ComparativeConfig.d.ts +12 -0
  27. package/dist-tsc/ComparativeConfig.d.ts.map +1 -0
  28. package/dist-tsc/ComparativeConfig.js +326 -0
  29. package/dist-tsc/ControlledComparative.d.ts +30 -0
  30. package/dist-tsc/ControlledComparative.d.ts.map +1 -0
  31. package/dist-tsc/ControlledComparative.js +95 -0
  32. package/dist-tsc/UncontrolledComparative.d.ts +10 -0
  33. package/dist-tsc/UncontrolledComparative.d.ts.map +1 -0
  34. package/dist-tsc/UncontrolledComparative.js +50 -0
  35. package/dist-tsc/index.d.ts +7 -0
  36. package/dist-tsc/index.d.ts.map +1 -0
  37. package/dist-tsc/index.js +14 -0
  38. package/package.json +53 -16
  39. package/src/BiomarkerSelect.jsx +107 -0
  40. package/src/ComparativeConfig.jsx +562 -0
  41. package/src/ControlledComparative.jsx +140 -0
  42. package/src/UncontrolledComparative.jsx +88 -0
  43. package/src/index.js +18 -0
  44. package/dist/index.d.ts +0 -4
  45. package/dist/index.js +0 -9
@@ -0,0 +1,3127 @@
1
+ import { aw as n, ax as we, ay as se, ar as ue, as as ze, az as _e, l as he, aA as ke, aB as Ie, m as re, aC as le, e as C, V as _, ag as Z, ae as De, aq as M, aD as Me, aE as Pe, av as Ae, W as Be, ad as Ne, z as Ue, aF as Le, aG as j, ao as N, aH as Oe, am as Fe } from "./index-cJZeOqnJ.js";
2
+ import { useRef as P, useState as fe, useMemo as de, useEffect as $, Suspense as Ve } from "react";
3
+ import { u as ve, a as Ge, O as me, C as qe } from "./OrbitControls-BwflPmLE.js";
4
+ const S = 32, B = 64, G = 64, ce = 4, oe = B * G * ce, ge = B * S, xe = G * S, pe = ce * S, V = {
5
+ NOT_STARTED: "not_started",
6
+ IN_PROGRESS: "in_progress",
7
+ COMPLETE: "complete",
8
+ FAILED: "failed"
9
+ };
10
+ function z(f) {
11
+ se(le.DEBUG) && console.warn(`%cDM: ${f}`, "background: blue; color: white; padding: 2px; border-radius: 3px;");
12
+ }
13
+ function Ze(f) {
14
+ return f.map((t) => {
15
+ const { dims: e } = t;
16
+ return [
17
+ // Other spatial-accelerated code assumes TCZYX dimension order
18
+ e.t,
19
+ // TODO: standardize lowercase/uppercase dim names at store-level
20
+ e.c,
21
+ // TODO: handle case when dimension(s) are missing
22
+ e.z,
23
+ e.y,
24
+ e.x
25
+ ];
26
+ });
27
+ }
28
+ function Xe(f) {
29
+ return f.map((t) => {
30
+ const e = [
31
+ t.depth,
32
+ // z
33
+ t.height,
34
+ // y
35
+ t.width
36
+ // x
37
+ ];
38
+ return [
39
+ Math.ceil((e[0] || 1) / S),
40
+ Math.ceil((e[1] || 1) / S),
41
+ Math.ceil((e[2] || 1) / S)
42
+ ];
43
+ });
44
+ }
45
+ function je(f, t) {
46
+ n.debug("_initMRMCPT", f, t);
47
+ const e = {
48
+ channelOffsets: [
49
+ [0, 0, 1],
50
+ [0, 1, 0],
51
+ [0, 1, 1],
52
+ [1, 0, 0],
53
+ [1, 0, 1],
54
+ [1, 1, 0],
55
+ [1, 1, 1]
56
+ ],
57
+ anchors: [],
58
+ offsets: [],
59
+ xExtent: 0,
60
+ // includes the offset inclusive
61
+ yExtent: 0,
62
+ // includes the offset inclusive
63
+ zExtent: 0,
64
+ // includes the offset inclusive
65
+ z0Extent: 0,
66
+ // l0 z extent
67
+ zTotal: 0
68
+ // original z extent plus the l0 z extent times the channel count
69
+ };
70
+ e.xExtent = 1, e.yExtent = 1, e.zExtent = 1;
71
+ const i = f[0][0];
72
+ e.z0Extent = i, e.lowestDataRes = f.length - 1;
73
+ for (let u = f.length - 1; u > 0; u--)
74
+ e.anchors.push([
75
+ e.xExtent,
76
+ e.yExtent,
77
+ e.zExtent
78
+ ]), e.xExtent += f[u][2], e.yExtent += f[u][1], e.zExtent += f[u][0];
79
+ e.anchors.push([0, 0, e.zExtent]), e.anchors.reverse(), e.zTotal = e.zExtent + t * i;
80
+ const a = new Uint8Array(ge * xe * pe);
81
+ a.fill(0);
82
+ const r = new Uint32Array(e.xExtent * e.yExtent * e.zTotal);
83
+ r.fill(0);
84
+ const o = new ue(a, ge, xe, pe);
85
+ o.format = ze, o.type = _e, o.internalFormat = "R8", o.minFilter = he, o.magFilter = he, o.generateMipmaps = !1, o.needsUpdate = !0;
86
+ const l = new ue(r, e.xExtent, e.yExtent, e.zTotal);
87
+ return l.format = ke, l.type = Ie, l.internalFormat = "R32UI", l.minFilter = re, l.magFilter = re, l.generateMipmaps = !1, l.needsUpdate = !0, n.debug("_initMRMCPT", e, l, o), {
88
+ PT: e,
89
+ ptTHREE: l,
90
+ bcTHREE: o
91
+ };
92
+ }
93
+ function Ye(f, t, e, i, a) {
94
+ const r = (o) => Math.max(0, Math.min(127, Math.floor(o / 2)));
95
+ return (1 << 31 | 1 << 30 | r(f) << 23 | r(t) << 16 | (e & 63) << 10 | (i & 63) << 4 | a & 15) >>> 0;
96
+ }
97
+ function He(f, t, e, i) {
98
+ const { PT_zExtent: a, PT_z0Extent: r, PT_anchors: o } = i;
99
+ let l = -1, u = -1, s = -1, v = -1, g = -1;
100
+ if (e >= a)
101
+ u = 0, s = f, v = t, g = (e - a) % r, l = Math.floor((e - a) / r);
102
+ else
103
+ for (let c = 1; c < o.length; c++)
104
+ if (!(f < o[c][0] && t < o[c][1] && e < o[c][2])) {
105
+ u = c;
106
+ const d = [0, 0, 0];
107
+ f >= o[c][0] && (d[0] = 1), t >= o[c][1] && (d[1] = 1), e >= o[c][2] && (d[2] = 1);
108
+ const m = d[0] << 2 | d[1] << 1 | d[2];
109
+ l = Math.max(1, Math.min(7, m)) - 1;
110
+ const h = d.map((x, b) => x * o[c][b]);
111
+ s = f - h[0], v = t - h[1], g = e - h[2];
112
+ break;
113
+ }
114
+ return {
115
+ channel: l,
116
+ resolution: u,
117
+ x: s,
118
+ y: v,
119
+ z: g
120
+ };
121
+ }
122
+ const Ke = 0.25;
123
+ function We(f, t, e) {
124
+ const i = /* @__PURE__ */ new Map(), { width: a, height: r, sigmaNormalized: o } = e, l = Number.isInteger(a) && Number.isInteger(r) && a > 0 && r > 0 && typeof o == "number";
125
+ l || n.warn("_requestBufferToRequestObjects: proceeding without weighting");
126
+ const u = Math.floor(f.length / 4);
127
+ for (let v = 0; v < u; v += 1) {
128
+ const g = v * 4, c = f[g], d = f[g + 1], m = f[g + 2], h = f[g + 3];
129
+ if ((c | d | m | h) === 0)
130
+ continue;
131
+ const x = (c << 24 | d << 16 | m << 8 | h) >>> 0;
132
+ let b = 1;
133
+ if (l) {
134
+ const R = v % a, E = Math.floor(v / a), k = R - a / 2, O = E - r / 2, T = Math.sqrt(k * k / (a * a) + O * O / (r * r)) / o;
135
+ b = Math.exp(-0.5 * T * T);
136
+ }
137
+ i.set(x, (i.get(x) || 0) + b);
138
+ }
139
+ return { requests: [...i.entries()].sort((v, g) => g[1] - v[1]).slice(0, t).map(([v]) => ({
140
+ x: v >> 22 & 1023,
141
+ y: v >> 12 & 1023,
142
+ z: v & 4095
143
+ })), origRequestCount: i.size };
144
+ }
145
+ class $e {
146
+ constructor(t) {
147
+ z("CLASS INITIALIZING"), n.debug("VolumeDataManager constructor", { glParam: t, glParamContext: t.getContext?.() });
148
+ const e = t.getContext?.() || t, i = t;
149
+ e.domElement && e.getContext ? this.gl = e.getContext() : e.isWebGLRenderer ? this.gl = e.getContext() : this.gl = e, this.renderer = i, (!this.gl || typeof this.gl.getParameter != "function") && (n.debug("Unable to get WebGL context, using mock context"), this.gl = {
150
+ getParameter: (a) => ({
151
+ MAX_TEXTURE_SIZE: 4096,
152
+ MAX_3D_TEXTURE_SIZE: 256,
153
+ MAX_RENDERBUFFER_SIZE: 4096,
154
+ MAX_UNIFORM_BUFFER_BINDINGS: 16
155
+ })[a] || 0,
156
+ isContextLost: () => !1,
157
+ MAX_TEXTURE_SIZE: "MAX_TEXTURE_SIZE",
158
+ MAX_3D_TEXTURE_SIZE: "MAX_3D_TEXTURE_SIZE",
159
+ MAX_RENDERBUFFER_SIZE: "MAX_RENDERBUFFER_SIZE",
160
+ MAX_UNIFORM_BUFFER_BINDINGS: "MAX_UNIFORM_BUFFER_BINDINGS"
161
+ }), this._originalGlParam = t, this._isContextLost = !1, this._contextRestoredCallbacks = [], this.gl && this.gl.canvas && (this.gl.canvas.addEventListener("webglcontextlost", this._handleContextLost.bind(this)), this.gl.canvas.addEventListener("webglcontextrestored", this._handleContextRestored.bind(this))), n.debug("GL CONSTANTS"), n.debug(this.gl), n.debug(this.gl.TEXTURE0), n.debug(this.gl.textures), n.debug("RENDERER"), n.debug(this.renderer), this.deviceLimits = {
162
+ maxTextureSize: this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE),
163
+ max3DTextureSize: this.gl.getParameter(this.gl.MAX_3D_TEXTURE_SIZE),
164
+ maxRenderbufferSize: this.gl.getParameter(this.gl.MAX_RENDERBUFFER_SIZE),
165
+ maxUniformBufferBindings: this.gl.getParameter(this.gl.MAX_UNIFORM_BUFFER_BINDINGS)
166
+ }, this.zarrStore = {
167
+ resolutions: null,
168
+ // 6 (the number of resolutions aka. pyramid levels in the file)
169
+ chunkSize: [],
170
+ // [32, 32, 32]
171
+ shapes: [],
172
+ // [[795, 1024, 1024], ..., [64, 64, 64], [32, 32, 32]]
173
+ arrays: [],
174
+ // [array0, array1, array2, array3, array4, array5]
175
+ dtype: "",
176
+ // 'uint8'
177
+ physicalSizeTotal: [],
178
+ // [795 x 0.0688, 1024 x 0.03417, 1024 x 0.03417]
179
+ physicalSizeVoxel: [],
180
+ // [0.0688, 0.03417, 0.03417]
181
+ brickLayout: [],
182
+ // [[25, 32, 32],[13, 16, 16], ..., [2,2,2],[1,1,1]]
183
+ // store: '', // ref to this.store
184
+ // group: '', // ref to this.group
185
+ channelCount: 1,
186
+ // MAX 7 TODO: get from zarr metadata
187
+ scales: [],
188
+ // downsample ratios, [x,y,z] per resolution level
189
+ lowestDataRes: 0
190
+ // lowest resolution level with data
191
+ }, this.ptTHREE = null, this.bcTHREE = null, this.channels = {
192
+ maxChannels: 7,
193
+ // lower when dataset has fewer, dictates page table size
194
+ zarrMappings: [],
195
+ // stores the zarr channel index for every one of the up to 7 channels
196
+ colorMappings: [],
197
+ // stores the PT slot for every color
198
+ downsampleMin: [],
199
+ // stores the downsample min for every one of the up to 7 channels
200
+ downsampleMax: []
201
+ // stores the downsample max for every one of the up to 7 channels
202
+ }, this.PT = {
203
+ channelOffsets: [
204
+ [0, 0, 1],
205
+ [0, 1, 0],
206
+ [0, 1, 1],
207
+ [1, 0, 0],
208
+ [1, 0, 1],
209
+ [1, 1, 0],
210
+ [1, 1, 1]
211
+ ],
212
+ anchors: [],
213
+ offsets: [],
214
+ xExtent: 0,
215
+ // includes the offset inclusive
216
+ yExtent: 0,
217
+ // includes the offset inclusive
218
+ zExtent: 0,
219
+ // includes the offset inclusive
220
+ z0Extent: 0,
221
+ // l0 z extent
222
+ zTotal: 0
223
+ // original z extent plus the l0 z extent times the channel count
224
+ }, this.bricksEverLoaded = /* @__PURE__ */ new Set(), this.isBusy = !1, this.BCTimeStamps = new Array(oe).fill(0), this.BCMinMax = new Array(oe).fill([0, 0]), this.BCFull = !1, this.BCUnusedIndex = 0, this.bc2pt = new Array(oe).fill(null), this.LRUStack = [], this.triggerUsage = !0, this.triggerRequest = !1, this.timeStamp = 0, this.k = 40, this.noNewRequests = !1, this.manuallyStopped = !1, this.needsBailout = !1, this.initStatus = V.NOT_STARTED, this.initError = null, this._lastChannelConfig = null, this.currentRequestCount = 0, this.totalBricksRequested = 0, z("VolumeDataManager constructor complete");
225
+ }
226
+ /**
227
+ * Get loading progress information
228
+ * @returns {Object} Loading progress with bricksLoaded, totalBricks, isLoading, and percentage
229
+ */
230
+ getLoadingProgress() {
231
+ const t = this.bricksEverLoaded.size, e = !this.noNewRequests && this.currentRequestCount > 0, i = this.totalBricksRequested > 0 ? (this.totalBricksRequested - this.currentRequestCount) / this.totalBricksRequested * 100 : 0;
232
+ return {
233
+ bricksLoaded: t,
234
+ currentRequestCount: this.currentRequestCount,
235
+ totalBricksRequested: this.totalBricksRequested,
236
+ isLoading: e,
237
+ percentage: i,
238
+ noNewRequests: this.noNewRequests
239
+ };
240
+ }
241
+ /**
242
+ * Manually stop loading and render at highest resolution
243
+ */
244
+ stopLoading() {
245
+ n.debug("Manually stopping data loading"), this.noNewRequests = !0, this.manuallyStopped = !0, this.needsBailout = !0, this.currentRequestCount = 0, this.totalBricksRequested = 0;
246
+ }
247
+ /**
248
+ * Manually restart loading
249
+ */
250
+ restartLoading() {
251
+ n.debug("Manually restarting data loading"), this.noNewRequests = !1, this.manuallyStopped = !1, this.needsBailout = !1, this.triggerUsage = !0, this.currentRequestCount = 0, this.totalBricksRequested = 0;
252
+ }
253
+ /**
254
+ * Handle WebGL context loss
255
+ */
256
+ _handleContextLost(t) {
257
+ z("CONTEXT LOST"), n.warn("WebGL context lost, preventing default and setting flag"), t.preventDefault(), this._isContextLost = !0, this.channels && this.channels.zarrMappings && (this._lastChannelConfig = {
258
+ zarrMappings: [...this.channels.zarrMappings],
259
+ colorMappings: [...this.channels.colorMappings],
260
+ downsampleMin: [...this.channels.downsampleMin],
261
+ downsampleMax: [...this.channels.downsampleMax]
262
+ });
263
+ }
264
+ /**
265
+ * Handle WebGL context restoration
266
+ */
267
+ _handleContextRestored(t) {
268
+ if (z("CONTEXT RESTORED"), n.warn("WebGL context restored, reinitializing textures"), this._isContextLost = !1, this._originalGlParam && this._originalGlParam.getContext && (this.gl = this._originalGlParam.getContext()), this._lastChannelConfig && (this.channels.zarrMappings = [...this._lastChannelConfig.zarrMappings], this.channels.colorMappings = [...this._lastChannelConfig.colorMappings], this.channels.downsampleMin = [...this._lastChannelConfig.downsampleMin], this.channels.downsampleMax = [...this._lastChannelConfig.downsampleMax], n.debug("Restored channel configuration after context loss")), this.PT && this.zarrStore && this.zarrStore.brickLayout)
269
+ try {
270
+ this.initMRMCPT(), n.debug("Successfully reinitialized MRMCPT after context restoration");
271
+ } catch (e) {
272
+ n.error("Failed to reinitialize MRMCPT after context restoration:", e);
273
+ }
274
+ this._contextRestoredCallbacks.forEach((e) => {
275
+ try {
276
+ e();
277
+ } catch (i) {
278
+ n.error("Error in context restored callback:", i);
279
+ }
280
+ });
281
+ }
282
+ /**
283
+ * Check if WebGL context is lost
284
+ */
285
+ isContextLost() {
286
+ return this._isContextLost ? !0 : this.gl && typeof this.gl.isContextLost == "function" ? this.gl.isContextLost() : !1;
287
+ }
288
+ /**
289
+ * Register a callback to be called when context is restored
290
+ */
291
+ onContextRestored(t) {
292
+ typeof t == "function" && this._contextRestoredCallbacks.push(t);
293
+ }
294
+ initImages(t, e) {
295
+ z("INIT IMAGES"), this.images = t, this.imageLayerScopes = e;
296
+ }
297
+ /**
298
+ * Initialize the VolumeDataManager with Zarr store details and device limits
299
+ * This should be called ONCE at website initialization
300
+ * TODO(mark): merge this with the constructor?
301
+ * @returns {Promise<Object>} Object with Zarr store details and device limits
302
+ */
303
+ async init(t) {
304
+ if (z("INIT()"), this.initStatus !== V.NOT_STARTED)
305
+ return n.debug("VolumeDataManager init() was called more than once!"), this.initStatus === V.COMPLETE ? {
306
+ success: !0,
307
+ deviceLimits: this.deviceLimits,
308
+ zarrStore: this.zarrStore,
309
+ // physicalScale: this.physicalScale,
310
+ physicalSizeTotal: this.zarrStore.physicalSizeTotal,
311
+ physicalSizeVoxel: this.zarrStore.physicalSizeVoxel,
312
+ error: null
313
+ } : this.initStatus === V.FAILED ? {
314
+ success: !1,
315
+ error: this.initError || "Unknown initialization error"
316
+ } : {
317
+ success: !1,
318
+ pending: !0,
319
+ error: "Initialization in progress"
320
+ };
321
+ this.initStatus = V.IN_PROGRESS, z("INIT() IN PROGRESS");
322
+ try {
323
+ const e = this.images?.[this.imageLayerScopes?.[0]]?.image?.instance;
324
+ if (this.ngffMetadata = e.vivLoader.metadata, n.debug("ngffMetadata", this.ngffMetadata), !e || e.getType() !== "ome-zarr")
325
+ throw new Error("Invalid imageWrapper or not an OME-Zarr image");
326
+ const i = e.getMultiResolutionStats(), a = Ze(i), r = i.length;
327
+ this.zarrStore.resolutions = r;
328
+ const o = e.getData();
329
+ if (!Array.isArray(o) || o.length < 1)
330
+ throw new Error("Not a multiresolution loader");
331
+ if (!we(o[0].labels, ["t", "c", "z", "y", "x"]))
332
+ throw new Error("Expected OME-Zarr data with dimensions [t, c, z, y, x]");
333
+ n.debug("vivData", o);
334
+ const l = o.map((s) => s._data), u = new Array(r).fill(null);
335
+ if (l.length > 0) {
336
+ const s = l[0];
337
+ if (this.zarrStore = {
338
+ resolutions: r,
339
+ chunkSize: s.chunks,
340
+ shapes: a,
341
+ arrays: l,
342
+ dtype: s.dtype,
343
+ physicalSizeTotal: [],
344
+ // Will be populated if metadata exists
345
+ physicalSizeVoxel: [],
346
+ // Will be populated if metadata exists
347
+ brickLayout: [],
348
+ // Calculate from shapes and chunk sizes
349
+ // store: this.store,
350
+ // group: this.group,
351
+ channelCount: a[0][1],
352
+ scales: u
353
+ }, this.channels.colorMappings = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(-1), this.channels.zarrMappings = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), this.channels.downsampleMin = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), this.channels.downsampleMax = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), s.meta && s.meta.physicalSizes) {
354
+ const { x: d, y: m, z: h } = s.meta.physicalSizes, x = h?.size || 1, b = m?.size || 1, R = d?.size || 1;
355
+ this.zarrStore.physicalSizeVoxel = [x, b, R], s.shape && s.shape.length >= 5 && (this.zarrStore.physicalSizeTotal = [
356
+ (s.shape[2] || 1) * x,
357
+ (s.shape[3] || 1) * b,
358
+ (s.shape[4] || 1) * R
359
+ ]);
360
+ } else
361
+ this.zarrStore.physicalSizeVoxel = [1, 1, 1], this.zarrStore.physicalSizeTotal = [
362
+ s.shape[2] || 1,
363
+ s.shape[3] || 1,
364
+ s.shape[4] || 1
365
+ ];
366
+ const { multiscales: v } = this.ngffMetadata;
367
+ if (!v)
368
+ throw new Error("Expected multiscales metadata in group.attrs");
369
+ if (v?.[0]?.datasets?.[0]?.coordinateTransformations) {
370
+ for (let d = 0; d < r; d++)
371
+ if (v?.[0]?.datasets?.[d]?.coordinateTransformations?.[0]?.scale) {
372
+ const { scale: m } = v[0].datasets[d].coordinateTransformations[0];
373
+ u[d] = [m[4], m[3], m[2]];
374
+ }
375
+ } else {
376
+ n.error("no coordinateTransformations available, assuming downsampling ratio of 2 per dimension");
377
+ for (let d = 0; d < r; d++) {
378
+ const m = 2 ** d;
379
+ u[d] = [m, m, m];
380
+ }
381
+ }
382
+ this.zarrStore.scales = u;
383
+ const { coordinateTransformations: g } = this.ngffMetadata;
384
+ if (g?.[0]?.scale) {
385
+ const { scale: d } = g[0], m = d.length;
386
+ if (m >= 3) {
387
+ const h = d[m - 3], x = d[m - 2], b = d[m - 1];
388
+ this.zarrStore.physicalSizeVoxel = [h, x, b], s.shape && s.shape.length >= 5 && (this.zarrStore.physicalSizeTotal = [
389
+ (s.shape[2] || 1) * h,
390
+ (s.shape[3] || 1) * x,
391
+ (s.shape[4] || 1) * b
392
+ ]);
393
+ }
394
+ }
395
+ this.zarrStore.brickLayout = Xe(e.getMultiResolutionStats()), n.debug("config", t);
396
+ const { omero: c } = this.ngffMetadata || {};
397
+ if (!c)
398
+ throw new Error("Expected omero metadata in ngffMetadata");
399
+ n.debug("omero", c), Object.keys(t).forEach((d, m) => {
400
+ const h = t[d].spatialTargetC;
401
+ this.channels.zarrMappings[m] = h, this.channels.colorMappings[m] = m, this.channels.downsampleMin[m] = c?.channels?.[h]?.window?.min || 0, this.channels.downsampleMax[m] = c?.channels?.[h]?.window?.max || 65535;
402
+ }), n.debug("zarrMappings after init", this.channels.zarrMappings), n.debug("colorMappings after init", this.channels.colorMappings), n.debug("downsampleMin after init", this.channels.downsampleMin), n.debug("downsampleMax after init", this.channels.downsampleMax), this.initMRMCPT();
403
+ }
404
+ return this.initStatus = V.COMPLETE, z("INIT() COMPLETE"), {
405
+ success: !0,
406
+ deviceLimits: this.deviceLimits,
407
+ zarrStore: this.zarrStore,
408
+ // physicalScale: this.physicalScale,
409
+ physicalSizeTotal: this.zarrStore.physicalSizeTotal,
410
+ physicalSizeVoxel: this.zarrStore.physicalSizeVoxel,
411
+ error: null
412
+ };
413
+ } catch (e) {
414
+ return z("INIT() FAILED"), n.error("Error initializing VolumeDataManager:", e), this.initStatus = V.FAILED, this.initError = e.message || "Unknown error", {
415
+ success: !1,
416
+ error: this.initError
417
+ };
418
+ }
419
+ }
420
+ /**
421
+ * Initialize the BrickCache and PageTable
422
+ * MRMCPT: multi-resolution multi-channel page table
423
+ *
424
+ * Depends on:
425
+ * - zarrStore.brickLayout
426
+ * - zarrMappings.length (zarrMappings: the zarr channel index for every one of the up to 7 channels)
427
+ * -
428
+ */
429
+ initMRMCPT() {
430
+ z("initMRMCPT");
431
+ const { PT: t, ptTHREE: e, bcTHREE: i } = je(this.zarrStore.brickLayout, this.channels.zarrMappings.length);
432
+ this.PT = t, this.ptTHREE = e, this.bcTHREE = i, z("initMRMCPT() COMPLETE");
433
+ }
434
+ async initTexture() {
435
+ const t = [
436
+ { x: 0, y: 0, z: 1 }
437
+ ];
438
+ z("initTexture - loading first brick"), await this.handleBrickRequests(t);
439
+ }
440
+ updateChannels(t) {
441
+ if (z("updateChannels"), n.debug("channelProps", t), n.debug("this.channels.zarrMappings", this.channels.zarrMappings), n.debug("this.channels.colorMappings", this.channels.colorMappings), n.debug("this.channels.downsampleMin", this.channels.downsampleMin), n.debug("this.channels.downsampleMax", this.channels.downsampleMax), this.channels.zarrMappings.length === 0) {
442
+ n.debug("channels not initialized yet");
443
+ return;
444
+ }
445
+ const e = Object.values(t).map((l) => l.spatialTargetC).filter((l) => l !== void 0), i = this.channels.zarrMappings.filter((l) => l !== void 0), a = [...new Set(e)].sort((l, u) => l - u), r = [...new Set(i)].sort((l, u) => l - u);
446
+ a.length === r.length && a.every((l, u) => l === r[u]) && n.debug("Channel mappings unchanged, skipping update"), n.debug("Channel mappings changed:", {
447
+ current: r,
448
+ requested: a
449
+ }), Object.entries(t).forEach(([l, u]) => {
450
+ const s = u.spatialTargetC;
451
+ n.debug(`UI channel "${l}" wants zarr channel ${s}`);
452
+ const v = this.channels.zarrMappings.indexOf(s);
453
+ if (v === -1) {
454
+ const g = this.channels.zarrMappings.findIndex((c) => c === void 0);
455
+ if (g !== -1)
456
+ this.channels.zarrMappings[g] = s, n.debug("channelData", u), n.debug("this.ngffMetadata?.omero?.channels", this.ngffMetadata?.omero?.channels), n.debug("targetZarrChannel", s), this.channels.downsampleMin[g] = this.ngffMetadata?.omero?.channels?.[s]?.window?.min || 0, this.channels.downsampleMax[g] = this.ngffMetadata?.omero?.channels?.[s]?.window?.max || 65535, n.debug(`Mapped zarr channel ${s} to slot ${g}`), n.debug("channels", this.channels);
457
+ else {
458
+ n.debug("No free slots found, looking for unused mapped channels");
459
+ const c = this.channels.zarrMappings.filter((h) => h !== void 0), d = e, m = c.filter((h) => !d.includes(h));
460
+ if (n.debug("Currently mapped:", c), n.debug("Still requested:", d), n.debug("Unused mapped channels:", m), m.length > 0) {
461
+ const h = this.channels.zarrMappings.findIndex((x) => m.includes(x));
462
+ if (h !== -1) {
463
+ const x = this.channels.zarrMappings[h];
464
+ this.channels.zarrMappings[h] = s, this.channels.downsampleMin[h] = this.ngffMetadata?.omero?.channels?.[s]?.window?.min || 0, this.channels.downsampleMax[h] = this.ngffMetadata?.omero?.channels?.[s]?.window?.max || 65535, n.debug(`Reused slot ${h}: ${x} -> ${s}`), this._purgeChannel(h);
465
+ } else
466
+ n.error("Could not find slot to reuse - this should not happen");
467
+ } else
468
+ n.error("All slots are full and all mapped channels are still in use");
469
+ }
470
+ } else
471
+ n.debug(`Zarr channel ${s} already mapped to slot ${v}`);
472
+ });
473
+ const o = Object.values(t).map((l) => {
474
+ const u = this.channels.zarrMappings.indexOf(l.spatialTargetC);
475
+ return u !== -1 ? u : -1;
476
+ });
477
+ for (; o.length < 7; )
478
+ o.push(-1);
479
+ n.debug("newColorMappings", o), this.channels.colorMappings = o, n.debug("updatedChannels", this.channels), this._lastChannelConfig = {
480
+ zarrMappings: [...this.channels.zarrMappings],
481
+ colorMappings: [...this.channels.colorMappings],
482
+ downsampleMin: [...this.channels.downsampleMin],
483
+ downsampleMax: [...this.channels.downsampleMax]
484
+ };
485
+ }
486
+ /**
487
+ * Try to load a resolution level
488
+ * @param {number} resolutionIndex - The resolution level to load
489
+ * @param {Array} arrays - Array to store the loaded arrays
490
+ * @returns {Promise} Promise resolving when the resolution is loaded or rejected
491
+ */
492
+ /*
493
+ async tryLoadResolution(resolutionIndex, arrays) {
494
+ logWithColor('tryLoadResolution');
495
+ log.debug(resolutionIndex, arrays);
496
+ try {
497
+ const array = await zarrita.open(this.group.resolve(String(resolutionIndex)));
498
+ // Create new arrays to avoid modifying parameters directly
499
+ const newArrays = [...arrays];
500
+ newArrays[resolutionIndex] = array;
501
+ // Update the original arrays
502
+ Object.assign(arrays, newArrays);
503
+ logWithColor('tryLoadResolution() COMPLETE');
504
+ return { success: true, level: resolutionIndex };
505
+ } catch (err) {
506
+ log.error(`Failed to load resolution ${resolutionIndex}:`, err);
507
+ return { success: false, level: resolutionIndex, error: err.message };
508
+ }
509
+ }
510
+ */
511
+ /**
512
+ * Get physical dimensions
513
+ * @returns {Array} Physical dimensions [X, Y, Z]
514
+ */
515
+ getPhysicalDimensionsXYZ() {
516
+ n.debug("getPhysicalDimensionsXYZ"), n.debug("this.zarrStore.physicalSizeTotal", this.zarrStore.physicalSizeTotal);
517
+ const t = [
518
+ this.zarrStore.physicalSizeTotal[2],
519
+ this.zarrStore.physicalSizeTotal[1],
520
+ this.zarrStore.physicalSizeTotal[0]
521
+ ];
522
+ return n.debug("out", t), t;
523
+ }
524
+ /**
525
+ * Get the maximum resolution
526
+ * @returns {number} Maximum resolution
527
+ */
528
+ getMaxResolutionXYZ() {
529
+ n.debug("getMaxResolutionXYZ"), n.debug("this.zarrStore.shapes", this.zarrStore.shapes);
530
+ const t = [
531
+ this.zarrStore.shapes[0][4],
532
+ this.zarrStore.shapes[0][3],
533
+ this.zarrStore.shapes[0][2]
534
+ ];
535
+ return n.debug("out", t), t;
536
+ }
537
+ getOriginalScaleXYZ() {
538
+ z("getOriginalScaleXYZ"), n.debug("this.zarrStore.physicalSizeVoxel", this.zarrStore.physicalSizeVoxel);
539
+ const t = [
540
+ this.zarrStore.physicalSizeVoxel[2],
541
+ this.zarrStore.physicalSizeVoxel[1],
542
+ this.zarrStore.physicalSizeVoxel[0]
543
+ ];
544
+ return n.debug("out", t), t;
545
+ }
546
+ getNormalizedScaleXYZ() {
547
+ n.debug("getNormalizedScaleXYZ");
548
+ const t = [
549
+ 1,
550
+ this.zarrStore.physicalSizeVoxel[1] / this.zarrStore.physicalSizeVoxel[2],
551
+ this.zarrStore.physicalSizeVoxel[0] / this.zarrStore.physicalSizeVoxel[0]
552
+ ];
553
+ return n.debug("out", t), t;
554
+ }
555
+ getBoxDimensionsXYZ() {
556
+ n.debug("getBoxDimensionsXYZ"), n.debug("this.zarrStore.shapes", this.zarrStore.shapes);
557
+ const t = [
558
+ 1,
559
+ this.zarrStore.shapes[0][3] / this.zarrStore.shapes[0][4],
560
+ this.zarrStore.shapes[0][2] / this.zarrStore.shapes[0][4]
561
+ ];
562
+ return n.debug("out", t), t;
563
+ }
564
+ /**
565
+ * Load a specific Zarr chunk based on [t,c,z,y,x] coordinates
566
+ * @param {number} t - Time point (default 0)
567
+ * @param {number} c - Channel (default 0)
568
+ * @param {number} z - Z coordinate
569
+ * @param {number} y - Y coordinate
570
+ * @param {number} x - X coordinate
571
+ * @param {number} resolution - Resolution level
572
+ * @returns {Promise<Uint8Array>} 32x32x32 chunk data
573
+ */
574
+ async loadZarrChunk(t = 0, e = 0, i, a, r, o) {
575
+ if (!this.zarrStore || !this.zarrStore.arrays[o])
576
+ throw new Error("Zarr store or resolution not initialized");
577
+ n.debug("loadZarrChunk", { t, c: e, z: i, y: a, x: r, resolution: o });
578
+ const u = await this.zarrStore.arrays[o].getChunk([t, e, i, a, r]);
579
+ if (!u)
580
+ throw new Error(`No chunk found at coordinates [${t},${e},${i},${a},${r}]`);
581
+ if (u.data.length !== S * S * S)
582
+ throw new Error(`Unexpected chunk size: ${u.data.length}`);
583
+ return u.data;
584
+ }
585
+ /**
586
+ * Process the buffer of brick requests from the shader, turning them into
587
+ * actual Promises for Zarr chunks on the JS side.
588
+ * @param {Uint8Array} buffer The bufRequest (of length width*height*4)
589
+ * containing the brick requests from the shader.
590
+ * @param {object} optsForWeighting
591
+ * @param {number} optsForWeighting.width The width of the render target.
592
+ * @param {number} optsForWeighting.height The height of the render target.
593
+ * @param {number} optsForWeighting.sigmaNormalized The normalized sigma value
594
+ * to use for weighting the brick requests based on their distance from
595
+ * the center of the render target.
596
+ */
597
+ async processRequestData(t, e) {
598
+ if (this.isBusy) {
599
+ n.debug("processRequestData: already busy, skipping");
600
+ return;
601
+ }
602
+ if (this.noNewRequests) {
603
+ n.debug("processRequestData: loading stopped by user, skipping");
604
+ return;
605
+ }
606
+ if (this.isContextLost()) {
607
+ n.debug("processRequestData: WebGL context is lost, skipping");
608
+ return;
609
+ }
610
+ this.isBusy = !0, this.triggerRequest = !1;
611
+ const { requests: i, origRequestCount: a } = We(t, this.k, e);
612
+ i.length === 0 && (this.noNewRequests = !0), n.debug(`processRequestData: handling ${i.length} requests of ${a}`), await this.handleBrickRequests(i), this.triggerUsage = !0, this.isBusy = !1;
613
+ }
614
+ async processUsageData(t) {
615
+ if (this.isBusy) {
616
+ n.debug("processUsageData: already busy, skipping"), this.needsBailout = !0;
617
+ return;
618
+ }
619
+ if (this.isContextLost()) {
620
+ n.debug("processUsageData: WebGL context is lost, skipping");
621
+ return;
622
+ }
623
+ this.isBusy = !0, this.triggerUsage = !1;
624
+ const e = ++this.timeStamp, i = /* @__PURE__ */ new Set();
625
+ for (let a = 0; a < t.length; a += 4) {
626
+ const r = t[a], o = t[a + 1], l = t[a + 2];
627
+ if ((r | o | l) === 0)
628
+ continue;
629
+ const u = l * B * G + o * B + r;
630
+ u < this.BCTimeStamps.length && i.add(u);
631
+ }
632
+ Array.from(i).forEach((a) => {
633
+ this.BCTimeStamps[a] = e;
634
+ }), this.BCFull && this._buildLRU(), this.triggerRequest = !0, this.isBusy = !1;
635
+ }
636
+ // Helper method to update PT entries for evicted bricks
637
+ _evictBrick(t) {
638
+ const e = this.bc2pt[t];
639
+ if (!e)
640
+ return;
641
+ const [i, a] = this.BCMinMax[t] || [0, 0], r = (0 | 1 << 30 | Math.min(127, i >> 1) << 23 | Math.min(127, a >> 1) << 16) >>> 0;
642
+ this._updatePTEntry(e.x, e.y, e.z, r), this.bc2pt[t] = null;
643
+ }
644
+ _purgeChannel(t) {
645
+ if (n.debug("purging channel", t), n.debug("corresponding zarr channel", this.channels.zarrMappings[t]), !this.ptTHREE) {
646
+ n.error("pagetable texture not initialized");
647
+ return;
648
+ }
649
+ if (this.isContextLost()) {
650
+ n.warn("WebGL context is lost, skipping channel purge");
651
+ return;
652
+ }
653
+ this.channels.downsampleMin[t] = void 0, this.channels.downsampleMax[t] = void 0, this.channels.zarrMappings[t] = void 0;
654
+ const e = this.PT.channelOffsets[t];
655
+ n.debug("channelMask", e), n.error("TODO: not tested yet");
656
+ const { gl: i } = this, a = this.renderer.properties.get(this.ptTHREE).__webglTexture;
657
+ i.activeTexture(i.TEXTURE0), i.bindTexture(i.TEXTURE_3D, a);
658
+ for (let r = 0; r < this.zarrStore.resolutions; r++) {
659
+ const o = [
660
+ this.PT.anchors[r][2] * e[2],
661
+ this.PT.anchors[r][1] * e[1],
662
+ this.PT.anchors[r][0] * e[0]
663
+ ];
664
+ n.debug("anchor", o);
665
+ const l = this.zarrStore.brickLayout[r], u = l[0] * l[1] * l[2];
666
+ n.debug("extents", l), n.debug("size", u), i.texSubImage3D(i.TEXTURE_3D, 0, o[0], o[1], o[2], l[0], l[1], l[2], i.RED_INTEGER, i.UNSIGNED_INT, new Uint32Array(u));
667
+ }
668
+ i.bindTexture(i.TEXTURE_3D, null);
669
+ }
670
+ // Update a PT entry
671
+ _updatePTEntry(t, e, i, a) {
672
+ if (!this.ptTHREE)
673
+ return;
674
+ if (this.isContextLost()) {
675
+ n.warn("WebGL context is lost, skipping PT entry update");
676
+ return;
677
+ }
678
+ const { gl: r } = this, o = this.renderer.properties.get(this.ptTHREE).__webglTexture;
679
+ r.activeTexture(r.TEXTURE0), r.bindTexture(r.TEXTURE_3D, o), r.texSubImage3D(r.TEXTURE_3D, 0, t, e, i, 1, 1, 1, r.RED_INTEGER, r.UNSIGNED_INT, new Uint32Array([a])), r.bindTexture(r.TEXTURE_3D, null);
680
+ }
681
+ /* ------------------------------------------------------------- *
682
+ * 2. Allocate the next n free bricks in the brick cache *
683
+ * ------------------------------------------------------------- */
684
+ /**
685
+ *
686
+ * @param {number} n The number of slots to allocate
687
+ * @returns {{ bcIndex, x, y, z }[]} Array of brick cache coordinates for the allocated slots.
688
+ */
689
+ _allocateBCSlots(t) {
690
+ let e = [];
691
+ const i = B * G * ce;
692
+ if (!this.BCFull && this.BCUnusedIndex + t > i && (this.BCFull = !0, n.debug("BRICK CACHE FULL")), this.BCFull)
693
+ this.LRUStack.length < t && this._buildLRU(), e = this.LRUStack.splice(0, t).map((a) => {
694
+ this._evictBrick(a);
695
+ const r = Math.floor(a / (B * G)), o = a - r * B * G, l = Math.floor(o / B), u = o % B;
696
+ return { bcIndex: a, x: u, y: l, z: r };
697
+ });
698
+ else {
699
+ for (let a = 0; a < t; ++a) {
700
+ const r = (this.BCUnusedIndex + a) % i, o = Math.floor(r / (B * G)), l = r - o * B * G, u = Math.floor(l / B), s = l % B;
701
+ e.push({ bcIndex: r, x: s, y: u, z: o });
702
+ }
703
+ this.BCUnusedIndex += t;
704
+ }
705
+ return e;
706
+ }
707
+ /* ------------------------------------------------------------- *
708
+ * 4. Upload one brick + PT entry *
709
+ * ------------------------------------------------------------- */
710
+ async _uploadBrick(t, e) {
711
+ if (n.debug("uploading brick", t, e), this.isContextLost()) {
712
+ n.warn("WebGL context is lost, skipping brick upload");
713
+ return;
714
+ }
715
+ if (t.x >= this.PT.xExtent || t.y >= this.PT.yExtent || t.z >= this.PT.zTotal || t.x < 0 || t.y < 0 || t.z < 0) {
716
+ n.error("this.PT", this.PT), n.error("ptCoord out of bounds", t);
717
+ return;
718
+ }
719
+ const { channel: i, resolution: a, x: r, y: o, z: l } = He(t.x, t.y, t.z, { PT_zExtent: this.PT.zExtent, PT_z0Extent: this.PT.z0Extent, PT_anchors: this.PT.anchors });
720
+ if (!this.channels || !this.channels.zarrMappings || this.channels.zarrMappings.length === 0) {
721
+ n.error("Channel mappings not initialized, skipping brick upload");
722
+ return;
723
+ }
724
+ if (i < 0 || i >= this.channels.zarrMappings.length) {
725
+ n.error("Channel index out of bounds", { channel: i, mappingsLength: this.channels.zarrMappings.length });
726
+ return;
727
+ }
728
+ const u = this.channels.zarrMappings[i];
729
+ if (u === void 0 || u === -1)
730
+ if (n.warn("zarrChannel is undefined or -1", {
731
+ zarrChannel: u,
732
+ channel: i,
733
+ ptCoord: t,
734
+ channelMappings: this.channels.zarrMappings,
735
+ contextLost: this.isContextLost()
736
+ }), this._lastChannelConfig && this._lastChannelConfig.zarrMappings[i] !== void 0) {
737
+ n.warn("Attempting to use last known channel config"), this.channels.zarrMappings = [...this._lastChannelConfig.zarrMappings], this.channels.colorMappings = [...this._lastChannelConfig.colorMappings], this.channels.downsampleMin = [...this._lastChannelConfig.downsampleMin], this.channels.downsampleMax = [...this._lastChannelConfig.downsampleMax];
738
+ const R = this.channels.zarrMappings[i];
739
+ if (R !== void 0 && R !== -1)
740
+ n.debug("Successfully restored channel mapping, continuing with upload");
741
+ else {
742
+ n.error("Could not restore valid channel mapping, aborting brick upload");
743
+ return;
744
+ }
745
+ } else {
746
+ n.error("No fallback channel config available, aborting brick upload");
747
+ return;
748
+ }
749
+ n.debug("starting to load zarr chunk", { resolution: a, z: l, y: o, x: r, zarrChannel: u });
750
+ let s = await this.loadZarrChunk(0, u, l, o, r, a);
751
+ if (n.debug("chunk", s), s instanceof Uint16Array) {
752
+ if (n.debug("chunk is Uint16Array, converting to Uint8Array"), this.channels.downsampleMin[i] === void 0) {
753
+ const T = this.channels.zarrMappings[i];
754
+ n.debug("channelId was not found in this.channels.downsampleMin[channel]", T), this.channels.downsampleMin[i] = this.ngffMetadata?.omero?.channels?.[T]?.window?.min || 0, this.channels.downsampleMax[i] = this.ngffMetadata?.omero?.channels?.[T]?.window?.max || 65535, n.debug("this.channels.downsampleMin[channel]", this.channels.downsampleMin[i]), n.debug("this.channels.downsampleMax[channel]", this.channels.downsampleMax[i]);
755
+ }
756
+ const R = new Uint16Array(s.buffer), E = new Uint8Array(s.length), k = this.channels.downsampleMin[i], O = this.channels.downsampleMax[i], X = O - k;
757
+ for (let T = 0; T < R.length; T++) {
758
+ const L = R[T], U = Math.max(k, Math.min(O, L));
759
+ E[T] = (U - k) * 255 / X | 0;
760
+ }
761
+ s = E;
762
+ }
763
+ if (!(s instanceof Uint8Array))
764
+ throw new Error(`Unsupported chunk type: ${s.constructor.name}. Expected Uint8Array.`);
765
+ let v = 255, g = 0;
766
+ for (let R = 0; R < s.length; ++R) {
767
+ const E = s[R];
768
+ E < v && (v = E), E > g && (g = E);
769
+ }
770
+ const { gl: c } = this, d = this.renderer.properties.get(this.bcTHREE).__webglTexture;
771
+ c.activeTexture(c.TEXTURE2), c.bindTexture(c.TEXTURE_3D, d), c.pixelStorei(c.UNPACK_ALIGNMENT, 1), c.texSubImage3D(c.TEXTURE_3D, 0, e.x * S, e.y * S, e.z * S, S, S, S, c.RED, c.UNSIGNED_BYTE, s), c.pixelStorei(c.UNPACK_ALIGNMENT, 4), c.bindTexture(c.TEXTURE_3D, null);
772
+ const m = c.getError();
773
+ m !== c.NO_ERROR && n.error("WebGL error during brick upload:", m, s), i >= this.channels.zarrMappings.length && (n.debug("channel is out of bounds", i), v = 255, g = 255);
774
+ const h = Ye(v, g, e.x, e.y, e.z), x = this.renderer.properties.get(this.ptTHREE).__webglTexture;
775
+ c.activeTexture(c.TEXTURE0), c.bindTexture(c.TEXTURE_3D, x), c.texSubImage3D(c.TEXTURE_3D, 0, t.x, t.y, t.z, 1, 1, 1, c.RED_INTEGER, c.UNSIGNED_INT, new Uint32Array([h])), c.bindTexture(c.TEXTURE_3D, null);
776
+ const b = c.getError();
777
+ b !== c.NO_ERROR && n.error("WebGL error during pagetable upload:", b, s), this.BCTimeStamps[e.bcIndex] = this.timeStamp, this.BCMinMax[e.bcIndex] = [v, g], this.bc2pt[e.bcIndex] = t;
778
+ }
779
+ /* ------------------------------------------------------------- *
780
+ * 5. Public: handle a batch of PT requests (array of {x,y,z}) *
781
+ * ------------------------------------------------------------- */
782
+ async handleBrickRequests(t) {
783
+ if (t.length === 0)
784
+ return;
785
+ this.totalBricksRequested = t.length, this.currentRequestCount = t.length;
786
+ const e = this._allocateBCSlots(t.length);
787
+ n.debug("Handling brick requests:", { requestCount: t.length, slotCount: e.length }), n.debug("handleBrickRequests: starting for loop");
788
+ for (let i = 0; i < t.length; ++i) {
789
+ await this._uploadBrick(t[i], e[i]), this.currentRequestCount = t.length - i - 1;
790
+ const a = this.bricksEverLoaded.size;
791
+ if (this.bricksEverLoaded.add(`${t[i].x},${t[i].y},${t[i].z}`), a === this.bricksEverLoaded.size && n.debug("DUPLICATE BRICK LOADED", t[i]), this.needsBailout) {
792
+ n.debug("Bailing out of handleBrickRequests early due to needsBailout flag"), this.needsBailout = !1, this.currentRequestCount = 0;
793
+ break;
794
+ }
795
+ }
796
+ this.currentRequestCount = 0, n.debug("this.bricksEverLoaded", this.bricksEverLoaded);
797
+ }
798
+ /* --------------------------------------------------------- *
799
+ * Rebuild the LRUStack with the k least-recently-used bricks *
800
+ * --------------------------------------------------------- */
801
+ _buildLRU() {
802
+ const t = this.BCTimeStamps.map((e, i) => ({ index: i, time: e }));
803
+ this.LRUStack = t.sort((e, i) => e.time - i.time).slice(0, this.k).map((e) => e.index);
804
+ }
805
+ }
806
+ const Qe = `//
807
+ // Output: Unnormalized ray direction from camera to each vertex
808
+ // Used by fragment shader for ray marching through the volume
809
+ out vec3 rayDirUnnorm;
810
+
811
+ // Output: Camera position transformed into volume's local coordinate system
812
+ // Used to calculate ray origins in the fragment shader
813
+ out vec3 cameraCorrected;
814
+
815
+ // Volume scale uniform (likely for anisotropic voxels)
816
+ uniform vec3 u_vol_scale;
817
+
818
+ // Volume size uniform
819
+ uniform vec3 u_size;
820
+
821
+ // Output: Vertex positions normalized to [0,1] range within volume bounds
822
+ // Standard coordinate system for volume sampling
823
+ varying vec3 worldSpaceCoords;
824
+
825
+ // Output: Texture coordinates for sampling volume data
826
+ varying vec2 vUv;
827
+
828
+ // Output: Final clip-space position (stored for fragment shader access)
829
+ varying vec4 glPosition;
830
+
831
+ // Volume bounding box size uniform
832
+ uniform highp vec3 boxSize;
833
+
834
+ void main()
835
+ {
836
+ // Transform vertex positions from [-0.5, 0.5] range to [0, 1] range
837
+ // This is the standard coordinate system for volume sampling
838
+ //
839
+ // Mathematical transformation:
840
+ // worldSpaceCoords = (position / boxSize) + 0.5
841
+ //
842
+ // Example:
843
+ // position = (-0.5, -0.5, -0.5) → worldSpaceCoords = (0, 0, 0)
844
+ // position = ( 0.0, 0.0, 0.0) → worldSpaceCoords = (0.5, 0.5, 0.5)
845
+ // position = ( 0.5, 0.5, 0.5) → worldSpaceCoords = (1, 1, 1)
846
+ worldSpaceCoords = position / boxSize + vec3(0.5, 0.5, 0.5); //move it from [-0.5;0.5] to [0,1]
847
+
848
+ // Transform camera position into volume's local coordinate system
849
+ // This gives us the ray origin in volume space
850
+ cameraCorrected = (inverse(modelMatrix) * vec4(cameraPosition, 1.)).xyz;
851
+
852
+ // Calculate unnormalized ray direction from camera to each vertex
853
+ // Used by fragment shader for ray marching through the volume
854
+ rayDirUnnorm = position - cameraCorrected;
855
+
856
+ // Apply standard MVP transformation to get clip-space coordinates
857
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
858
+
859
+ // Store clip-space position for fragment shader access
860
+ glPosition = gl_Position;
861
+
862
+ // Pass through texture coordinates for volume sampling
863
+ vUv = uv;
864
+ }
865
+ `, Je = `//
866
+ // #include <packing>
867
+ precision highp float;
868
+ precision highp int;
869
+ precision highp sampler3D;
870
+ precision highp usampler3D;
871
+
872
+ // ========================================
873
+ // INPUT VARIABLES (from vertex shader)
874
+ // ========================================
875
+ // Unnormalized ray direction from camera
876
+ in vec3 rayDirUnnorm;
877
+ // Camera position in world space
878
+ in vec3 cameraCorrected;
879
+
880
+ // ========================================
881
+ // TEXTURE SAMPLERS
882
+ // ========================================
883
+ // 3D texture containing cached brick data (2048x2048x128)
884
+ // (2048*2048*128)/(32*32*32) = 16,384 bricks can be stored?
885
+ uniform sampler3D brickCacheTex;
886
+ // 3D texture containing page table entries (brick metadata)
887
+ uniform usampler3D pageTableTex;
888
+
889
+ // ========================================
890
+ // RENDERING PARAMETERS/CONSTANTS
891
+ // ========================================
892
+ // Rendering style: 0=MIP, 1=MinIP, 2=standard volume rendering, 3=DEBUG
893
+ uniform int u_renderstyle;
894
+ // Global opacity multiplier for volume rendering
895
+ uniform float opacity;
896
+
897
+ // ========================================
898
+ // CONTRAST LIMITS (per channel)
899
+ // per channel min/max values for value normalization
900
+ // ========================================
901
+ uniform vec2 clim0;
902
+ uniform vec2 clim1;
903
+ uniform vec2 clim2;
904
+ uniform vec2 clim3;
905
+ uniform vec2 clim4;
906
+ uniform vec2 clim5;
907
+ uniform vec2 clim6;
908
+
909
+ // ========================================
910
+ // CLIPPING PLANES
911
+ // e.g., for X-axis clipping: (min_x, max_x) or (-1, -1) if disabled
912
+ // ========================================
913
+ uniform vec2 xClip;
914
+ uniform vec2 yClip;
915
+ uniform vec2 zClip;
916
+
917
+ // ========================================
918
+ // CHANNEL COLORS AND OPACITIES
919
+ // rgb -- color values, a -- visibility (boolean)
920
+ // ========================================
921
+ uniform vec4 color0;
922
+ uniform vec4 color1;
923
+ uniform vec4 color2;
924
+ uniform vec4 color3;
925
+ uniform vec4 color4;
926
+ uniform vec4 color5;
927
+ uniform vec4 color6;
928
+
929
+ // maps colors to physical spaces
930
+ uniform int channelMapping[7];
931
+
932
+ // ========================================
933
+ // VOLUME AND RESOLUTION PARAMETERS
934
+ // ========================================
935
+ // Volume bounding box size in world space
936
+ uniform highp vec3 boxSize;
937
+ // Rendering resolution level (affects step size)
938
+ // stepsize, correlates with resolution
939
+ uniform int renderRes;
940
+ // Volume dimensions in voxels (x, y, z)
941
+ // resolution 0 voxel extents
942
+ uniform uvec3 voxelExtents;
943
+ // Global resolution range: (min_res, max_res)
944
+ // global range of requested resolutions
945
+ uniform ivec2 resGlobal;
946
+ // Maximum number of active channels
947
+ // max number of channels (relevant for the cache statistics)
948
+ // between 1 and 7
949
+ uniform int maxChannels;
950
+
951
+ // ========================================
952
+ // PER-CHANNEL RESOLUTION RANGES
953
+ // per color channel resolution range
954
+ // Each channel can have different available resolution levels
955
+ // e.g., for Channel 0: (min_res, max_res)
956
+ // ========================================
957
+ uniform ivec2 res0;
958
+ uniform ivec2 res1;
959
+ uniform ivec2 res2;
960
+ uniform ivec2 res3;
961
+ uniform ivec2 res4;
962
+ uniform ivec2 res5;
963
+ uniform ivec2 res6;
964
+ // Channel 7: unused
965
+ uniform ivec2 res7;
966
+
967
+ // ========================================
968
+ // LEVEL-OF-DETAIL PARAMETERS
969
+ // controls how fast we decrease the resolution
970
+ // ========================================
971
+ // LOD factor for distance-based resolution selection
972
+ uniform float lodFactor;
973
+
974
+ // ========================================
975
+ // ANCHOR POINTS (per resolution level)
976
+ // per resolution anchor point for pagetable
977
+ // ========================================
978
+ // Anchor points define the origin of page table for each resolution level
979
+ // Resolution 0 anchor point (highest detail)
980
+ uniform uvec3 anchor0;
981
+ uniform uvec3 anchor1;
982
+ uniform uvec3 anchor2;
983
+ uniform uvec3 anchor3;
984
+ uniform uvec3 anchor4;
985
+ uniform uvec3 anchor5;
986
+ uniform uvec3 anchor6;
987
+ uniform uvec3 anchor7;
988
+ uniform uvec3 anchor8;
989
+ uniform uvec3 anchor9;
990
+ // Resolution 9 anchor point (lowest detail)
991
+
992
+ // ========================================
993
+ // SCALE FACTORS (per resolution level)
994
+ // per resolution downsample factor
995
+ // ========================================
996
+ // Scale factors determine voxel size at each resolution level
997
+ // Resolution 0 scale factors (should be 1,1,1)
998
+ uniform vec3 scale0;
999
+ uniform vec3 scale1;
1000
+ uniform vec3 scale2;
1001
+ uniform vec3 scale3;
1002
+ uniform vec3 scale4;
1003
+ uniform vec3 scale5;
1004
+ uniform vec3 scale6;
1005
+ uniform vec3 scale7;
1006
+ uniform vec3 scale8;
1007
+ uniform vec3 scale9;
1008
+ // Resolution 9 scale factors
1009
+
1010
+ // ========================================
1011
+ // VARYING VARIABLES (unused but required)
1012
+ // ========================================
1013
+ // Fragment position (unused)
1014
+ varying vec4 glPosition;
1015
+ // World space coordinates (used for depth only)
1016
+ varying vec3 worldSpaceCoords;
1017
+
1018
+ // ========================================
1019
+ // OUTPUT VARIABLES (multiple render targets)
1020
+ // output buffers
1021
+ // ========================================
1022
+ // Final rendered color (sRGB)
1023
+ layout(location = 0) out vec4 gColor;
1024
+ // Brick loading requests (packed coordinates)
1025
+ layout(location = 1) out vec4 gRequest;
1026
+ // Brick usage tracking (for cache management)
1027
+ layout(location = 2) out vec4 gUsage;
1028
+
1029
+ // ========================================
1030
+ // CONSTANTS
1031
+ // ========================================
1032
+ // Size of each brick in voxels (32x32x32)
1033
+ const float BRICK_SIZE = 32.0;
1034
+ // Brick cache texture width
1035
+ const float BRICK_CACHE_SIZE_X = 2048.0;
1036
+ // Brick cache texture height
1037
+ const float BRICK_CACHE_SIZE_Y = 2048.0;
1038
+ // Brick cache texture depth
1039
+ const float BRICK_CACHE_SIZE_Z = 128.0;
1040
+ // Number of bricks in X (64)
1041
+ const float BRICK_CACHE_BRICKS_X = BRICK_CACHE_SIZE_X / BRICK_SIZE;
1042
+ // Number of bricks in Y (64)
1043
+ const float BRICK_CACHE_BRICKS_Y = BRICK_CACHE_SIZE_Y / BRICK_SIZE;
1044
+ // Number of bricks in Z (4)
1045
+ const float BRICK_CACHE_BRICKS_Z = BRICK_CACHE_SIZE_Z / BRICK_SIZE;
1046
+
1047
+ // ========================================
1048
+ // RAY-VOLUME INTERSECTION
1049
+ // calculating the intersection of the ray with the bounding box
1050
+ // ========================================
1051
+ // Calculates the intersection of a ray with the volume's bounding box
1052
+ // Returns (entry_time, exit_time) for the ray-box intersection
1053
+ // Handles clipping planes by adjusting the bounding box
1054
+ //
1055
+ // Parameters:
1056
+ // orig - vec3: Ray origin point in world space
1057
+ // dir - vec3: Ray direction vector (should be normalized)
1058
+ //
1059
+ // Returns:
1060
+ // vec2: (entry_time, exit_time) where:
1061
+ // - entry_time: Distance along ray to enter the volume
1062
+ // - exit_time: Distance along ray to exit the volume
1063
+ // - If no intersection: entry_time > exit_time
1064
+ vec2 intersect_hit(vec3 orig, vec3 dir) {
1065
+ // Start with full volume bounds
1066
+ vec3 boxMin = vec3(-0.5) * boxSize;
1067
+ vec3 boxMax = vec3(0.5) * boxSize;
1068
+
1069
+ // Apply clipping planes if they're active (xClip.x > -1.0 means active)
1070
+ if (xClip.x > -1.0) {
1071
+ boxMin.x = xClip.x - (boxSize.x / 2.0);
1072
+ if (xClip.y < boxSize.x)
1073
+ boxMax.x = xClip.y - (boxSize.x / 2.0);
1074
+ }
1075
+ if (yClip.x > -1.0) {
1076
+ boxMin.y = yClip.x - (boxSize.y / 2.0);
1077
+ if (yClip.y < boxSize.y)
1078
+ boxMax.y = yClip.y - (boxSize.y / 2.0);
1079
+ }
1080
+ if (zClip.x > -1.0) {
1081
+ boxMin.z = zClip.x - (boxSize.z / 2.0);
1082
+ if (zClip.y < boxSize.z)
1083
+ boxMax.z = zClip.y - (boxSize.z / 2.0);
1084
+ }
1085
+
1086
+ // Standard ray-box intersection algorithm
1087
+ vec3 invDir = 1.0 / dir;
1088
+ vec3 tmin0 = (boxMin - orig) * invDir;
1089
+ vec3 tmax0 = (boxMax - orig) * invDir;
1090
+ vec3 tmin = min(tmin0, tmax0);
1091
+ vec3 tmax = max(tmin0, tmax0);
1092
+ float t0 = max(tmin.x, max(tmin.y, tmin.z)); // Entry time
1093
+ float t1 = min(tmax.x, min(tmax.y, tmax.z)); // Exit time
1094
+ return vec2(t0, t1);
1095
+ }
1096
+
1097
+ // ========================================
1098
+ // UTILITY FUNCTIONS
1099
+ // ========================================
1100
+
1101
+ // Pseudo-random number generator for jittered sampling
1102
+ // random number generator based on the uv coordinate
1103
+ // Author @patriciogv - 2015
1104
+ // http://patriciogonzalezvivo.com
1105
+ //
1106
+ // Parameters:
1107
+ // None (uses gl_FragCoord.xy as input)
1108
+ //
1109
+ // Returns:
1110
+ // float: Random value between 0.0 and 1.0 based on fragment coordinates
1111
+ float random() {
1112
+ return fract(sin(dot(gl_FragCoord.xy, vec2(12.9898,78.233)))* 43758.5453123);
1113
+ }
1114
+
1115
+ // Convert from linear RGB to sRGB color space
1116
+ // Implements the standard sRGB transfer function for gamma correction
1117
+ //
1118
+ // Parameters:
1119
+ // x - float: Linear RGB value between 0.0 and 1.0
1120
+ //
1121
+ // Returns:
1122
+ // float: sRGB value between 0.0 and 1.0
1123
+ float linear_to_srgb(float x) {
1124
+ if (x <= 0.0031308f) {
1125
+ return 12.92f * x;
1126
+ }
1127
+ return 1.055f * pow(x, 1.f / 2.4f) - 0.055f;
1128
+ }
1129
+
1130
+ // Convert from linear RGB to sRGB color space (vector version)
1131
+ // Applies sRGB conversion to each RGB component while preserving alpha
1132
+ //
1133
+ // Parameters:
1134
+ // x - vec4: Linear RGBA color with components between 0.0 and 1.0
1135
+ //
1136
+ // Returns:
1137
+ // vec4: sRGB RGBA color with components between 0.0 and 1.0
1138
+ vec4 linear_to_srgb(vec4 x) {
1139
+ return vec4(linear_to_srgb(x.r), linear_to_srgb(x.g), linear_to_srgb(x.b), x.a);
1140
+ }
1141
+
1142
+ // ========================================
1143
+ // PAGE TABLE COORDINATE PACKING
1144
+ // transform the pagetable coordinate into a RGBA8 value
1145
+ // ========================================
1146
+ // Packs 3D page table coordinates into RGBA8 texture format
1147
+ // Uses 10 bits for X, 10 bits for Y, 12 bits for Z
1148
+ //
1149
+ // Parameters:
1150
+ // coord - uvec3: 3D coordinates to pack (X, Y, Z components)
1151
+ // - X coordinate: 10-bit unsigned integer (0-1023)
1152
+ // - Y coordinate: 10-bit unsigned integer (0-1023)
1153
+ // - Z coordinate: 12-bit unsigned integer (0-4095)
1154
+ //
1155
+ // Returns:
1156
+ // vec4: RGBA8 encoded coordinates with components between 0.0 and 1.0
1157
+ // - R: Upper 8 bits of packed 32-bit value
1158
+ // - G: Middle-upper 8 bits of packed 32-bit value
1159
+ // - B: Middle-lower 8 bits of packed 32-bit value
1160
+ // - A: Lower 8 bits of packed 32-bit value
1161
+ vec4 packPTCoordToRGBA8(uvec3 coord) {
1162
+
1163
+ uint x = coord.x & 0x3FFu; // 10 bits for X coordinate
1164
+ uint y = coord.y & 0x3FFu; // 10 bits for Y coordinate
1165
+ uint z = coord.z & 0xFFFu; // 12 bits for Z coordinate
1166
+
1167
+ // Pack into 32-bit integer
1168
+ uint packed =
1169
+ (x << 22u) |
1170
+ (y << 12u) |
1171
+ (z);
1172
+
1173
+ // Decompose into RGBA8 format
1174
+ return vec4(
1175
+ float((packed >> 24u) & 0xFFu) / 255.0,
1176
+ float((packed >> 16u) & 0xFFu) / 255.0,
1177
+ float((packed >> 8u) & 0xFFu) / 255.0,
1178
+ float(packed & 0xFFu) / 255.0
1179
+ );
1180
+ }
1181
+
1182
+ // ========================================
1183
+ // RESOLUTION AND ANCHOR POINT ACCESSORS
1184
+ // ========================================
1185
+
1186
+ // Get anchor point for a specific resolution level
1187
+ // Anchor points define the origin of the page table for each resolution
1188
+ //
1189
+ // Parameters:
1190
+ // index - int: Resolution level index (0-9, where 0 is highest resolution)
1191
+ //
1192
+ // Returns:
1193
+ // uvec3: 3D anchor point coordinates in the page table, or (-1, -1, -1) if invalid
1194
+ uvec3 getAnchorPoint(int index) {
1195
+ if (index == 0) return anchor0;
1196
+ if (index == 1) return anchor1;
1197
+ if (index == 2) return anchor2;
1198
+ if (index == 3) return anchor3;
1199
+ if (index == 4) return anchor4;
1200
+ if (index == 5) return anchor5;
1201
+ if (index == 6) return anchor6;
1202
+ if (index == 7) return anchor7;
1203
+ if (index == 8) return anchor8;
1204
+ if (index == 9) return anchor9;
1205
+ return uvec3(-1, -1, -1);
1206
+ }
1207
+
1208
+ // Find the lowest available resolution level
1209
+ // Returns the highest resolution index that has valid data
1210
+ //
1211
+ // Parameters:
1212
+ // None
1213
+ //
1214
+ // Returns:
1215
+ // int: Highest resolution level index (0-9) that has valid anchor point data
1216
+ // Returns 9 if no valid resolution levels are found
1217
+ int getLowestRes() {
1218
+ for (int i = 0; i < 10; i++) {
1219
+ if (getAnchorPoint(i) == uvec3(0,0,0)) {
1220
+ return i - 1;
1221
+ }
1222
+ }
1223
+ return 9;
1224
+ }
1225
+
1226
+ // Get the downsample factor for a resolution level
1227
+ // Scale factors determine the voxel size at each resolution
1228
+ //
1229
+ // Parameters:
1230
+ // index - int: Resolution level index (0-9, where 0 is highest resolution)
1231
+ //
1232
+ // Returns:
1233
+ // vec3: Scale factors (x, y, z) for the resolution level, or (-1, -1, -1) if invalid
1234
+ // Higher scale factors indicate larger voxels (lower resolution)
1235
+ vec3 getScale(int index) {
1236
+ if (index == 0) return scale0;
1237
+ if (index == 1) return scale1;
1238
+ if (index == 2) return scale2;
1239
+ if (index == 3) return scale3;
1240
+ if (index == 4) return scale4;
1241
+ if (index == 5) return scale5;
1242
+ if (index == 6) return scale6;
1243
+ if (index == 7) return scale7;
1244
+ if (index == 8) return scale8;
1245
+ if (index == 9) return scale9;
1246
+ return vec3(-1.0, -1.0, -1.0);
1247
+ }
1248
+
1249
+ // Get the resolution range for a color channel
1250
+ // Returns (min_res, max_res) for the channel
1251
+ //
1252
+ // Parameters:
1253
+ // index - int: Channel index (0-6)
1254
+ //
1255
+ // Returns:
1256
+ // ivec2: Resolution range as (min_resolution_level, max_resolution_level)
1257
+ // Returns (-1, -1) if channel index is invalid
1258
+ ivec2 getRes(int index) {
1259
+ if (index == 0) return res0;
1260
+ if (index == 1) return res1;
1261
+ if (index == 2) return res2;
1262
+ if (index == 3) return res3;
1263
+ if (index == 4) return res4;
1264
+ if (index == 5) return res5;
1265
+ if (index == 6) return res6;
1266
+ return ivec2(-1, -1);
1267
+ }
1268
+
1269
+ // Get the min/max values (contrast limits) for a color channel
1270
+ // Returns (min_value, max_value) for normalization
1271
+ //
1272
+ // Parameters:
1273
+ // index - int: Channel index (0-6)
1274
+ //
1275
+ // Returns:
1276
+ // vec2: Contrast limits as (min_value, max_value) for data normalization
1277
+ // Returns (-1.0, -1.0) if channel index is invalid
1278
+ vec2 getClim(int index) {
1279
+ if (index == 0) return clim0;
1280
+ if (index == 1) return clim1;
1281
+ if (index == 2) return clim2;
1282
+ if (index == 3) return clim3;
1283
+ if (index == 4) return clim4;
1284
+ if (index == 5) return clim5;
1285
+ if (index == 6) return clim6;
1286
+ return vec2(-1.0, -1.0);
1287
+ }
1288
+
1289
+ // ========================================
1290
+ // COORDINATE TRANSFORMATIONS
1291
+ // ========================================
1292
+
1293
+ // Convert normalized coordinates (0-1) to voxel coordinates.
1294
+ // get the voxel coordinate in the specified resolution from the normalized coordinate
1295
+ //
1296
+ // Parameters:
1297
+ // normalized - vec3: Normalized coordinates in range [0,1] for each axis
1298
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1299
+ //
1300
+ // Returns:
1301
+ // vec3: Voxel coordinates in the volume space at the specified resolution
1302
+ vec3 getVoxelFromNormalized(vec3 normalized, int res) {
1303
+ vec3 extents = (vec3(voxelExtents) / getScale(res)); // Voxel extents at this resolution
1304
+ vec3 voxel = normalized * extents;
1305
+ return voxel;
1306
+ }
1307
+
1308
+ // Convert voxel coordinates to normalized coordinates (0-1)
1309
+ // get the normalized coordinate based on the voxel coordinate in the specified resolution
1310
+ //
1311
+ // Parameters:
1312
+ // voxel - vec3: Voxel coordinates in the volume space
1313
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1314
+ //
1315
+ // Returns:
1316
+ // vec3: Normalized coordinates in range [0,1] for each axis
1317
+ vec3 getNormalizedFromVoxel(vec3 voxel, int res) {
1318
+ vec3 extents = (vec3(voxelExtents) / getScale(res)); // Voxel extents at this resolution
1319
+ vec3 normalized = voxel / extents;
1320
+ return normalized;
1321
+ }
1322
+
1323
+ // Convert normalized coordinates to brick coordinates.
1324
+ // get the brick coordinate in the specified resolution based on the normalized coordinate
1325
+ // needed for pagetable calculations
1326
+ //
1327
+ // Parameters:
1328
+ // normalized - vec3: Normalized coordinates in range [0,1] for each axis
1329
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1330
+ //
1331
+ // Returns:
1332
+ // vec3: Brick coordinates (each brick is 32x32x32 voxels)
1333
+ vec3 getBrickFromNormalized(vec3 normalized, int res) {
1334
+ vec3 voxel = getVoxelFromNormalized(normalized, res);
1335
+ vec3 brick = floor(voxel / 32.0); // Each brick is 32x32x32 voxels
1336
+ return brick;
1337
+ }
1338
+
1339
+ // Convert voxel coordinates to brick coordinates.
1340
+ // get the brick coordinate in the specified resolution based on the voxel coordinate
1341
+ //
1342
+ // Parameters:
1343
+ // voxel - vec3: Voxel coordinates in the volume space
1344
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1345
+ //
1346
+ // Returns:
1347
+ // vec3: Brick coordinates (each brick is 32x32x32 voxels)
1348
+ vec3 getBrickFromVoxel(vec3 voxel, int res) {
1349
+ vec3 brick = floor(voxel / 32.0); // Each brick is 32x32x32 voxels
1350
+ return brick;
1351
+ }
1352
+
1353
+ // ========================================
1354
+ // CHANNEL-SPECIFIC ACCESSORS
1355
+ // ========================================
1356
+
1357
+ // Get channel offset in page table.
1358
+ // get the vector for the specified channel slot in the pagetable
1359
+ // Different channels are stored at different Z-offsets in the page table
1360
+ //
1361
+ // Parameters:
1362
+ // index - int: Channel index (0-6)
1363
+ //
1364
+ // Returns:
1365
+ // uvec3: 3D offset coordinates for the channel in the page table
1366
+ uvec3 getChannelOffset(int index) {
1367
+ if (index == 0) return uvec3(0, 0, 1);
1368
+ if (index == 1) return uvec3(0, 1, 0);
1369
+ if (index == 2) return uvec3(0, 1, 1);
1370
+ if (index == 3) return uvec3(1, 0, 0);
1371
+ if (index == 4) return uvec3(1, 0, 1);
1372
+ if (index == 5) return uvec3(1, 1, 0);
1373
+ if (index == 6) return uvec3(1, 1, 1);
1374
+ return uvec3(0, 0, 0);
1375
+ }
1376
+
1377
+ // Get color for a channel.
1378
+ // get the color per color channel
1379
+ //
1380
+ // Parameters:
1381
+ // index - int: Channel index (0-6)
1382
+ //
1383
+ // Returns:
1384
+ // vec3: RGB color values for the specified channel
1385
+ vec3 getChannelColor(int index) {
1386
+ if (index == 0) return color0.xyz;
1387
+ if (index == 1) return color1.xyz;
1388
+ if (index == 2) return color2.xyz;
1389
+ if (index == 3) return color3.xyz;
1390
+ if (index == 4) return color4.xyz;
1391
+ if (index == 5) return color5.xyz;
1392
+ if (index == 6) return color6.xyz;
1393
+ return vec3(0.0, 0.0, 0.0);
1394
+ }
1395
+
1396
+ // Get opacity for a channel
1397
+ // get the opacity (used as visibility) per color channel
1398
+ //
1399
+ // Parameters:
1400
+ // index - int: Channel index (0-6)
1401
+ //
1402
+ // Returns:
1403
+ // float: Opacity value (0.0-1.0) for the specified channel
1404
+ float getChannelOpacity(int index) {
1405
+ if (index == 0) return color0.w;
1406
+ if (index == 1) return color1.w;
1407
+ if (index == 2) return color2.w;
1408
+ if (index == 3) return color3.w;
1409
+ if (index == 4) return color4.w;
1410
+ if (index == 5) return color5.w;
1411
+ if (index == 6) return color6.w;
1412
+ return 0.0;
1413
+ }
1414
+
1415
+ // ========================================
1416
+ // PAGE TABLE DECODING
1417
+ // ========================================
1418
+
1419
+ /**
1420
+ * retrieving the brick based on:
1421
+ * location -- normalized coordinate
1422
+ * targetRes -- target resolution
1423
+ * channel -- physical channel slot
1424
+ * rnd -- random number for jittering requests
1425
+ * query -- whether to query the brick (we dont query for interblock interpolation)
1426
+ * colorIndex -- color index for querying the min max values
1427
+ *
1428
+ * returns:
1429
+ * w >= 0 -- xyz contains brick cache coordinate, w stores resolution
1430
+ * w == -1 -- not resident in any resolution, should be treated as empty
1431
+ * w == -2 -- empty (with respect to current transfer function)
1432
+ * w == -3 -- constant full (with respect to current transfer function)
1433
+ * w == -4 -- constant value within range, x stores that value
1434
+ *
1435
+ * bit layout:
1436
+ * [1] 31 | 0 — flag resident
1437
+ * [1] 30 | 1 — flag init
1438
+ * [7] 23…29 | 2…8 — min → 128
1439
+ * [7] 16…22 | 9…15 — max → 128
1440
+ * [6] 10…15 | 16…21 — x offset in brick cache → max 64
1441
+ * [6] 4…9 | 22…27 — y offset in brick cache → max 64
1442
+ * [4] 0…3 | 28…31 — z offset in brick cache → max 16, effectively 4
1443
+ */
1444
+
1445
+ /*
1446
+ Page table entry format (32 bits):
1447
+ [31] | 0 — flag resident (1=loaded in cache)
1448
+ [30] | 1 — flag init (1=initialized)
1449
+ [29:23] | 2…8 — min value (7 bits) → 128 levels
1450
+ [22:16] | 9…15 — max value (7 bits) → 128 levels
1451
+ [15:10] | 16…21 — x offset in brick cache (6 bits) → 64 bricks
1452
+ [9:4] | 22…27 — y offset in brick cache (6 bits) → 64 bricks
1453
+ [3:0] | 28…31 — z offset in brick cache (4 bits) → 16 bricks
1454
+ */
1455
+
1456
+ // Query page table to find brick location and status
1457
+ // Searches for a brick at the specified location across multiple resolution levels
1458
+ // and returns its cache coordinates and status information
1459
+ //
1460
+ // Parameters:
1461
+ // location - vec3: Normalized coordinates (0-1) within the volume
1462
+ // targetRes - int: Target resolution level to start searching from
1463
+ // channel - int: Channel index (0-6) to query
1464
+ // rnd - float: Random value (0-1) used for brick loading request selection
1465
+ // query - bool: Whether to allow brick loading requests (true) or just query (false)
1466
+ // colorIndex - int
1467
+ //
1468
+ // Returns:
1469
+ // ivec4: (x_offset, y_offset, z_offset, status) where:
1470
+ // - x_offset, y_offset, z_offset: Brick cache coordinates if found
1471
+ // - status: Resolution level (>=0) if found, or status code:
1472
+ // * -1: Not found at any resolution level
1473
+ // * -2: Empty brick (all values below threshold)
1474
+ // * -3: Constant full brick (all values above threshold)
1475
+ // * -4: Constant value brick (uniform value)
1476
+ // add maxres here
1477
+ ivec4 getBrickLocation(vec3 location, int targetRes, int channel, float rnd, bool query, int colorIndex) {
1478
+
1479
+ // min max for current color
1480
+ vec2 clim = getClim(colorIndex);
1481
+
1482
+ // resolution ranges, TODO: connect this back to color
1483
+ int channelMin = getRes(channel).x;
1484
+ int channelMax = getRes(channel).y;
1485
+
1486
+ // Clamp resolution to channel's available range
1487
+ int currentRes = clamp(targetRes, channelMin, channelMax);
1488
+ currentRes = clamp(currentRes, resGlobal.x, resGlobal.y);
1489
+ int lowestRes = clamp(resGlobal.y, channelMin, channelMax);
1490
+
1491
+ // Determine if this channel should request brick loading.
1492
+ // request the current channel based on probability
1493
+ bool requestChannel = false;
1494
+ if (int(floor(rnd * float(maxChannels))) == colorIndex) {
1495
+ requestChannel = true;
1496
+ }
1497
+
1498
+ // Try progressively lower resolutions until we find data.
1499
+ // loop through resolutions
1500
+ while (currentRes <= lowestRes) {
1501
+
1502
+ // Calculate page table coordinates for this brick
1503
+ uvec3 anchorPoint = getAnchorPoint(currentRes);
1504
+ vec3 brickLocation = getBrickFromNormalized(location, currentRes);
1505
+ uvec3 channelOffset = getChannelOffset(channel);
1506
+ vec3 coordinate = floor(vec3(anchorPoint * channelOffset)) + brickLocation;
1507
+
1508
+ // Special handling for resolution 0 (highest detail)
1509
+ if (currentRes == 0) {
1510
+ int zExtent = int(ceil(float(voxelExtents.z) / 32.0));
1511
+ coordinate = vec3(anchorPoint) + vec3(0.0, 0.0, zExtent * channel) + brickLocation;
1512
+ }
1513
+
1514
+ // Query the page table.
1515
+ // get PT entry
1516
+ uint ptEntry = texelFetch(pageTableTex, ivec3(coordinate), 0).r;
1517
+
1518
+ // Check if brick is initialized.
1519
+ // check if the PT entry is initialized
1520
+ uint isInit = (ptEntry >> 30u) & 1u;
1521
+ if (isInit == 0u) {
1522
+ currentRes++;
1523
+ // Request brick loading if needed
1524
+ if (requestChannel == true && (gRequest.a + gRequest.b + gRequest.g + gRequest.r == 0.0) && query == true) {
1525
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1526
+ }
1527
+ continue;
1528
+ }
1529
+
1530
+ // Extract min/max values from page table entry.
1531
+ // get the min max values of the brick
1532
+ uint umin = ((ptEntry >> 23u) & 0x7Fu);
1533
+ uint umax = ((ptEntry >> 16u) & 0x7Fu);
1534
+ float min = float(int(umin)) / 127.0;
1535
+ float max = float(int(umax)) / 127.0;
1536
+
1537
+ // Check if brick is empty (all values below threshold).
1538
+ // exit early if brick is constant
1539
+ if (float(max) <= clim.x) {
1540
+ return ivec4(0,0,0,-2);
1541
+ // EMPTY
1542
+ } else if (float(min) >= clim.y) {
1543
+ return ivec4(0,0,0,-3); // CONSTANT FULL
1544
+ } else if ((umax - umin) < 2u) {
1545
+ return ivec4(min,0,0,-4); // CONSTANT OTHER VALUE
1546
+ }
1547
+
1548
+ // Check if brick is resident in cache.
1549
+ // return brick cache location if resident
1550
+ // continue to next resolution if not resident
1551
+ uint isResident = (ptEntry >> 31u) & 1u;
1552
+ if (isResident == 0u) {
1553
+ currentRes++;
1554
+ // Request brick loading if needed
1555
+ if (requestChannel == true && (gRequest.a + gRequest.b + gRequest.g + gRequest.r == 0.0) && query == true) {
1556
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1557
+ }
1558
+ continue;
1559
+ } else {
1560
+ // Extract brick cache coordinates
1561
+ uint xBrickCache = (ptEntry >> 10u) & 0x3Fu;
1562
+ uint yBrickCache = (ptEntry >> 4u) & 0x3Fu;
1563
+ uint zBrickCache = ptEntry & 0xFu;
1564
+ uvec3 brickCacheCoord = uvec3(xBrickCache, yBrickCache, zBrickCache);
1565
+
1566
+ return ivec4(brickCacheCoord, currentRes);
1567
+ }
1568
+ }
1569
+
1570
+ // not resident in any resolution, should be treated as empty
1571
+ return ivec4(0,0,0,-1); // Not found
1572
+ }
1573
+
1574
+ // Request brick loading for a specific location and resolution.
1575
+ // Initiates a request to load a brick from disk into the brick cache.
1576
+ // set the brick request for the specified slot channel
1577
+ //
1578
+ // Parameters:
1579
+ // location - vec3: Normalized world space coordinates (0.0 to 1.0) where the brick is needed
1580
+ // targetRes - int: Target resolution level (0-9, where 0 is highest resolution)
1581
+ // channel - int: Channel index (0-6) for multi-channel datasets
1582
+ // rnd - float: Random value between 0.0 and 1.0 used for load balancing across channels
1583
+ //
1584
+ // Returns:
1585
+ // void: No return value, but sets gRequest output variable if conditions are met
1586
+ void setBrickRequest(vec3 location, int targetRes, int channel, float rnd) {
1587
+ uvec3 anchorPoint = getAnchorPoint(targetRes);
1588
+ vec3 brickLocation = getBrickFromNormalized(location, targetRes);
1589
+ uvec3 channelOffset = getChannelOffset(channel);
1590
+ vec3 coordinate = floor(vec3(anchorPoint * channelOffset)) + brickLocation;
1591
+
1592
+ // Special handling for resolution 0
1593
+ if (targetRes == 0) {
1594
+ int zExtent = int(ceil(float(voxelExtents.z) / 32.0));
1595
+ coordinate = vec3(anchorPoint) + vec3(0.0, 0.0, zExtent * channel) + brickLocation;
1596
+ }
1597
+
1598
+ // Pack coordinates and set request
1599
+ if (int(floor(rnd * float(maxChannels))) == channel) {
1600
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1601
+ }
1602
+ }
1603
+
1604
+ // Track brick usage for cache management.
1605
+ // Records which brick in the cache is being accessed for LRU (Least Recently Used) eviction.
1606
+ // set the usage for the specified brick
1607
+ //
1608
+ // Parameters:
1609
+ // brickCacheOffset - ivec3: 3D coordinates of the brick within the brick cache texture
1610
+ // t_hit_min_os - float: Ray entry time in object space (start of ray-volume intersection)
1611
+ // t_hit_max_os - float: Ray exit time in object space (end of ray-volume intersection)
1612
+ // t_os - float: Current sampling position along the ray in object space
1613
+ // rnd - float: Random value between 0.0 and 1.0 used for probabilistic usage tracking
1614
+ //
1615
+ // Returns:
1616
+ // void: No return value, but sets gUsage output variable to track cache access patterns
1617
+ void setUsage(ivec3 brickCacheOffset, float t_hit_min_os, float t_hit_max_os, float t_os, float rnd) {
1618
+ float normalized_t_os = (t_os - t_hit_min_os) / (t_hit_max_os - t_hit_min_os); // Normalize to 0-1
1619
+ if (normalized_t_os <= rnd || gUsage == vec4(0.0, 0.0, 0.0, 0.0)) {
1620
+ gUsage = vec4(vec3(brickCacheOffset) / 255.0, 1.0);
1621
+ }
1622
+ }
1623
+
1624
+ // ========================================
1625
+ // UTILITY FUNCTIONS
1626
+ // ========================================
1627
+
1628
+ // Get maximum component of a 3D vector.
1629
+ // get the max value of a vec3
1630
+ //
1631
+ // Parameters:
1632
+ // v - vec3: Input 3D vector
1633
+ //
1634
+ // Returns:
1635
+ // float: The maximum value among the x, y, and z components
1636
+ float vec3_max(vec3 v) {
1637
+ return max(v.x, max(v.y, v.z));
1638
+ }
1639
+
1640
+ // Get minimum component of a 3D vector.
1641
+ // get the min value of a vec3
1642
+ //
1643
+ // Parameters:
1644
+ // v - vec3: Input 3D vector
1645
+ //
1646
+ // Returns:
1647
+ // float: The minimum value among the x, y, and z components
1648
+ float vec3_min(vec3 v) {
1649
+ return min(v.x, min(v.y, v.z));
1650
+ }
1651
+
1652
+ // Calculate level-of-detail based on distance.
1653
+ // Uses logarithmic scaling to determine appropriate resolution level.
1654
+ // get the LOD based on the distance to the camera
1655
+ //
1656
+ // Parameters:
1657
+ // distance - float: Distance from camera to sampling point
1658
+ // highestRes - int: Highest available resolution level (typically 0)
1659
+ // lowestRes - int: Lowest available resolution level (typically 9)
1660
+ // lodFactor - float: Scaling factor that controls LOD sensitivity
1661
+ //
1662
+ // Returns:
1663
+ // int: Resolution level index (0-9) where 0 is highest resolution
1664
+ int getLOD(float distance, int highestRes, int lowestRes, float lodFactor) {
1665
+ int lod = int(log2(distance * lodFactor));
1666
+ return clamp(lod, highestRes, lowestRes);
1667
+ }
1668
+
1669
+ // Calculate step size for ray marching at a given resolution.
1670
+ // Determines optimal sampling step size based on voxel dimensions and ray direction.
1671
+ // get the voxel step in object space
1672
+ //
1673
+ // Parameters:
1674
+ // res - int: Resolution level index (0-9, where 0 is highest resolution)
1675
+ // osDir - vec3: Ray direction vector in object space (should be normalized)
1676
+ //
1677
+ // Returns:
1678
+ // float: Optimal step size in object space units for stable ray marching
1679
+ float voxelStepOS(int res, vec3 osDir) {
1680
+ vec3 voxelSize = getScale(res) / vec3(voxelExtents);
1681
+ vec3 dt_vec = voxelSize / abs(osDir);
1682
+ return min(dt_vec.x, min(dt_vec.y, dt_vec.z));
1683
+ }
1684
+
1685
+ // ========================================
1686
+ // INTERPOLATION FUNCTIONS
1687
+ // ========================================
1688
+
1689
+ // Linear interpolation between two values.
1690
+ // Performs smooth interpolation between two scalar values.
1691
+ //
1692
+ // Parameters:
1693
+ // v0 - float: First value to interpolate from
1694
+ // v1 - float: Second value to interpolate to
1695
+ // fx - float: Interpolation factor between 0.0 and 1.0
1696
+ //
1697
+ // Returns:
1698
+ // float: Interpolated value between v0 and v1 based on fx
1699
+ float lerp(float v0, float v1, float fx) {
1700
+ return mix(v0, v1, fx); // (1-fx)·v0 + fx·v1
1701
+ }
1702
+
1703
+ // Bilinear interpolation between four values
1704
+ // Performs 2D interpolation using four corner values arranged in a square
1705
+ //
1706
+ // Parameters:
1707
+ // v00 - float: Bottom-left corner value
1708
+ // v10 - float: Bottom-right corner value
1709
+ // v01 - float: Top-left corner value
1710
+ // v11 - float: Top-right corner value
1711
+ // f - vec2: 2D interpolation factors (x, y) between 0.0 and 1.0
1712
+ //
1713
+ // Returns:
1714
+ // float: Interpolated value from the four corner values
1715
+ float bilerp(float v00, float v10, float v01, float v11, vec2 f) {
1716
+ float c0 = mix(v00, v10, f.x); // Interpolate in X on bottom row
1717
+ float c1 = mix(v01, v11, f.x); // Interpolate in X on top row
1718
+ return mix(c0, c1, f.y); // Now interpolate those in Y
1719
+ }
1720
+
1721
+ // Trilinear interpolation between eight values
1722
+ // Performs 3D interpolation using eight corner values arranged in a cube
1723
+ //
1724
+ // Parameters:
1725
+ // v000 - float: Bottom-left-back corner value
1726
+ // v100 - float: Bottom-right-back corner value
1727
+ // v010 - float: Bottom-left-front corner value
1728
+ // v110 - float: Bottom-right-front corner value
1729
+ // v001 - float: Top-left-back corner value
1730
+ // v101 - float: Top-right-back corner value
1731
+ // v011 - float: Top-left-front corner value
1732
+ // v111 - float: Top-right-front corner value
1733
+ // f - vec3: 3D interpolation factors (x, y, z) between 0.0 and 1.0
1734
+ //
1735
+ // Returns:
1736
+ // float: Interpolated value from the eight corner values
1737
+ float trilerp(
1738
+ float v000, float v100, float v010, float v110,
1739
+ float v001, float v101, float v011, float v111,
1740
+ vec3 f) { // f = fract(coord)
1741
+ // Interpolate along X for each of the four bottom-face voxels
1742
+ float c00 = mix(v000, v100, f.x);
1743
+ float c10 = mix(v010, v110, f.x);
1744
+ float c01 = mix(v001, v101, f.x);
1745
+ float c11 = mix(v011, v111, f.x);
1746
+
1747
+ // Interpolate those along Y
1748
+ float c0 = mix(c00, c10, f.y);
1749
+ float c1 = mix(c01, c11, f.y);
1750
+
1751
+ // Final interpolation along Z
1752
+ return mix(c0, c1, f.z);
1753
+ }
1754
+
1755
+ // ========================================
1756
+ // BRICK CACHE SAMPLING
1757
+ // ========================================
1758
+
1759
+ // Sample a value from the brick cache texture.
1760
+ // Converts brick coordinates and voxel position to texture coordinates for sampling.
1761
+ // sample the brick cache based on the brick cache coordinate and the in-brick coordinate
1762
+ //
1763
+ // Parameters:
1764
+ // brickCacheCoord - vec3: 3D coordinates of the brick within the brick cache
1765
+ // voxelInBrick - vec3: 3D coordinates of the voxel within the brick (0-31 in each dimension)
1766
+ //
1767
+ // Returns:
1768
+ // float: Sampled voxel value from the brick cache texture (typically normalized 0.0-1.0)
1769
+ float sampleBrick(vec3 brickCacheCoord, vec3 voxelInBrick) {
1770
+ vec3 brickCacheCoordNormalized = vec3(
1771
+ (float(brickCacheCoord.x) * BRICK_SIZE + float(voxelInBrick.x)) / BRICK_CACHE_SIZE_X,
1772
+ (float(brickCacheCoord.y) * BRICK_SIZE + float(voxelInBrick.y)) / BRICK_CACHE_SIZE_Y,
1773
+ (float(brickCacheCoord.z) * BRICK_SIZE + float(voxelInBrick.z)) / BRICK_CACHE_SIZE_Z
1774
+ );
1775
+ return texture(brickCacheTex, brickCacheCoordNormalized).r;
1776
+ }
1777
+
1778
+ /**
1779
+ * main renderloop
1780
+ */
1781
+ void main(void) {
1782
+
1783
+ // ========================================
1784
+ // INITIALIZATION
1785
+ // ========================================
1786
+
1787
+ // Initialize all render targets (multiple output textures)
1788
+ gRequest = vec4(0,0,0,0); // Brick loading requests
1789
+ gUsage = vec4(0,0,0,0); // Brick usage tracking
1790
+ gColor = vec4(0.0, 0.0, 0.0, 0.0); // Final color output
1791
+
1792
+ // out color sums up our accumulated value before writing it into the gColor buffer
1793
+ vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0); // Accumulated color
1794
+
1795
+ // Generate random number for jittered sampling (reduces artifacts)
1796
+ float rnd = random();
1797
+
1798
+ // Get the lowest available resolution level
1799
+ int lowestDataRes = getLowestRes();
1800
+
1801
+ // ========================================
1802
+ // RAY-VOLUME INTERSECTION
1803
+ // ========================================
1804
+
1805
+ // Normalize the view ray direction
1806
+ vec3 ws_rayDir = normalize(rayDirUnnorm);
1807
+
1808
+ // Calculate intersection with volume bounding box
1809
+ // Returns (entry_time, exit_time) for the ray-box intersection
1810
+ vec2 t_hit = intersect_hit(cameraCorrected, ws_rayDir);
1811
+ if (t_hit.x >= t_hit.y) { discard; } // Ray misses volume entirely
1812
+
1813
+ t_hit.x = max(t_hit.x, 0.0); // Clamp entry to 0 (no negative distances)
1814
+ float t = t_hit.x;
1815
+
1816
+ // Calculate distance from camera for LOD selection
1817
+ float distance = abs((cameraCorrected / boxSize).z + (ws_rayDir / boxSize).z * t );
1818
+
1819
+ // ========================================
1820
+ // COORDINATE SPACE CONVERSION
1821
+ // ========================================
1822
+
1823
+ // Convert from world space to object space (normalized 0-1 coordinates)
1824
+ float ws2os = length(ws_rayDir / boxSize); // Scale factor for conversion
1825
+ float t_hit_min_os = t_hit.x * ws2os; // Entry point in object space
1826
+ float t_hit_max_os = t_hit.y * ws2os; // Exit point in object space
1827
+ float t_os = t_hit_min_os; // Current position in object space
1828
+
1829
+ // Calculate effective LOD factor based on volume size.
1830
+ // voxel edge is the max extent of the volume
1831
+ float voxelEdge = float(max(voxelExtents.x, max(voxelExtents.y, voxelExtents.z)));
1832
+
1833
+ // calculate LOD factor based on the voxel edge
1834
+ float lodFactorEffective = lodFactor * voxelEdge / 256.0;
1835
+
1836
+ // ========================================
1837
+ // RESOLUTION AND SAMPLING SETUP
1838
+ // ========================================
1839
+
1840
+ // Determine target resolution based on distance (LOD)
1841
+ int targetRes = getLOD(t, 0, 9, lodFactorEffective);
1842
+
1843
+ // Set adaptive stepping resolution
1844
+ int stepResAdaptive = renderRes;
1845
+ int stepResEffective = clamp(stepResAdaptive, 0, lowestDataRes);
1846
+
1847
+ // Convert ray to object space coordinates
1848
+ vec3 os_rayDir = normalize(ws_rayDir / boxSize);
1849
+ vec3 os_rayOrigin = cameraCorrected / boxSize + vec3(0.5);
1850
+
1851
+ // Calculate step size based on current resolution
1852
+ float dt = voxelStepOS(stepResEffective, os_rayDir);
1853
+
1854
+ // ========================================
1855
+ // SAMPLING POSITION INITIALIZATION
1856
+ // ========================================
1857
+
1858
+ // Convert to normalized sampling coordinates (0-1 range)
1859
+ vec3 p = cameraCorrected + t_hit.x * ws_rayDir;
1860
+ p = p / boxSize + vec3(0.5); // Transform to 0-1 range
1861
+
1862
+ // Calculate step vector in normalized space
1863
+ vec3 dp = (os_rayDir * dt);
1864
+
1865
+ // Apply jittered sampling to reduce artifacts
1866
+ p += dp * (rnd);
1867
+ // Avoid boundary issues
1868
+ p = clamp(p, 0.0 + 0.0000028, 1.0 - 0.0000028);
1869
+
1870
+ // ========================================
1871
+ // RENDERING VARIABLES
1872
+ // ========================================
1873
+
1874
+ // Color accumulation for front-to-back compositing.
1875
+ // color accumulation variables, are calculated per 'slice'
1876
+ vec3 rgbCombo = vec3(0.0);
1877
+ float total = 0.0;
1878
+
1879
+ // For alpha blending.
1880
+ // alpha accumulation variable runs globally
1881
+ float alphaMultiplicator = 1.0;
1882
+
1883
+ // Request tracking (for brick loading).
1884
+ // if we have a request for a brick which not visible in lower
1885
+ // resolutions, we can overwrite it once
1886
+ bool overWrittenRequest = false;
1887
+
1888
+ // Current state tracking
1889
+ vec3 currentTargetResPTCoord = vec3(0,0,0);
1890
+ int currentLOD = targetRes;
1891
+
1892
+ // ========================================
1893
+ // CHANNEL-SPECIFIC CONSTANTS
1894
+ // ========================================
1895
+
1896
+ // Pre-compute channel properties for efficiency.
1897
+ // constants per color channel
1898
+ vec3 [] c_color = vec3[7](getChannelColor(0), getChannelColor(1), getChannelColor(2), getChannelColor(3), getChannelColor(4), getChannelColor(5), getChannelColor(6));
1899
+ float [] c_opacity = float[7](getChannelOpacity(0), getChannelOpacity(1), getChannelOpacity(2), getChannelOpacity(3), getChannelOpacity(4), getChannelOpacity(5), getChannelOpacity(6));
1900
+ // resolution ranges (currently) per color channel
1901
+ // TODO: figure out how to hook it up with frontend
1902
+ int [] c_res_min = int[7](getRes(0).x, getRes(1).x, getRes(2).x, getRes(3).x, getRes(4).x, getRes(5).x, getRes(6).x);
1903
+ int [] c_res_max = int[7](getRes(0).y, getRes(1).y, getRes(2).y, getRes(3).y, getRes(4).y, getRes(5).y, getRes(6).y);
1904
+ vec3 [] res_color = vec3[10](
1905
+ vec3(1.0, 0.0, 0.0),
1906
+ vec3(0.0, 0.0, 1.0),
1907
+ vec3(0.0, 1.0, 0.0),
1908
+ vec3(1.0, 0.0, 1.0),
1909
+ vec3(0.0, 1.0, 1.0),
1910
+ vec3(1.0, 1.0, 0.0),
1911
+ vec3(1.0, 0.5, 0.5),
1912
+ vec3(0.5, 0.5, 1.0),
1913
+ vec3(0.5, 1.0, 0.5),
1914
+ vec3(0.5, 0.5, 0.5)
1915
+ );
1916
+
1917
+ // ========================================
1918
+ // PER-CHANNEL STATE ARRAYS
1919
+ // ========================================
1920
+
1921
+ // Current state for each channel.
1922
+ // current state variables per color channel
1923
+
1924
+ // current resolution
1925
+ int [] c_res_current = int[7](0,0,0,0,0,0,0);
1926
+ // current value
1927
+ float [] c_val_current = float[7](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1928
+ // current brick cache coordinate
1929
+ vec3 [] c_brickCacheCoord_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1930
+ // current voxel in current resolution
1931
+ vec3 [] c_voxel_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1932
+ // current pagetable coordinate
1933
+ vec3 [] c_ptCoord_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1934
+ // current render mode -- 0: empty (add 0), 1: constant (add current val), 2: voxel (query new voxel)
1935
+ // upon change of PT we re-query anyways
1936
+ int [] c_renderMode_current = int[7](-1, -1, -1, -1, -1, -1, -1);
1937
+
1938
+ // Adjacent brick caching for interpolation
1939
+ // current pagetable coordinate of the adjacent bricks in X, Y, Z or diagonal direction
1940
+ vec3 [] c_PT_X_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1941
+ vec3 [] c_PT_Y_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1942
+ vec3 [] c_PT_Z_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1943
+ vec3 [] c_PT_XYZ_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1944
+ // corresponding brick coordinates of the adjacent bricks in X, Y, Z or diagonal direction
1945
+ vec4 [] c_brick_X_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1946
+ vec4 [] c_brick_Y_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1947
+ vec4 [] c_brick_Z_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1948
+ vec4 [] c_brick_XYZ_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1949
+
1950
+ // Min/max tracking for MIP/MinIP rendering.
1951
+ // min and max values of the current color
1952
+ // used for minimum/maximum intensity projection
1953
+ float [] c_minVal = float[7](-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
1954
+ float [] c_maxVal = float[7](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1955
+
1956
+ // Per-resolution coordinate tracking
1957
+ vec3 [] r_ptCoord = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1958
+ vec3 [] r_voxel = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1959
+ vec3 [] r_prevPTCoord = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1960
+ vec3 [] r_prevVoxel = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1961
+
1962
+ // resolution changed flag
1963
+ bool resolutionChanged = false;
1964
+ // number of repetitions (for debugging purposes)
1965
+ int reps = 0;
1966
+
1967
+ // ========================================
1968
+ // MAIN RAY-MARCHING LOOP
1969
+ // ========================================
1970
+
1971
+ // while we are 'in' the volume.
1972
+ // Continue marching until we exit the volume or reach maximum opacity.
1973
+ while (t_os < t_hit_max_os && t_os >= t_hit_min_os
1974
+ && vec3_max(p) < 1.0 && vec3_min(p) >= 0.0
1975
+ ) {
1976
+
1977
+ // Reset per-sample accumulation.
1978
+ // initialize slice values
1979
+ vec3 rgbCombo = vec3(0.0);
1980
+ float total = 0.0;
1981
+
1982
+ // Update target resolution based on current distance (with jitter).
1983
+ // calculate target resolution based on distance and lod factor
1984
+ targetRes = getLOD(t, 0, 9, lodFactorEffective * (0.999 + 0.002 * rnd));
1985
+
1986
+ // ========================================
1987
+ // RESOLUTION CHANGE HANDLING
1988
+ // ========================================
1989
+
1990
+ // if target resolution changed, update the current resolution and stepsize
1991
+ if (targetRes != currentLOD) {
1992
+ currentLOD = targetRes;
1993
+ stepResAdaptive++;
1994
+ stepResEffective = clamp(stepResAdaptive, 0, lowestDataRes);
1995
+
1996
+ // Adjust sampling position for new resolution
1997
+ p -= dp * rnd;
1998
+ dt = voxelStepOS(stepResEffective, os_rayDir);
1999
+ dp = os_rayDir * dt;
2000
+ p += dp * rnd;
2001
+ resolutionChanged = true;
2002
+
2003
+ // Check bounds after resolution change
2004
+ if (p.x < 0.0 || p.x >= 1.0 || p.y < 0.0 || p.y >= 1.0 || p.z < 0.0 || p.z >= 1.0) {
2005
+ break;
2006
+ }
2007
+ } else {
2008
+ resolutionChanged = false;
2009
+ }
2010
+
2011
+ // ========================================
2012
+ // UPDATE COORDINATES FOR ALL RESOLUTIONS
2013
+ // ========================================
2014
+
2015
+ // Calculate page table coordinates and voxel positions for all resolution levels
2016
+ for (int r = 0; r < 10; r++) {
2017
+ r_prevPTCoord[r] = r_ptCoord[r];
2018
+ r_prevVoxel[r] = r_voxel[r];
2019
+ r_ptCoord[r] = getBrickFromNormalized(p, r);
2020
+ r_voxel[r] = getVoxelFromNormalized(p, r);
2021
+ }
2022
+
2023
+ // ========================================
2024
+ // RENDER MODE DEFINITIONS
2025
+ // ========================================
2026
+ // 0: empty brick (no data)
2027
+ // 1: constant brick (uniform value)
2028
+ // 2: voxel brick (variable data)
2029
+
2030
+ // initialize the per channel slice values
2031
+ vec3 sliceColor = vec3(0.0);
2032
+ float sliceAlpha = 0.0;
2033
+
2034
+ // ========================================
2035
+ // MULTI-CHANNEL SAMPLING
2036
+ // ========================================
2037
+
2038
+ // Process each channel independently.
2039
+ // iterate over up to 7 channels by color
2040
+ for (int c = 0; c < 7; c++) {
2041
+ // Skip channels with zero opacity.
2042
+ // skip if opacity is 0 or if color is not mapped to a physical slot
2043
+ if (c_opacity[c] <= 0.000001) {
2044
+ continue;
2045
+ } else if (channelMapping[c] == -1) {
2046
+ continue;
2047
+ }
2048
+
2049
+ // physical slot in pagetable
2050
+ int slot = channelMapping[c];
2051
+
2052
+ // keep track of status
2053
+ bool newBrick = false;
2054
+ bool newVoxel = false;
2055
+ // best possible resolution
2056
+ int bestRes = clamp(targetRes, c_res_min[c], c_res_max[c]);
2057
+
2058
+ // Check if we need to load a new brick at a better resolution.
2059
+ // check if any new better resolution could be available, if so, we need to re-query the brick
2060
+ bool betterResChanged = false;
2061
+ for (int r = bestRes; r <= c_res_current[c]; r++ ) {
2062
+ if (r_ptCoord[r] != r_prevPTCoord[r]) {
2063
+ betterResChanged = true;
2064
+ break;
2065
+ }
2066
+ }
2067
+
2068
+ // Determine if we need to load new brick data.
2069
+ // check if we need to re-query the brick / voxel or reuse past 'val'
2070
+ if (r_ptCoord[bestRes] != r_prevPTCoord[bestRes]
2071
+ || c_renderMode_current[c] == -1
2072
+ || resolutionChanged == true
2073
+ || betterResChanged
2074
+ ) {
2075
+ newBrick = true;
2076
+ newVoxel = true;
2077
+ } else if (c_renderMode_current[c] == 2) {
2078
+ newVoxel = true;
2079
+ } else if (c_renderMode_current[c] == 0) {
2080
+ continue; // Skip empty bricks
2081
+ }
2082
+
2083
+ // ========================================
2084
+ // BRICK LOADING AND CACHING
2085
+ // ========================================
2086
+
2087
+ // check if a new brick is available in the best possible resolution
2088
+ if (newBrick) {
2089
+ // Query page table for brick location and status
2090
+ ivec4 brickCacheInfo = getBrickLocation(p, bestRes, slot, rnd, true, c);
2091
+ // check information about the newly queried brick
2092
+ // if the res is not at best res, possibly the same as previous brick
2093
+ if (brickCacheInfo.w == -1 || brickCacheInfo.w == -2) {
2094
+ // Empty brick - no data available.
2095
+ // we can skip the rest of the loop
2096
+ c_val_current[c] = 0.0;
2097
+ c_renderMode_current[c] = 0;
2098
+ c_minVal[c] = 0.0;
2099
+ continue;
2100
+ } else if (brickCacheInfo.w == -3) {
2101
+ // Solid brick - constant maximum value.
2102
+ // we set the value and do not need to query a voxel
2103
+ c_val_current[c] = 1.0;
2104
+ c_renderMode_current[c] = 1;
2105
+ c_maxVal[c] = 1.0;
2106
+ newVoxel = false;
2107
+ } else if (brickCacheInfo.w == -4) {
2108
+ // Constant brick - uniform value.
2109
+ // static value -- we set the value and do not need to query a voxel
2110
+ float val = float(brickCacheInfo.x);
2111
+ c_val_current[c] = max(0.0, (val - getClim(c).x) / (getClim(c).y - getClim(c).x));
2112
+ c_renderMode_current[c] = 1;
2113
+ newVoxel = false;
2114
+ } else if (brickCacheInfo.w >= 0) {
2115
+ // Voxel brick - variable data, load from cache.
2116
+ // new brick -- we set the coordinate and resolution and need to query a voxel
2117
+ c_res_current[c] = brickCacheInfo.w;
2118
+ c_ptCoord_current[c] = r_ptCoord[c_res_current[c]];
2119
+ c_brickCacheCoord_current[c] = vec3(brickCacheInfo.xyz);
2120
+ c_renderMode_current[c] = 2;
2121
+ newVoxel = true;
2122
+
2123
+ // Track brick usage for cache management.
2124
+ // we set the usage of the brick based on the channel and the relative distance into the cube
2125
+ if (int(floor(rnd * float(maxChannels))) == c) {
2126
+ setUsage(brickCacheInfo.xyz, t_hit_min_os, t_hit_max_os, t_os, rnd);
2127
+ }
2128
+ }
2129
+ }
2130
+
2131
+ // ========================================
2132
+ // VOXEL SAMPLING WITH INTERPOLATION
2133
+ // ========================================
2134
+
2135
+ // we need to query a new voxel e.g. sample the brick cache
2136
+ if (newVoxel) {
2137
+ c_voxel_current[c] = r_voxel[c_res_current[c]];
2138
+
2139
+ // we clamp the coordinate to be inside the brick and sample the volume
2140
+ reps++;
2141
+
2142
+ // Calculate position within the brick (0-31 range)
2143
+ vec3 voxelInBrick = mod(c_voxel_current[c], 32.0);
2144
+ vec3 clampedVoxelInBrick = clamp(voxelInBrick, 0.5, 31.5);
2145
+ // Sample the brick cache texture
2146
+ float val = sampleBrick(c_brickCacheCoord_current[c].xyz, clampedVoxelInBrick);
2147
+
2148
+ // ========================================
2149
+ // HIGH-QUALITY INTERPOLATION (renderRes == 0)
2150
+ // ========================================
2151
+
2152
+ // interblock interpolation
2153
+ if (renderRes == 0) {
2154
+ // calculate what axis we need to interpolate
2155
+
2156
+ // Check if we're near brick boundaries (need interpolation)
2157
+ bvec3 clampedMin = lessThan(voxelInBrick, clampedVoxelInBrick);
2158
+ bvec3 clampedMax = greaterThan(voxelInBrick, clampedVoxelInBrick);
2159
+ bvec3 clamped = bvec3(clampedMin.x || clampedMax.x, clampedMin.y || clampedMax.y, clampedMin.z || clampedMax.z);
2160
+ vec3 diff = voxelInBrick - clampedVoxelInBrick;
2161
+
2162
+ if (any(clampedMin) || any(clampedMax)) {
2163
+ int boundaryAxes = int(clamped.x) + int(clamped.y) + int(clamped.z);
2164
+ float f = 0.0;
2165
+
2166
+ if (boundaryAxes == 1) {
2167
+ // Linear interpolation across one boundary
2168
+ vec3 otherGlobalVoxelPos = vec3(0,0,0);
2169
+ vec3 otherP = vec3(0,0,0);
2170
+ float otherVoxelVal = 0.0;
2171
+
2172
+ // Determine which axis we're interpolating across
2173
+ if (clampedMin.x) {
2174
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(1.0, 0.0, 0.0);
2175
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2176
+ f = abs(diff.x);
2177
+ } else if (clampedMax.x) {
2178
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(1.0, 0.0, 0.0);
2179
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2180
+ f = abs(diff.x);
2181
+ } else if (clampedMin.y) {
2182
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(0.0, 1.0, 0.0);
2183
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2184
+ f = abs(diff.y);
2185
+ } else if (clampedMax.y) {
2186
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(0.0, 1.0, 0.0);
2187
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2188
+ f = abs(diff.y);
2189
+ } else if (clampedMin.z) {
2190
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(0.0, 0.0, 1.0);
2191
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2192
+ f = abs(diff.z);
2193
+ } else if (clampedMax.z) {
2194
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(0.0, 0.0, 1.0);
2195
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2196
+ f = abs(diff.z);
2197
+ }
2198
+
2199
+ // Sample the neighboring voxel
2200
+ vec3 otherPTcoord = getBrickFromNormalized(otherP, c_res_current[c]);
2201
+ otherPTcoord = getBrickFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2202
+ vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0);
2203
+ otherVoxelInBrick -= diff;
2204
+
2205
+ // Check if neighbor is outside volume bounds
2206
+ if (otherP.x < 0.0 || otherP.x >= 1.0 || otherP.y < 0.0 || otherP.y >= 1.0 || otherP.z < 0.0 || otherP.z >= 1.0) {
2207
+ otherVoxelVal = val;
2208
+ } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) {
2209
+ // Use cached adjacent brick
2210
+ otherVoxelVal = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick);
2211
+ } else {
2212
+ // Load new adjacent brick
2213
+ ivec4 otherBrickCacheInfo = ivec4(-1);
2214
+ if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz) {
2215
+ otherBrickCacheInfo = ivec4(c_brick_XYZ_adjacent[c]);
2216
+ } else {
2217
+ otherBrickCacheInfo = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c);
2218
+ }
2219
+ if (otherBrickCacheInfo.w == -1 || otherBrickCacheInfo.w == -2) {
2220
+ otherVoxelVal = val;
2221
+ } else if (otherBrickCacheInfo.w == -3) {
2222
+ otherVoxelVal = 1.0;
2223
+ } else if (otherBrickCacheInfo.w == -4) {
2224
+ otherVoxelVal = float(otherBrickCacheInfo.x);
2225
+ } else {
2226
+ // TODO: we do not recalculate the voxelInBrick based on the resolution
2227
+ otherVoxelVal = sampleBrick(vec3(otherBrickCacheInfo.xyz), otherVoxelInBrick);
2228
+ }
2229
+ c_PT_XYZ_adjacent[c] = getBrickFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2230
+ c_brick_XYZ_adjacent[c] = vec4(otherBrickCacheInfo);
2231
+ }
2232
+
2233
+ // Perform linear interpolation
2234
+ float originalVal = val;
2235
+ val = lerp(originalVal, otherVoxelVal, f);
2236
+ } else if (boundaryAxes == 2) {
2237
+ // Bilinear interpolation across two boundaries
2238
+ vec3 offA = vec3(0.0);
2239
+ vec3 offB = vec3(0.0);
2240
+ vec2 f = vec2(0.0);
2241
+
2242
+ // Determine which two axes we're interpolating across
2243
+ if (clamped.x && clamped.y) {
2244
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2245
+ offB.y = clampedMin.y ? -1.0 : 1.0;
2246
+ f = vec2(abs(diff.x), abs(diff.y));
2247
+ } else if (clamped.x && clamped.z) {
2248
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2249
+ offB.z = clampedMin.z ? -1.0 : 1.0;
2250
+ f = vec2(abs(diff.x), abs(diff.z));
2251
+ } else if (clamped.y && clamped.z) {
2252
+ offA.y = clampedMin.y ? -1.0 : 1.0;
2253
+ offB.z = clampedMin.z ? -1.0 : 1.0;
2254
+ f = vec2(abs(diff.y), abs(diff.z));
2255
+ }
2256
+
2257
+ // Macro for sampling at offset positions
2258
+ #define SAMPLE_AT_OFFSET(OFF, DEST) { vec3 otherGlobalVoxelPos = c_voxel_current[c] + (OFF); vec3 otherP = getNormalizedFromVoxel( otherGlobalVoxelPos, c_res_current[c]); if ( any(lessThan(otherP, vec3(0.0))) || any(greaterThanEqual(otherP, vec3(1.0))) ) { DEST = val; } else { vec3 otherPTcoord = getBrickFromNormalized( otherP, c_res_current[c]); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; bool matched = false; if (otherPTcoord == c_PT_X_adjacent[c].xyz && c_brick_X_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_X_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz && c_brick_Y_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Y_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz && c_brick_Z_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Z_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick); matched = true; } ivec4 info = ivec4(-1); if (otherPTcoord == c_PT_X_adjacent[c].xyz) { info = ivec4(c_brick_X_adjacent[c]); } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz) { info = ivec4(c_brick_Y_adjacent[c]); } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz) { info = ivec4(c_brick_Z_adjacent[c]); } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz) { info = ivec4(c_brick_XYZ_adjacent[c]); } else { info = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c); } if (!matched) { if (info.w == -1 || info.w == -2) { DEST = val; } else if (info.w == -3) { DEST = 1.0; } else if (info.w == -4) { DEST = float(info.x); } else { DEST = sampleBrick(vec3(info.xyz), otherVoxelInBrick); } if (abs((OFF).x) > 0.5 && abs((OFF).y) < 0.5 && abs((OFF).z) < 0.5) { c_PT_X_adjacent[c] = otherPTcoord; c_brick_X_adjacent[c] = vec4(info); } else if (abs((OFF).y) > 0.5 && abs((OFF).x) < 0.5 && abs((OFF).z) < 0.5) { c_PT_Y_adjacent[c] = otherPTcoord; c_brick_Y_adjacent[c] = vec4(info); } else if (abs((OFF).z) > 0.5 && abs((OFF).x) < 0.5 && abs((OFF).y) < 0.5) { c_PT_Z_adjacent[c] = otherPTcoord; c_brick_Z_adjacent[c] = vec4(info); } else { c_PT_XYZ_adjacent[c] = otherPTcoord; c_brick_XYZ_adjacent[c] = vec4(info); } } } }
2259
+
2260
+ // Sample the four corners for bilinear interpolation
2261
+ float v00 = val;
2262
+ float v10; float v01; float v11;
2263
+ SAMPLE_AT_OFFSET(offA, v10);
2264
+ SAMPLE_AT_OFFSET(offB, v01);
2265
+ SAMPLE_AT_OFFSET(offA + offB, v11);
2266
+
2267
+ val = bilerp(v00, v10, v01, v11, f);
2268
+
2269
+ #undef SAMPLE_AT_OFFSET
2270
+
2271
+ } else if (boundaryAxes == 3) {
2272
+ // Trilinear interpolation across all three boundaries
2273
+
2274
+ vec3 offA = vec3(0.0);
2275
+ vec3 offB = vec3(0.0);
2276
+ vec3 offC = vec3(0.0);
2277
+ vec3 f = vec3(0.0);
2278
+
2279
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2280
+ offB.y = clampedMin.y ? -1.0 : 1.0;
2281
+ offC.z = clampedMin.z ? -1.0 : 1.0;
2282
+
2283
+ f = vec3(abs(diff.x), abs(diff.y), abs(diff.z));
2284
+
2285
+ // Macro for sampling at offset positions
2286
+ #define SAMPLE_AT_OFFSET(OFF, DEST) { vec3 otherGlobalVoxelPos = c_voxel_current[c] + (OFF); vec3 otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]); if (any(lessThan(otherP, vec3(0.0))) || any(greaterThanEqual(otherP, vec3(1.0)))) { DEST = val; } else { vec3 otherPTcoord = getBrickFromNormalized(otherP, c_res_current[c]); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; if (otherPTcoord == c_PT_X_adjacent[c] && c_brick_X_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_X_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz && c_brick_Y_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Y_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz && c_brick_Z_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Z_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick); } else { ivec4 otherBrickCacheInfo = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; if (otherBrickCacheInfo.w == -1 || otherBrickCacheInfo.w == -2) { DEST = val; } else if (otherBrickCacheInfo.w == -3) { DEST = 1.0; } else if (otherBrickCacheInfo.w == -4) { DEST = float(otherBrickCacheInfo.x); } else { DEST = sampleBrick(vec3(otherBrickCacheInfo.xyz), otherVoxelInBrick); } } } }
2287
+
2288
+ // Sample all eight corners for trilinear interpolation
2289
+ float v000 = val;
2290
+ float v100; float v010; float v001; float v110; float v101; float v011; float v111;
2291
+ SAMPLE_AT_OFFSET(offA, v100);
2292
+ SAMPLE_AT_OFFSET(offB, v010);
2293
+ SAMPLE_AT_OFFSET(offC, v001);
2294
+ SAMPLE_AT_OFFSET(offA + offB, v110);
2295
+ SAMPLE_AT_OFFSET(offA + offC, v101);
2296
+ SAMPLE_AT_OFFSET(offB + offC, v011);
2297
+ SAMPLE_AT_OFFSET(offA + offB + offC, v111);
2298
+
2299
+ val = trilerp(v000, v100, v010, v001, v110, v101, v011, v111, f);
2300
+
2301
+ #undef SAMPLE_AT_OFFSET
2302
+
2303
+ }
2304
+
2305
+ } else {
2306
+ // No boundary interpolation needed - clear adjacent brick cache.
2307
+ // no adjacent bricks -> reset the adjacent trackers
2308
+ c_PT_X_adjacent[c] = c_PT_Y_adjacent[c] = c_PT_Z_adjacent[c] = c_PT_XYZ_adjacent[c] = vec3(-1.0);
2309
+ c_brick_X_adjacent[c] = c_brick_Y_adjacent[c] = c_brick_Z_adjacent[c] = c_brick_XYZ_adjacent[c] = vec4(-1.0);
2310
+ }
2311
+ }
2312
+
2313
+ // ========================================
2314
+ // VALUE NORMALIZATION AND TRACKING
2315
+ // ========================================
2316
+
2317
+ // Normalize value to 0-1 range using channel-specific contrast limits.
2318
+ // we normalize the (accumulated) value to the range of the color channel
2319
+ c_val_current[c] = max(0.0, (val - getClim(c).x) / (getClim(c).y - getClim(c).x));
2320
+
2321
+ // Track min/max values for MIP/MinIP rendering.
2322
+ // update the min and max values for the min/max projection
2323
+ if (c_minVal[c] == -1.0) {
2324
+ c_minVal[c] = c_val_current[c];
2325
+ } else {
2326
+ c_minVal[c] = min(c_minVal[c], c_val_current[c]);
2327
+ }
2328
+ c_maxVal[c] = max(c_maxVal[c], c_val_current[c]);
2329
+
2330
+ }
2331
+
2332
+ // ========================================
2333
+ // BRICK REQUEST GENERATION
2334
+ // ========================================
2335
+
2336
+ // Request higher resolution bricks if we're using lower resolution than optimal.
2337
+ // potentially overwrite brick request
2338
+ if (!overWrittenRequest
2339
+ && c_res_current[c] != bestRes
2340
+ && c_val_current[c] > 0.0
2341
+ && c_renderMode_current[c] == 2
2342
+ && int(floor(rnd * float(maxChannels))) == c) {
2343
+ setBrickRequest(p, bestRes, slot, rnd);
2344
+ overWrittenRequest = true;
2345
+ }
2346
+
2347
+ // ========================================
2348
+ // CHANNEL COMPOSITING
2349
+ // ========================================
2350
+
2351
+ // Accumulate this channel's contribution.
2352
+ // sum up the values onto the slice values
2353
+ total += c_val_current[c];
2354
+ if (u_renderstyle == 3) {
2355
+ rgbCombo += c_val_current[c] * res_color[targetRes];
2356
+ } else if (u_renderstyle == 4) {
2357
+ rgbCombo += c_val_current[c] * res_color[c_res_current[c]];
2358
+ } else {
2359
+ rgbCombo += c_val_current[c] * c_color[c];
2360
+ }
2361
+
2362
+ }
2363
+
2364
+ // ========================================
2365
+ // FRONT-TO-BACK COMPOSITING
2366
+ // ========================================
2367
+
2368
+ // Clamp total intensity and calculate alpha.
2369
+ // add the calculated slice to the total color
2370
+ total = clamp(total, 0.0, 1.0);
2371
+ sliceAlpha = total * opacity * dt * 32.0; // Scale by step size and brick size
2372
+ sliceColor = rgbCombo;
2373
+
2374
+ // Front-to-back alpha blending
2375
+ outColor.rgb += sliceAlpha * alphaMultiplicator * sliceColor;
2376
+ outColor.a += sliceAlpha * alphaMultiplicator;
2377
+ alphaMultiplicator *= (1.0 - sliceAlpha);
2378
+
2379
+ // Early termination for opaque regions (standard rendering only).
2380
+ // check if we can exit early
2381
+ if (outColor.a > 0.99 && u_renderstyle == 0) { break; }
2382
+
2383
+ // ========================================
2384
+ // ADVANCE RAY POSITION
2385
+ // ========================================
2386
+
2387
+ // Move to next sample position
2388
+ t += dt;
2389
+ p += dp;
2390
+ t_os += dt;
2391
+ }
2392
+
2393
+ // ========================================
2394
+ // RENDERING STYLE POST-PROCESSING
2395
+ // ========================================
2396
+
2397
+ if (u_renderstyle == 1) {
2398
+ // Minimum Intensity Projection (MinIP)
2399
+ // Shows the minimum value encountered along each ray
2400
+ outColor = vec4(0.0);
2401
+ for (int c = 0; c < 7; c++) {
2402
+ if (c_color[c] != vec3(0.0, 0.0, 0.0)) {
2403
+ outColor.rgb += c_minVal[c] * c_color[c];
2404
+ outColor.a += c_minVal[c];
2405
+ }
2406
+ }
2407
+ } else if (u_renderstyle == 0) {
2408
+ // Maximum Intensity Projection (MIP)
2409
+ // Shows the maximum value encountered along each ray
2410
+ outColor = vec4(0.0);
2411
+ for (int c = 0; c < 7; c++) {
2412
+ if (c_color[c] != vec3(0.0, 0.0, 0.0)) {
2413
+ outColor.rgb += c_maxVal[c] * c_color[c];
2414
+ }
2415
+ }
2416
+ outColor.a = 1.0;
2417
+ }
2418
+
2419
+ // ========================================
2420
+ // FINAL OUTPUT
2421
+ // ========================================
2422
+
2423
+ // Convert from linear to sRGB color space and set all render targets
2424
+ gColor = vec4(linear_to_srgb(outColor.r),
2425
+ linear_to_srgb(outColor.g),
2426
+ linear_to_srgb(outColor.b),
2427
+ outColor.a);
2428
+
2429
+ }
2430
+ `, et = {
2431
+ uniforms: {
2432
+ u_size: { value: new C(1, 1, 1) },
2433
+ clim0: { value: new _(0.2, 0.8) },
2434
+ clim1: { value: new _(0.2, 0.8) },
2435
+ clim2: { value: new _(0.2, 0.8) },
2436
+ clim3: { value: new _(0.2, 0.8) },
2437
+ clim4: { value: new _(0.2, 0.8) },
2438
+ clim5: { value: new _(0.2, 0.8) },
2439
+ clim6: { value: new _(0.2, 0.8) },
2440
+ clim7: { value: new _(0.2, 0.8) },
2441
+ xClip: { value: new _(0, 1e6) },
2442
+ yClip: { value: new _(0, 1e6) },
2443
+ zClip: { value: new _(0, 1e6) },
2444
+ u_window_size: { value: new _(1, 1) },
2445
+ u_vol_scale: { value: new C(1, 1, 1) },
2446
+ // Set renderstyle to 3 or 4 for debugging modes
2447
+ u_renderstyle: { value: 2 },
2448
+ brickCacheTex: { type: "sampler3D", value: null },
2449
+ pageTableTex: { type: "usampler3D", value: null },
2450
+ color0: { value: new Z(0, 0, 0) },
2451
+ color1: { value: new Z(0, 0, 0) },
2452
+ color2: { value: new Z(0, 0, 0) },
2453
+ color3: { value: new Z(0, 0, 0) },
2454
+ color4: { value: new Z(0, 0, 0) },
2455
+ color5: { value: new Z(0, 0, 0) },
2456
+ color6: { value: new Z(0, 0, 0) },
2457
+ channelMapping: {
2458
+ value: [-1, -1, -1, -1, -1, -1, -1]
2459
+ },
2460
+ resGlobal: { value: new _(0, 9) },
2461
+ res0: { value: new _(0, 9) },
2462
+ res1: { value: new _(0, 9) },
2463
+ res2: { value: new _(0, 9) },
2464
+ res3: { value: new _(0, 9) },
2465
+ res4: { value: new _(0, 9) },
2466
+ res5: { value: new _(0, 9) },
2467
+ res6: { value: new _(0, 9) },
2468
+ maxChannels: { value: 0 },
2469
+ lodFactor: { value: 1 },
2470
+ near: { value: 0.1 },
2471
+ far: { value: 1e4 },
2472
+ opacity: { value: 1 },
2473
+ volumeCount: { value: 0 },
2474
+ boxSize: { value: new C(1, 1, 1) },
2475
+ renderRes: { value: 1e3 },
2476
+ voxelExtents: { value: new C(1, 1, 1) },
2477
+ anchor0: { value: new C(0, 0, 0) },
2478
+ anchor1: { value: new C(0, 0, 0) },
2479
+ anchor2: { value: new C(0, 0, 0) },
2480
+ anchor3: { value: new C(0, 0, 0) },
2481
+ anchor4: { value: new C(0, 0, 0) },
2482
+ anchor5: { value: new C(0, 0, 0) },
2483
+ anchor6: { value: new C(0, 0, 0) },
2484
+ anchor7: { value: new C(0, 0, 0) },
2485
+ anchor8: { value: new C(0, 0, 0) },
2486
+ anchor9: { value: new C(0, 0, 0) },
2487
+ scale0: { value: new C(1, 1, 1) },
2488
+ scale1: { value: new C(2, 2, 2) },
2489
+ scale2: { value: new C(4, 4, 4) },
2490
+ scale3: { value: new C(8, 8, 8) },
2491
+ scale4: { value: new C(16, 16, 16) },
2492
+ scale5: { value: new C(32, 32, 32) },
2493
+ scale6: { value: new C(64, 64, 64) },
2494
+ scale7: { value: new C(128, 128, 128) },
2495
+ scale8: { value: new C(256, 256, 256) },
2496
+ scale9: { value: new C(512, 512, 512) }
2497
+ },
2498
+ vertexShader: Qe,
2499
+ fragmentShader: Je
2500
+ };
2501
+ function A(f) {
2502
+ se(le.DEBUG) && console.warn(`%cRM: ${f}`, "background: orange; color: white; padding: 2px; border-radius: 3px;");
2503
+ }
2504
+ function ne(f, t) {
2505
+ return f / t[1];
2506
+ }
2507
+ class tt {
2508
+ constructor() {
2509
+ A("Initializing VolumeRenderManager"), this.uniforms = null, this.shader = null, this.meshScale = [1, 1, 1], this.geometrySize = [1, 1, 1], this.boxSize = [1, 1, 1], this.zarrInit = !1, this.channelsVisible = [], this.channelTargetC = [], this.zarrStoreNumResolutions = null, this.channelMaxResolutionIndex = [], this.colors = [], this.contrastLimits = [], this.layerTransparency = 1, this.xSlice = new _(-1, 1e5), this.ySlice = new _(-1, 1e5), this.zSlice = new _(-1, 1e5), this.originalScale = [1, 1, 1], this.physicalDimensions = [1, 1, 1], this.maxResolution = [1, 1, 1], this.maxRange = 255, this.maxRangeSet = !1, this.initializeShader();
2510
+ }
2511
+ /**
2512
+ * Initialize shader and uniform objects
2513
+ */
2514
+ initializeShader() {
2515
+ A("Initializing shader"), this.shader = et, this.uniforms = De.clone(this.shader.uniforms);
2516
+ }
2517
+ /**
2518
+ * Extract rendering settings from coordination props
2519
+ * @param {Object} props - Component props
2520
+ * @returns {Object} Extracted rendering settings
2521
+ */
2522
+ extractRenderingSettingsFromProps(t) {
2523
+ const { images: e = {}, imageLayerScopes: i = [], imageLayerCoordination: a = [{}], imageChannelScopesByLayer: r = {}, imageChannelCoordination: o = [{}], spatialRenderingMode: l } = t, u = i[0];
2524
+ if (!u)
2525
+ return A("Extracting rendering settings from props - no layer scope"), {
2526
+ valid: !1
2527
+ };
2528
+ const s = r[u], v = a[0][u], g = o[0][u], c = e[u]?.image?.instance?.getData();
2529
+ if (!c)
2530
+ return A("Extracting rendering settings from props - no image data"), {
2531
+ valid: !1
2532
+ };
2533
+ if (!g[s?.[0]][M.SPATIAL_CHANNEL_WINDOW])
2534
+ return A("Extracting rendering settings from props - no channel window set"), {
2535
+ valid: !1
2536
+ };
2537
+ const d = e[u].image.instance, m = l === "3D", h = v[M.PHOTOMETRIC_INTERPRETATION] === "RGB", x = v[M.SPATIAL_LAYER_VISIBLE], b = v[M.SPATIAL_LAYER_OPACITY], R = h ? [
2538
+ [255, 0, 0],
2539
+ [0, 255, 0],
2540
+ [0, 0, 255]
2541
+ ] : s.map((I) => g[I][M.SPATIAL_CHANNEL_COLOR]), E = h ? [
2542
+ [0, 255],
2543
+ [0, 255],
2544
+ [0, 255]
2545
+ ] : s.map((I) => g[I][M.SPATIAL_CHANNEL_WINDOW] || [0, 255]);
2546
+ this.maxRangeSet || (this.maxRange = Math.max(...E.map((I) => I[1])), this.maxRangeSet = !0);
2547
+ const k = h ? [
2548
+ x && !0,
2549
+ x && !0,
2550
+ x && !0
2551
+ ] : s.map((I) => x && g[I][M.SPATIAL_CHANNEL_VISIBLE]), O = h ? [
2552
+ x && !0,
2553
+ x && !0,
2554
+ x && !0
2555
+ ] : s.map((I) => x && d.getChannelIndex(g[I][M.SPATIAL_TARGET_C])), X = h ? [
2556
+ x && null,
2557
+ x && null,
2558
+ x && null
2559
+ ] : s.map((I) => g[I][M.SPATIAL_MAX_RESOLUTION]);
2560
+ let T = v[M.SPATIAL_SLICE_X], L = v[M.SPATIAL_SLICE_Y], U = v[M.SPATIAL_SLICE_Z];
2561
+ const Y = v[M.SPATIAL_LOD_FACTOR] ?? 1;
2562
+ T = T !== null ? T : new _(-1, 1e5), L = L !== null ? L : new _(-1, 1e5), U = U !== null ? U : new _(-1, 1e5);
2563
+ const ie = e[u].image.loaders[0].channels;
2564
+ return A("Extracting rendering settings from props - success"), {
2565
+ valid: !0,
2566
+ channelsVisible: k,
2567
+ allChannels: ie,
2568
+ channelTargetC: O,
2569
+ channelMaxResolutionIndex: X,
2570
+ data: c,
2571
+ colors: R,
2572
+ contrastLimits: E,
2573
+ is3dMode: m,
2574
+ layerTransparency: b,
2575
+ xSlice: T,
2576
+ ySlice: L,
2577
+ zSlice: U,
2578
+ lodFactor: Y
2579
+ };
2580
+ }
2581
+ /**
2582
+ * Update the render settings from the given props
2583
+ * @param {Object} props - Component props
2584
+ * @returns {boolean} True if settings were successfully updated
2585
+ */
2586
+ updateFromProps(t) {
2587
+ const e = this.extractRenderingSettingsFromProps(t);
2588
+ return e.valid ? (this.channelsVisible = e.channelsVisible, this.channelTargetC = e.channelTargetC, this.channelMaxResolutionIndex = e.channelMaxResolutionIndex, this.colors = e.colors, this.contrastLimits = e.contrastLimits, this.renderingMode = e.renderingMode, this.layerTransparency = e.layerTransparency, this.xSlice = e.xSlice, this.ySlice = e.ySlice, this.zSlice = e.zSlice, this.uniforms.lodFactor.value = e.lodFactor, A(`lodFactor ${e.lodFactor}`), this.shader.uniforms.lodFactor.value = e.lodFactor, A("Updating from props - success"), !0) : (A("Updating from props - invalid settings"), !1);
2589
+ }
2590
+ /**
2591
+ * Update the rendering based on the current volume data from the data manager
2592
+ * @param {object} volumeDataManagerProps - Params derived from the volume data manager
2593
+ * @returns {Object|null} Updated rendering settings or null if rendering is not possible
2594
+ */
2595
+ updateRendering({ zarrStoreShapes: t, originalScaleXYZ: e, physicalDimensionsXYZ: i, maxResolutionXYZ: a, boxDimensionsXYZ: r, normalizedScaleXYZ: o, bcTHREE: l, ptTHREE: u }) {
2596
+ if (A("Updating rendering"), this.channelTargetC.findIndex((m, h) => this.channelsVisible[h]), !Array.isArray(t) || t.length === 0)
2597
+ return null;
2598
+ const s = t[0], v = {
2599
+ xLength: s[4] || 1,
2600
+ yLength: s[3] || 1,
2601
+ zLength: s[2] || 1
2602
+ }, g = [], c = [], d = [];
2603
+ if (this.channelTargetC.forEach((m, h) => {
2604
+ this.channelsVisible[h];
2605
+ {
2606
+ const b = [0, this.maxRange ? this.maxRange : 255];
2607
+ c.push([
2608
+ this.colors[h][0] / 255,
2609
+ this.colors[h][1] / 255,
2610
+ this.colors[h][2] / 255,
2611
+ this.channelsVisible[h] ? 1 : 0
2612
+ ]), n.debug("colorsSave", c), this.contrastLimits[h][0] === 0 && this.contrastLimits[h][1] === 255 ? d.push([
2613
+ ne(b[0], b),
2614
+ ne(b[1], b)
2615
+ ]) : d.push([
2616
+ ne(this.contrastLimits[h][0], b),
2617
+ ne(this.contrastLimits[h][1], b)
2618
+ ]);
2619
+ }
2620
+ }), !this.zarrInit) {
2621
+ this.originalScale = e, this.physicalDimensions = i, this.maxResolution = a;
2622
+ const m = r;
2623
+ this.normalizedScale = o, this.meshScale = [
2624
+ this.originalScale[0] / this.originalScale[0],
2625
+ this.originalScale[1] / this.originalScale[0],
2626
+ this.originalScale[2] / this.originalScale[0]
2627
+ ], this.geometrySize = m, this.boxSize = m, n.debug("this.boxSize", this.boxSize), n.debug("this.geometrySize", this.geometrySize), n.debug("this.meshScale", this.meshScale), n.debug("this.originalScale", this.originalScale), n.debug("this.physicalDimensions", this.physicalDimensions), n.debug("this.maxResolution", this.maxResolution), n.debug("scaledResolution", m), this.zarrInit = !0;
2628
+ }
2629
+ return this.updateUniforms(
2630
+ g,
2631
+ v,
2632
+ // Pass dimensions object instead of volume
2633
+ this.renderingMode,
2634
+ d,
2635
+ c,
2636
+ this.layerTransparency,
2637
+ this.xSlice,
2638
+ this.ySlice,
2639
+ this.zSlice,
2640
+ l,
2641
+ u
2642
+ ), {
2643
+ uniforms: this.uniforms,
2644
+ shader: this.shader,
2645
+ meshScale: this.meshScale,
2646
+ geometrySize: this.geometrySize,
2647
+ boxSize: this.boxSize
2648
+ };
2649
+ }
2650
+ /**
2651
+ * Update shader uniforms with current rendering values
2652
+ * @param {Array} textures - List of 3D textures
2653
+ * @param {Object} dimensions - Dimensions object
2654
+ * @param {number} renderstyle - Rendering mode value
2655
+ * @param {Array} contrastLimits - List of contrast limits for each channel
2656
+ * @param {Array} colors - List of colors for each channel
2657
+ * @param {number} layerTransparency - Overall transparency value
2658
+ * @param {Vector2} xSlice - X clipping plane
2659
+ * @param {Vector2} ySlice - Y clipping plane
2660
+ * @param {Vector2} zSlice - Z clipping plane
2661
+ */
2662
+ updateUniforms(t, e, i, a, r, o, l, u, s, v, g) {
2663
+ A("Updating uniforms"), this.uniforms.boxSize.value.set(this.boxSize[0], this.boxSize[1], this.boxSize[2]), this.uniforms.brickCacheTex.value = v, this.uniforms.pageTableTex.value = g, this.uniforms.near.value = 0.1, this.uniforms.far.value = 3e3, this.uniforms.opacity.value = o, this.uniforms.volumeCount.value = t.length, this.uniforms.u_size.value.set(e.xLength, e.yLength, e.zLength), this.uniforms.u_window_size.value.set(0, 0), this.uniforms.u_vol_scale.value.set(1 / e.xLength, 1 / e.yLength, 1 / e.zLength * 2), this.uniforms.clim0.value.set(a.length > 0 ? a[0][0] : null, a.length > 0 ? a[0][1] : null), this.uniforms.clim1.value.set(a.length > 1 ? a[1][0] : null, a.length > 1 ? a[1][1] : null), this.uniforms.clim2.value.set(a.length > 2 ? a[2][0] : null, a.length > 2 ? a[2][1] : null), this.uniforms.clim3.value.set(a.length > 3 ? a[3][0] : null, a.length > 3 ? a[3][1] : null), this.uniforms.clim4.value.set(a.length > 4 ? a[4][0] : null, a.length > 4 ? a[4][1] : null), this.uniforms.clim5.value.set(a.length > 5 ? a[5][0] : null, a.length > 5 ? a[5][1] : null), this.uniforms.clim6.value.set(a.length > 6 ? a[6][0] : null, a.length > 6 ? a[6][1] : null), this.uniforms.xClip.value.set(l[0] * (1 / this.maxResolution[0]) * this.boxSize[0], l[1] * (1 / this.maxResolution[0]) * this.boxSize[0]), this.uniforms.yClip.value.set(u[0] * (1 / this.maxResolution[1]) * this.boxSize[1], u[1] * (1 / this.maxResolution[1]) * this.boxSize[1]), this.uniforms.zClip.value.set(s[0] * (1 / this.maxResolution[2]) * this.boxSize[2], s[1] * (1 / this.maxResolution[2]) * this.boxSize[2]), this.uniforms.color0.value.set(r.length > 0 ? r[0][0] : null, r.length > 0 ? r[0][1] : null, r.length > 0 ? r[0][2] : null, r.length > 0 ? r[0][3] : null), this.uniforms.color1.value.set(r.length > 1 ? r[1][0] : null, r.length > 1 ? r[1][1] : null, r.length > 1 ? r[1][2] : null, r.length > 1 ? r[1][3] : null), this.uniforms.color2.value.set(r.length > 2 ? r[2][0] : null, r.length > 2 ? r[2][1] : null, r.length > 2 ? r[2][2] : null, r.length > 2 ? r[2][3] : null), this.uniforms.color3.value.set(r.length > 3 ? r[3][0] : null, r.length > 3 ? r[3][1] : null, r.length > 3 ? r[3][2] : null, r.length > 3 ? r[3][3] : null), this.uniforms.color4.value.set(r.length > 4 ? r[4][0] : null, r.length > 4 ? r[4][1] : null, r.length > 4 ? r[4][2] : null, r.length > 4 ? r[4][3] : null), this.uniforms.color5.value.set(r.length > 5 ? r[5][0] : null, r.length > 5 ? r[5][1] : null, r.length > 5 ? r[5][2] : null, r.length > 5 ? r[5][3] : null), this.uniforms.color6.value.set(r.length > 6 ? r[6][0] : null, r.length > 6 ? r[6][1] : null, r.length > 6 ? r[6][2] : null, r.length > 6 ? r[6][3] : null);
2664
+ for (let c = 0; c < 7; c++)
2665
+ typeof this.channelMaxResolutionIndex[c] == "number" && this.uniforms[`res${c}`].value.set(Math.max(1, this.channelMaxResolutionIndex[c]), this.zarrStoreNumResolutions - 1);
2666
+ }
2667
+ /**
2668
+ * Sets the processing render target
2669
+ * @param {WebGLMultipleRenderTargets} mrt - Multiple render targets object with 3 attachments
2670
+ */
2671
+ /*
2672
+ setProcessingTargets(mrt) {
2673
+ logWithColor('setting processing targets');
2674
+ this.mrt = mrt;
2675
+ }
2676
+ */
2677
+ setChannelMapping(t) {
2678
+ A("setting channel mapping"), n.debug("channelMapping", t), this.uniforms.channelMapping.value = t;
2679
+ }
2680
+ // Only called on initialization of the
2681
+ // VolumeDataManager and VolumeRenderManager for a particular image.
2682
+ setZarrUniforms(t, e) {
2683
+ A("setting zarr uniforms"), n.debug("zarrStore", t), n.debug("PT", e);
2684
+ for (let i = 0; i <= 9; i++)
2685
+ e.anchors && e.anchors[i] ? this.uniforms[`anchor${i}`].value.set(e.anchors[i][0] || 0, e.anchors[i][1] || 0, e.anchors[i][2] || 0) : (n.debug("anchor", i, "does not exist"), this.uniforms[`anchor${i}`].value.set(0, 0, 0)), t.scales && t.scales[i] ? this.uniforms[`scale${i}`].value.set(t.scales[i][0] || 1, t.scales[i][1] || 1, t.scales[i][2] || 1) : n.debug("scale", i, "does not exist");
2686
+ n.debug("zarrStore.brickLayout", t.brickLayout), this.zarrStoreNumResolutions = t.brickLayout.length;
2687
+ for (let i = 0; i < 7; i++)
2688
+ this.uniforms[`res${i}`].value.set(
2689
+ // TODO(mark) make this dependent on the per-channel maxResolution slider value.
2690
+ 1,
2691
+ t.brickLayout.length - 1
2692
+ );
2693
+ this.uniforms.resGlobal.value.set(1, t.brickLayout.length - 1), this.uniforms.voxelExtents.value.set(t.shapes[0][4], t.shapes[0][3], t.shapes[0][2]), this.uniforms.maxChannels.value = Math.min(t.channelCount, 7), n.debug("this.channelsVisible", this.channelsVisible), n.debug("zarrStore.shapes[0]", t.shapes[0]), n.debug("PT", e), n.debug("uniforms", this.uniforms);
2694
+ }
2695
+ }
2696
+ const nt = `//
2697
+ varying vec2 vUv;
2698
+ void main() {
2699
+ vUv = uv;
2700
+ gl_Position = vec4(position, 1.0);
2701
+ }
2702
+ `, rt = `//
2703
+ // Input texture to blur
2704
+ uniform sampler2D tDiffuse;
2705
+ // Resolution of the texture (width, height)
2706
+ uniform vec2 resolution;
2707
+ // Blur strength: 1=no blur, 2-3=3x3 kernel, 4-5=5x5 kernel, 6+=7x7 kernel
2708
+ uniform int gaussian;
2709
+ // Texture coordinates for current pixel
2710
+ varying vec2 vUv;
2711
+
2712
+ /**
2713
+ * No blur - returns the original pixel color
2714
+ */
2715
+ vec4 noGaussian() {
2716
+ vec4 color = texture2D(tDiffuse, vUv);
2717
+ return color;
2718
+ }
2719
+
2720
+ /**
2721
+ * Applies 3x3 Gaussian blur kernel
2722
+ * Samples 9 pixels in a 3x3 grid around the current pixel
2723
+ * Weights are based on 2D Gaussian distribution
2724
+ */
2725
+ vec4 gaussian3(vec2 texel) {
2726
+ vec4 color = vec4(0.0);
2727
+
2728
+ // Top row: weights [0.0625, 0.125, 0.0625]
2729
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 0.0625;
2730
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 0.125;
2731
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 0.0625;
2732
+
2733
+ // Middle row: weights [0.125, 0.25, 0.125] (center pixel gets highest weight)
2734
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 0.125;
2735
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 0.25;
2736
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 0.125;
2737
+
2738
+ // Bottom row: weights [0.0625, 0.125, 0.0625]
2739
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 0.0625;
2740
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 0.125;
2741
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 0.0625;
2742
+
2743
+ return color;
2744
+ }
2745
+
2746
+ /**
2747
+ * Applies 5x5 Gaussian blur kernel
2748
+ * Samples 25 pixels in a 5x5 grid around the current pixel
2749
+ * Weights sum to 1.0 (273/273) for proper normalization
2750
+ */
2751
+ vec4 gaussian5(vec2 texel) {
2752
+ vec4 color = vec4(0.0);
2753
+
2754
+ // Row 1: weights [1/273, 4/273, 7/273, 4/273, 1/273]
2755
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -2.0)) * 1.0/273.0;
2756
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -2.0)) * 4.0/273.0;
2757
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -2.0)) * 7.0/273.0;
2758
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -2.0)) * 4.0/273.0;
2759
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -2.0)) * 1.0/273.0;
2760
+
2761
+ // Row 2: weights [4/273, 16/273, 26/273, 16/273, 4/273]
2762
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -1.0)) * 4.0/273.0;
2763
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 16.0/273.0;
2764
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 26.0/273.0;
2765
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 16.0/273.0;
2766
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -1.0)) * 4.0/273.0;
2767
+
2768
+ // Row 3 (center): weights [7/273, 26/273, 41/273, 26/273, 7/273]
2769
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 0.0)) * 7.0/273.0;
2770
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 26.0/273.0;
2771
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 41.0/273.0; // Center pixel
2772
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 26.0/273.0;
2773
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 0.0)) * 7.0/273.0;
2774
+
2775
+ // Row 4: weights [4/273, 16/273, 26/273, 16/273, 4/273]
2776
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 1.0)) * 4.0/273.0;
2777
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 16.0/273.0;
2778
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 26.0/273.0;
2779
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 16.0/273.0;
2780
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 1.0)) * 4.0/273.0;
2781
+
2782
+ // Row 5: weights [1/273, 4/273, 7/273, 4/273, 1/273]
2783
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 2.0)) * 1.0/273.0;
2784
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 2.0)) * 4.0/273.0;
2785
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 2.0)) * 7.0/273.0;
2786
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 2.0)) * 4.0/273.0;
2787
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 2.0)) * 1.0/273.0;
2788
+
2789
+ return color;
2790
+ }
2791
+
2792
+ /**
2793
+ * Applies 7x7 Gaussian blur kernel
2794
+ * Samples 49 pixels in a 7x7 grid around the current pixel
2795
+ * Weights sum to 1.0 (1003/1003) for proper normalization
2796
+ * Creates the strongest blur effect
2797
+ */
2798
+ vec4 gaussian7(vec2 texel) {
2799
+ vec4 color = vec4(0.0);
2800
+
2801
+ // Row 1: weights [0, 0, 1/1003, 2/1003, 1/1003, 0, 0]
2802
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -3.0)) * 1.0/1003.0;
2803
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -3.0)) * 2.0/1003.0;
2804
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -3.0)) * 1.0/1003.0;
2805
+
2806
+ // Row 2: weights [0, 3/1003, 13/1003, 22/1003, 13/1003, 3/1003, 0]
2807
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -2.0)) * 3.0/1003.0;
2808
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -2.0)) * 13.0/1003.0;
2809
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -2.0)) * 22.0/1003.0;
2810
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -2.0)) * 13.0/1003.0;
2811
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -2.0)) * 3.0/1003.0;
2812
+
2813
+ // Row 3: weights [1/1003, 13/1003, 59/1003, 97/1003, 59/1003, 13/1003, 1/1003]
2814
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, -1.0)) * 1.0/1003.0;
2815
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -1.0)) * 13.0/1003.0;
2816
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 59.0/1003.0;
2817
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 97.0/1003.0;
2818
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 59.0/1003.0;
2819
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -1.0)) * 13.0/1003.0;
2820
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, -1.0)) * 1.0/1003.0;
2821
+
2822
+ // Row 4 (center): weights [2/1003, 22/1003, 97/1003, 159/1003, 97/1003, 22/1003, 2/1003]
2823
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, 0.0)) * 2.0/1003.0;
2824
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 0.0)) * 22.0/1003.0;
2825
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 97.0/1003.0;
2826
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 159.0/1003.0; // Center pixel
2827
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 97.0/1003.0;
2828
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 0.0)) * 22.0/1003.0;
2829
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, 0.0)) * 2.0/1003.0;
2830
+
2831
+ // Row 5: weights [1/1003, 13/1003, 59/1003, 97/1003, 59/1003, 13/1003, 1/1003]
2832
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, 1.0)) * 1.0/1003.0;
2833
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 1.0)) * 13.0/1003.0;
2834
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 59.0/1003.0;
2835
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 97.0/1003.0;
2836
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 59.0/1003.0;
2837
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 1.0)) * 13.0/1003.0;
2838
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, 1.0)) * 1.0/1003.0;
2839
+
2840
+ // Row 6: weights [0, 3/1003, 13/1003, 22/1003, 13/1003, 3/1003, 0]
2841
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 2.0)) * 3.0/1003.0;
2842
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 2.0)) * 13.0/1003.0;
2843
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 2.0)) * 22.0/1003.0;
2844
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 2.0)) * 13.0/1003.0;
2845
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 2.0)) * 3.0/1003.0;
2846
+
2847
+ // Row 7: weights [0, 0, 1/1003, 2/1003, 1/1003, 0, 0]
2848
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 3.0)) * 1.0/1003.0;
2849
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 3.0)) * 2.0/1003.0;
2850
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 3.0)) * 1.0/1003.0;
2851
+
2852
+ return color;
2853
+ }
2854
+
2855
+ /**
2856
+ * Main fragment shader function
2857
+ * Determines which blur kernel to apply based on the 'gaussian' uniform
2858
+ */
2859
+ void main() {
2860
+ // Calculate the size of one texel (pixel) in texture coordinates
2861
+ vec2 texel = 1.0 / resolution;
2862
+
2863
+ // Initialize output color (this line appears to be unused/debug code)
2864
+ vec4 color = vec4(1.0, 0.0, 0.0, 0.0);
2865
+
2866
+ // TODO: remove these variables since not used
2867
+ bool left = vUv.x < 0.5;
2868
+ bool top = vUv.y < 0.5;
2869
+
2870
+ if (gaussian > 1 && gaussian <= 3) {
2871
+ // Apply 3x3 Gaussian blur for values 2-3
2872
+ color = gaussian3(texel);
2873
+ } else if (gaussian > 3 && gaussian <= 5) {
2874
+ // Apply 5x5 Gaussian blur for values 4-5
2875
+ color = gaussian5(texel);
2876
+ } else if (gaussian > 5) {
2877
+ // Apply 7x7 Gaussian blur for values 6 and above
2878
+ color = gaussian7(texel);
2879
+ } else {
2880
+ // No blur for value 1 or less
2881
+ color = noGaussian();
2882
+ }
2883
+
2884
+ // Output the final blurred color
2885
+ gl_FragColor = color;
2886
+ }
2887
+ `;
2888
+ function be(f, t) {
2889
+ const e = f.properties?.get(t);
2890
+ return e?.framebuffer || e?.__webglFramebuffer || t.__webglFramebuffer;
2891
+ }
2892
+ function Q(f) {
2893
+ se(le.DEBUG) && console.warn(`%cV: ${f}`, "background: deeppink; color: white; padding: 2px; border-radius: 3px;");
2894
+ }
2895
+ function it(f, t, e, { mrtRef: i }) {
2896
+ f.setRenderTarget(i.current), f.clear(!0, !0, !0), f.render(e, t);
2897
+ }
2898
+ function at(f, { screenSceneRef: t, screenCameraRef: e }) {
2899
+ f.setRenderTarget(null), f.clear(!0, !0, !0), f.render(t.current, e.current);
2900
+ }
2901
+ function ot(f, { frameRef: t, dataManager: e, mrtRef: i, bufRequest: a, bufUsage: r }) {
2902
+ const o = f.getContext(), l = t.current;
2903
+ e.noNewRequests === !0 && !e.manuallyStopped && l % 100 === 0 && l < 500 && (e.noNewRequests = !1), e.triggerRequest === !0 && e.noNewRequests === !1 ? (o.bindFramebuffer(o.READ_FRAMEBUFFER, be(f, i.current)), o.readBuffer(o.COLOR_ATTACHMENT1), o.readPixels(0, 0, i.current.width, i.current.height, o.RGBA, o.UNSIGNED_BYTE, a.current), e.processRequestData(a.current, {
2904
+ // If width/height are not yet available,
2905
+ // processRequestData will proceed without weighting.
2906
+ width: i?.current?.width,
2907
+ height: i?.current?.height,
2908
+ // Default sigmaNormalized = 0.25; can be tuned
2909
+ sigmaNormalized: Ke
2910
+ })) : e.triggerUsage === !0 && e.noNewRequests === !1 && (o.bindFramebuffer(o.READ_FRAMEBUFFER, be(f, i.current)), o.readBuffer(o.COLOR_ATTACHMENT2), o.readPixels(0, 0, i.current.width, i.current.height, o.RGBA, o.UNSIGNED_BYTE, r.current), e.processUsageData(r.current));
2911
+ }
2912
+ function st(f, t) {
2913
+ const { invalidate: e, isInteracting: i, dataManager: a, spatialRenderingModeChanging: r, meshRef: o, stillRef: l, screenQuadRef: u, lastSampleRef: s, frameRef: v, lastFrameCountRef: g } = t;
2914
+ if (u.current && (l.current ? u.current.material.uniforms.gaussian.value = 0 : u.current.material.uniforms.gaussian.value = 7), i) {
2915
+ a.manuallyStopped || (a.noNewRequests = !1, a.triggerUsage = !0);
2916
+ return;
2917
+ }
2918
+ if (r)
2919
+ return;
2920
+ const c = o.current?.material?.uniforms, d = c?.renderRes?.value ?? a?.PT?.lowestDataRes;
2921
+ if (a.noNewRequests) {
2922
+ d !== 0 ? (c && (c.renderRes.value = 0), n.debug("Adaptive Quality: No new requests. Setting renderSpeed to 0 (best quality)."), l.current = !1, u.current.material.uniforms.gaussian.value = 7, e()) : l.current || (n.debug("Adaptive Quality: No new requests and already at best quality. Setting stillRef to true."), l.current = !0, u.current.material.uniforms.gaussian.value = 0);
2923
+ return;
2924
+ }
2925
+ l.current && (l.current = !1, e());
2926
+ const m = f.getElapsedTime();
2927
+ if (m - s.current < 1)
2928
+ return;
2929
+ const h = m - s.current, x = v.current - g.current;
2930
+ let b = 0;
2931
+ h > 0 && (b = x / h), s.current = m, g.current = v.current;
2932
+ const R = b > 100 && d > 0, E = b < 30 && d < a.PT.lowestDataRes;
2933
+ if (R || E) {
2934
+ const k = d + (E ? 1 : -1);
2935
+ c && (c.renderRes.value = k), e();
2936
+ }
2937
+ }
2938
+ function lt(f) {
2939
+ const {
2940
+ images: t,
2941
+ imageLayerScopes: e,
2942
+ imageLayerCoordination: i,
2943
+ imageChannelScopesByLayer: a,
2944
+ imageChannelCoordination: r,
2945
+ // onInitComplete,
2946
+ spatialRenderingMode: o,
2947
+ spatialRenderingModeChanging: l,
2948
+ onVolumeLoadingUpdate: u
2949
+ } = f, {
2950
+ gl: s
2951
+ // scene,
2952
+ // camera
2953
+ } = ve(), v = ve((y) => y.invalidate), g = P(null), c = P(null), d = P(null), m = P(null), h = P(null), [x, b] = fe({
2954
+ uniforms: null,
2955
+ shader: null,
2956
+ meshScale: [1, 1, 1],
2957
+ geometrySize: [1, 1, 1]
2958
+ }), R = o === "3D", E = P(null), k = P(null), O = P(null), [X, T] = fe(!1), L = P(null), U = P(!1), Y = P(0), ie = P(0), I = P(0), p = de(() => new $e(s), [s]), w = de(() => new tt(), []);
2959
+ $(() => {
2960
+ Q("useEffect MRT target matching canvas");
2961
+ const { width: y, height: D } = s.domElement, q = new Me(y, D, 3);
2962
+ q.texture.forEach((W) => {
2963
+ W.format = Pe, W.type = _e, W.minFilter = re, W.magFilter = re, W.generateMipmaps = !1;
2964
+ });
2965
+ const F = new Ae(), ee = new Be(-1, 1, 1, -1, 0.1, 10);
2966
+ ee.position.z = 1;
2967
+ const te = new Ne({
2968
+ uniforms: {
2969
+ // Bind the first render target texture as the input of the gaussian blur shader.
2970
+ tDiffuse: { value: q.texture[0] },
2971
+ resolution: { value: new _(y, D) },
2972
+ gaussian: { value: 7 }
2973
+ },
2974
+ vertexShader: nt,
2975
+ fragmentShader: rt,
2976
+ transparent: !0
2977
+ }), K = new Ue(new Le(2, 2), te);
2978
+ return F.add(K), E.current = F, k.current = ee, O.current = K, d.current = new Uint8Array(y * D * 4), m.current = new Uint8Array(y * D * 4), h.current = q, () => {
2979
+ q.dispose(), te.dispose(), K.geometry.dispose();
2980
+ };
2981
+ }, [s]);
2982
+ const ae = e?.[0], Ce = t?.[ae];
2983
+ a?.[ae];
2984
+ const J = r?.[0]?.[ae];
2985
+ $(() => {
2986
+ Q("useEffect INIT");
2987
+ let y = !1;
2988
+ if (!p || !w) {
2989
+ n.debug("dataManager or renderManager not initialized yet");
2990
+ return;
2991
+ }
2992
+ if (!Ce) {
2993
+ n.debug("no first image layer yet");
2994
+ return;
2995
+ }
2996
+ if (!J) {
2997
+ n.debug("no firstImageLayerChannelCoordination yet");
2998
+ return;
2999
+ }
3000
+ return (async () => {
3001
+ if (p.initStatus === V.COMPLETE) {
3002
+ n.debug("dataManager already initialized, skipping");
3003
+ return;
3004
+ }
3005
+ if (p.initImages(t, e), await p.init(J), y) {
3006
+ n.debug("Initialization useEffect has rerun, aborting remaining initialization");
3007
+ return;
3008
+ }
3009
+ n.debug("dataManager initialized"), w.setZarrUniforms(p.zarrStore, p.PT), w.setChannelMapping(p.channels.colorMappings), n.debug("rm.uniforms", w.uniforms), v();
3010
+ })(), () => {
3011
+ y = !0;
3012
+ };
3013
+ }, [p, w, t, e]), $(() => {
3014
+ if (o === "3D" && p && w) {
3015
+ Q("useEffect spatialRenderingMode");
3016
+ const D = {
3017
+ images: t,
3018
+ imageLayerScopes: e,
3019
+ imageLayerCoordination: i,
3020
+ imageChannelScopesByLayer: a,
3021
+ imageChannelCoordination: r,
3022
+ spatialRenderingMode: o
3023
+ };
3024
+ if (w.updateFromProps(D)) {
3025
+ const { zarrInit: q } = w;
3026
+ q || (p.ptTHREE.needsUpdate = !1, p.bcTHREE.needsUpdate = !1, p.renderer.initTexture(p.bcTHREE), p.renderer.initTexture(p.ptTHREE), p.initTexture());
3027
+ const F = w.updateRendering({
3028
+ zarrStoreShapes: p.zarrStore.shapes,
3029
+ originalScaleXYZ: p.getOriginalScaleXYZ(),
3030
+ physicalDimensionsXYZ: p.getPhysicalDimensionsXYZ(),
3031
+ maxResolutionXYZ: p.getMaxResolutionXYZ(),
3032
+ boxDimensionsXYZ: p.getBoxDimensionsXYZ(),
3033
+ normalizedScaleXYZ: p.getNormalizedScaleXYZ(),
3034
+ bcTHREE: p.bcTHREE,
3035
+ ptTHREE: p.ptTHREE
3036
+ });
3037
+ F && b(F);
3038
+ }
3039
+ }
3040
+ }, [p, w, t, e, i, a, r, o]), Ge((y, D, q) => {
3041
+ if (!h.current || !p || !w || !x.shader)
3042
+ return;
3043
+ const { gl: F, camera: ee, scene: te, clock: K } = y;
3044
+ U.current || it(F, ee, te, { mrtRef: h }), at(F, { screenSceneRef: E, screenCameraRef: k }), ot(F, { frameRef: Y, dataManager: p, mrtRef: h, bufRequest: d, bufUsage: m }), st(K, {
3045
+ invalidate: v,
3046
+ isInteracting: X,
3047
+ dataManager: p,
3048
+ spatialRenderingModeChanging: l,
3049
+ meshRef: c,
3050
+ stillRef: U,
3051
+ screenQuadRef: O,
3052
+ lastSampleRef: ie,
3053
+ frameRef: Y,
3054
+ lastFrameCountRef: I
3055
+ }), Y.current += 1;
3056
+ }, 1);
3057
+ const H = j((y) => {
3058
+ if (Q("invalidateOnInteraction callback"), T(y), y) {
3059
+ const D = c.current?.material?.uniforms;
3060
+ D && (D.renderRes.value = p.PT.lowestDataRes), U.current = !1, v();
3061
+ }
3062
+ }), Re = j((y) => {
3063
+ H(!0);
3064
+ }), ye = j((y) => {
3065
+ clearTimeout(L.current), L.current = setTimeout(() => {
3066
+ H(!1);
3067
+ }, 300);
3068
+ });
3069
+ $(() => {
3070
+ Q("useEffect firstImageLayerChannelCoordination"), H(!0), n.debug("something about channels changed"), p.updateChannels(J), w.setChannelMapping(p.channels.colorMappings), clearTimeout(L.current), L.current = setTimeout(() => {
3071
+ H(!1);
3072
+ }, 300);
3073
+ }, [p, J, w, H]);
3074
+ const Ee = j(() => {
3075
+ p && p.stopLoading();
3076
+ }), Te = j(() => {
3077
+ p && p.restartLoading();
3078
+ }), Se = j(() => p ? p.getLoadingProgress() : null);
3079
+ return $(() => {
3080
+ if (!u)
3081
+ return;
3082
+ const y = setInterval(() => {
3083
+ const D = Se();
3084
+ u({
3085
+ loadingProgress: D,
3086
+ stillRef: U,
3087
+ onStopLoading: Ee,
3088
+ onRestartLoading: Te
3089
+ });
3090
+ }, 1e3);
3091
+ return () => clearInterval(y);
3092
+ }, [u, U]), !R || !p || !w ? null : x.shader ? N.jsxs("group", { children: [N.jsx(
3093
+ me,
3094
+ {
3095
+ // ref={mainOrbitControlsRef}
3096
+ enableDamping: !1,
3097
+ onStart: Re,
3098
+ onEnd: ye
3099
+ }
3100
+ ), N.jsxs("mesh", { ref: c, scale: x.meshScale, children: [N.jsx("boxGeometry", { args: x.geometrySize }), N.jsx("shaderMaterial", { uniforms: x.uniforms, vertexShader: x.shader.vertexShader, fragmentShader: x.shader.fragmentShader, side: Fe, transparent: !1, glslVersion: Oe })] })] }) : N.jsxs("group", { children: [N.jsxs("mesh", { children: [N.jsx("boxGeometry", { args: [1, 1, 1] }), N.jsx("meshBasicMaterial", { color: "#444", wireframe: !0 })] }), N.jsx(me, { ref: g })] });
3101
+ }
3102
+ function dt(f) {
3103
+ return N.jsx(qe, { frameloop: "always", style: {
3104
+ position: "absolute",
3105
+ top: 0,
3106
+ left: 0,
3107
+ width: "100%",
3108
+ height: "100%",
3109
+ padding: 0,
3110
+ margin: 0
3111
+ // backgroundColor: 'white',
3112
+ }, camera: {
3113
+ fov: 50,
3114
+ up: [0, 1, 0],
3115
+ position: [0, 0, 4],
3116
+ near: 0.01,
3117
+ far: 15
3118
+ }, gl: {
3119
+ antialias: !0,
3120
+ logarithmicDepthBuffer: !1,
3121
+ preserveDrawingBuffer: !1,
3122
+ autoClear: !1
3123
+ }, children: N.jsx(Ve, { fallback: "Initializing Volume View...", children: N.jsx(lt, { ...f }) }) });
3124
+ }
3125
+ export {
3126
+ dt as SpatialWrapper
3127
+ };