vitessce 3.7.0 → 3.8.0

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