@vitessce/launcher 3.8.6

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