@luma.gl/core 9.3.0-alpha.4 → 9.3.0-alpha.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 (102) hide show
  1. package/dist/adapter/canvas-context.d.ts +6 -182
  2. package/dist/adapter/canvas-context.d.ts.map +1 -1
  3. package/dist/adapter/canvas-context.js +5 -481
  4. package/dist/adapter/canvas-context.js.map +1 -1
  5. package/dist/adapter/canvas-observer.d.ts +32 -0
  6. package/dist/adapter/canvas-observer.d.ts.map +1 -0
  7. package/dist/adapter/canvas-observer.js +90 -0
  8. package/dist/adapter/canvas-observer.js.map +1 -0
  9. package/dist/adapter/canvas-surface.d.ts +150 -0
  10. package/dist/adapter/canvas-surface.d.ts.map +1 -0
  11. package/dist/adapter/canvas-surface.js +392 -0
  12. package/dist/adapter/canvas-surface.js.map +1 -0
  13. package/dist/adapter/device.d.ts +64 -9
  14. package/dist/adapter/device.d.ts.map +1 -1
  15. package/dist/adapter/device.js +108 -4
  16. package/dist/adapter/device.js.map +1 -1
  17. package/dist/adapter/luma.js +1 -1
  18. package/dist/adapter/presentation-context.d.ts +11 -0
  19. package/dist/adapter/presentation-context.d.ts.map +1 -0
  20. package/dist/adapter/presentation-context.js +12 -0
  21. package/dist/adapter/presentation-context.js.map +1 -0
  22. package/dist/adapter/resources/buffer.d.ts +1 -1
  23. package/dist/adapter/resources/buffer.d.ts.map +1 -1
  24. package/dist/adapter/resources/buffer.js +14 -6
  25. package/dist/adapter/resources/buffer.js.map +1 -1
  26. package/dist/adapter/resources/command-encoder.d.ts +22 -1
  27. package/dist/adapter/resources/command-encoder.d.ts.map +1 -1
  28. package/dist/adapter/resources/command-encoder.js +65 -1
  29. package/dist/adapter/resources/command-encoder.js.map +1 -1
  30. package/dist/adapter/resources/fence.d.ts +1 -1
  31. package/dist/adapter/resources/fence.d.ts.map +1 -1
  32. package/dist/adapter/resources/fence.js +3 -1
  33. package/dist/adapter/resources/fence.js.map +1 -1
  34. package/dist/adapter/resources/query-set.d.ts +17 -1
  35. package/dist/adapter/resources/query-set.d.ts.map +1 -1
  36. package/dist/adapter/resources/query-set.js.map +1 -1
  37. package/dist/adapter/resources/render-pipeline.d.ts +19 -7
  38. package/dist/adapter/resources/render-pipeline.d.ts.map +1 -1
  39. package/dist/adapter/resources/render-pipeline.js +20 -2
  40. package/dist/adapter/resources/render-pipeline.js.map +1 -1
  41. package/dist/adapter/resources/resource.d.ts +8 -0
  42. package/dist/adapter/resources/resource.d.ts.map +1 -1
  43. package/dist/adapter/resources/resource.js +240 -14
  44. package/dist/adapter/resources/resource.js.map +1 -1
  45. package/dist/adapter/resources/shared-render-pipeline.d.ts +22 -0
  46. package/dist/adapter/resources/shared-render-pipeline.d.ts.map +1 -0
  47. package/dist/adapter/resources/shared-render-pipeline.js +25 -0
  48. package/dist/adapter/resources/shared-render-pipeline.js.map +1 -0
  49. package/dist/adapter/resources/texture.d.ts +78 -12
  50. package/dist/adapter/resources/texture.d.ts.map +1 -1
  51. package/dist/adapter/resources/texture.js +182 -30
  52. package/dist/adapter/resources/texture.js.map +1 -1
  53. package/dist/dist.dev.js +952 -193
  54. package/dist/dist.min.js +6 -6
  55. package/dist/index.cjs +918 -190
  56. package/dist/index.cjs.map +4 -4
  57. package/dist/index.d.ts +4 -1
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +2 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/shadertypes/data-types/decode-shader-types.d.ts +2 -2
  62. package/dist/shadertypes/data-types/decode-shader-types.d.ts.map +1 -1
  63. package/dist/shadertypes/data-types/decode-shader-types.js +11 -2
  64. package/dist/shadertypes/data-types/decode-shader-types.js.map +1 -1
  65. package/dist/shadertypes/textures/texture-format-decoder.d.ts.map +1 -1
  66. package/dist/shadertypes/textures/texture-format-decoder.js +51 -6
  67. package/dist/shadertypes/textures/texture-format-decoder.js.map +1 -1
  68. package/dist/shadertypes/textures/texture-format-table.d.ts.map +1 -1
  69. package/dist/shadertypes/textures/texture-format-table.js +10 -9
  70. package/dist/shadertypes/textures/texture-format-table.js.map +1 -1
  71. package/dist/shadertypes/textures/texture-formats.d.ts +5 -2
  72. package/dist/shadertypes/textures/texture-formats.d.ts.map +1 -1
  73. package/dist/shadertypes/textures/texture-formats.js.map +1 -1
  74. package/dist/shadertypes/textures/texture-layout.d.ts +1 -1
  75. package/dist/utils/array-equal.d.ts +1 -1
  76. package/dist/utils/array-equal.d.ts.map +1 -1
  77. package/dist/utils/array-equal.js +15 -9
  78. package/dist/utils/array-equal.js.map +1 -1
  79. package/dist/utils/stats-manager.d.ts.map +1 -1
  80. package/dist/utils/stats-manager.js +61 -1
  81. package/dist/utils/stats-manager.js.map +1 -1
  82. package/package.json +3 -3
  83. package/src/adapter/canvas-context.ts +7 -623
  84. package/src/adapter/canvas-observer.ts +130 -0
  85. package/src/adapter/canvas-surface.ts +521 -0
  86. package/src/adapter/device.ts +174 -13
  87. package/src/adapter/presentation-context.ts +16 -0
  88. package/src/adapter/resources/buffer.ts +13 -5
  89. package/src/adapter/resources/command-encoder.ts +91 -2
  90. package/src/adapter/resources/fence.ts +3 -1
  91. package/src/adapter/resources/query-set.ts +17 -1
  92. package/src/adapter/resources/render-pipeline.ts +42 -13
  93. package/src/adapter/resources/resource.ts +284 -14
  94. package/src/adapter/resources/shared-render-pipeline.ts +40 -0
  95. package/src/adapter/resources/texture.ts +267 -38
  96. package/src/index.ts +7 -0
  97. package/src/shadertypes/data-types/decode-shader-types.ts +13 -4
  98. package/src/shadertypes/textures/texture-format-decoder.ts +71 -6
  99. package/src/shadertypes/textures/texture-format-table.ts +10 -9
  100. package/src/shadertypes/textures/texture-formats.ts +6 -1
  101. package/src/utils/array-equal.ts +21 -9
  102. package/src/utils/stats-manager.ts +76 -2
@@ -1 +1 @@
1
- {"version":3,"file":"stats-manager.js","sourceRoot":"","sources":["../../src/utils/stats-manager.ts"],"names":[],"mappings":"AAAA,UAAU;AACV,+BAA+B;AAC/B,oCAAoC;AA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IAED,MAAM,cAAc,GAAyB,EAAE,CAAC;IAChD,IAAI,mBAAmB,GAAG,2BAA2B,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC5E,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,mBAAmB,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAChD,2BAA2B,CAAC,GAAG,CAAC,gBAAgB,EAAE,mBAAmB,CAAC,CAAC;IACzE,CAAC;IAED,KAAK,MAAM,QAAQ,IAAI,gBAAgB,EAAE,CAAC;QACxC,IAAI,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACvB,cAAc,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAED,KAAK,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxD,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACvC,cAAc,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;QAClC,CAAC;IACH,CAAC;IAED,KAAK,MAAM,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC7C,OAAO,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;IACxC,mBAAmB,CAAC,GAAG,CAAC,KAAK,EAAE,EAAC,gBAAgB,EAAE,SAAS,EAAC,CAAC,CAAC;AAChE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luma.gl/core",
3
- "version": "9.3.0-alpha.4",
3
+ "version": "9.3.0-alpha.6",
4
4
  "description": "The luma.gl core Device API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -44,7 +44,7 @@
44
44
  "@probe.gl/env": "^4.1.1",
45
45
  "@probe.gl/log": "^4.1.1",
46
46
  "@probe.gl/stats": "^4.1.1",
47
- "@types/offscreencanvas": "^2019.6.4"
47
+ "@types/offscreencanvas": "^2019.7.3"
48
48
  },
49
- "gitHead": "7486e7b0377fb6ab961b4499828681bede60f3b1"
49
+ "gitHead": "59fda5480c4d0bb3d64545d4621175221f2b6c7c"
50
50
  }
@@ -2,631 +2,15 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import {isBrowser} from '@probe.gl/env';
6
- import type {Device} from './device';
7
- import type {Framebuffer} from './resources/framebuffer';
8
- import type {TextureFormatDepthStencil} from '../shadertypes/textures/texture-formats';
9
- import {uid} from '../utils/uid';
10
- import {withResolvers} from '../utils/promise-utils';
11
- import {assertDefined} from '../utils/assert';
12
-
13
- /** Properties for a CanvasContext */
14
- export type CanvasContextProps = {
15
- /** Identifier, for debugging */
16
- id?: string;
17
- /** If a canvas not supplied, one will be created and added to the DOM. If a string, a canvas with that id will be looked up in the DOM */
18
- canvas?: HTMLCanvasElement | OffscreenCanvas | string | null;
19
- /** If new canvas is created, it will be created in the specified container, otherwise is appended as a child of document.body */
20
- container?: HTMLElement | string | null;
21
- /** Width in pixels of the canvas - used when creating a new canvas */
22
- width?: number;
23
- /** Height in pixels of the canvas - used when creating a new canvas */
24
- height?: number;
25
- /** Visibility (only used if new canvas is created). */
26
- visible?: boolean;
27
- /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */
28
- useDevicePixels?: boolean | number;
29
- /** Whether to track window resizes. */
30
- autoResize?: boolean;
31
- /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#alphamode */
32
- alphaMode?: 'opaque' | 'premultiplied';
33
- /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#colorspace */
34
- colorSpace?: 'srgb'; // GPUPredefinedColorSpace
35
- /** Whether to track position changes. Calls this.device.onPositionChange */
36
- trackPosition?: boolean;
37
- };
38
-
39
- export type MutableCanvasContextProps = {
40
- /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */
41
- useDevicePixels?: boolean | number;
42
- };
43
-
44
- /**
45
- * Manages a canvas. Supports both HTML or offscreen canvas
46
- * - Creates a new canvas or looks up a canvas from the DOM
47
- * - Provides check for DOM loaded
48
- * @todo commit() @see https://github.com/w3ctag/design-reviews/issues/288
49
- * @todo transferControlToOffscreen: @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen
50
- */
51
- export abstract class CanvasContext {
52
- static isHTMLCanvas(canvas: unknown): canvas is HTMLCanvasElement {
53
- return typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;
54
- }
55
-
56
- static isOffscreenCanvas(canvas: unknown): canvas is OffscreenCanvas {
57
- return typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;
58
- }
59
-
60
- static defaultProps: Required<CanvasContextProps> = {
61
- id: undefined!,
62
- canvas: null,
63
- width: 800,
64
- height: 600,
65
- useDevicePixels: true,
66
- autoResize: true,
67
- container: null,
68
- visible: true,
69
- alphaMode: 'opaque',
70
- colorSpace: 'srgb',
71
- trackPosition: false
72
- };
73
-
74
- abstract readonly device: Device;
75
- abstract readonly handle: unknown;
76
- readonly id: string;
77
-
78
- readonly props: Required<CanvasContextProps>;
79
- readonly canvas: HTMLCanvasElement | OffscreenCanvas;
80
- /** Handle to HTML canvas */
81
- readonly htmlCanvas?: HTMLCanvasElement;
82
- /** Handle to wrapped OffScreenCanvas */
83
- readonly offscreenCanvas?: OffscreenCanvas;
84
- readonly type: 'html-canvas' | 'offscreen-canvas' | 'node';
85
-
86
- /** Promise that resolved once the resize observer has updated the pixel size */
87
- initialized: Promise<void>;
88
- isInitialized: boolean = false;
89
-
90
- /** Visibility is automatically updated (via an IntersectionObserver) */
91
- isVisible: boolean = true;
92
-
93
- /** Width of canvas in CSS units (tracked by a ResizeObserver) */
94
- cssWidth: number;
95
- /** Height of canvas in CSS units (tracked by a ResizeObserver) */
96
- cssHeight: number;
97
-
98
- /** Device pixel ratio. Automatically updated via media queries */
99
- devicePixelRatio: number;
100
- /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */
101
- devicePixelWidth: number;
102
- /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */
103
- devicePixelHeight: number;
104
-
105
- /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */
106
- drawingBufferWidth: number;
107
- /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */
108
- drawingBufferHeight: number;
109
-
110
- /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */
111
- protected _initializedResolvers = withResolvers<void>();
112
- /** ResizeObserver to track canvas size changes */
113
- protected readonly _resizeObserver: ResizeObserver | undefined;
114
- /** IntersectionObserver to track canvas visibility changes */
115
- protected readonly _intersectionObserver: IntersectionObserver | undefined;
116
- private _observeDevicePixelRatioTimeout: ReturnType<typeof setTimeout> | null = null;
117
- /** Position of the canvas in the document, updated by a timer */
118
- protected _position: [number, number] = [0, 0];
119
- /** Whether this canvas context has been destroyed */
120
- protected destroyed = false;
121
- /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */
122
- protected _needsDrawingBufferResize: boolean = true;
123
-
124
- abstract get [Symbol.toStringTag](): string;
125
-
126
- toString(): string {
127
- return `${this[Symbol.toStringTag]}(${this.id})`;
128
- }
129
-
130
- constructor(props?: CanvasContextProps) {
131
- this.props = {...CanvasContext.defaultProps, ...props};
132
- props = this.props;
133
-
134
- this.initialized = this._initializedResolvers.promise;
135
-
136
- // Create a canvas element if needed
137
- if (!isBrowser()) {
138
- // TODO - does this prevent app from using jsdom style polyfills?
139
- this.canvas = {width: props.width || 1, height: props.height || 1} as OffscreenCanvas;
140
- } else if (!props.canvas) {
141
- this.canvas = createCanvasElement(props);
142
- } else if (typeof props.canvas === 'string') {
143
- this.canvas = getCanvasFromDOM(props.canvas);
144
- } else {
145
- this.canvas = props.canvas;
146
- }
147
-
148
- if (CanvasContext.isHTMLCanvas(this.canvas)) {
149
- this.id = props.id || this.canvas.id;
150
- this.type = 'html-canvas';
151
- this.htmlCanvas = this.canvas;
152
- } else if (CanvasContext.isOffscreenCanvas(this.canvas)) {
153
- this.id = props.id || 'offscreen-canvas';
154
- this.type = 'offscreen-canvas';
155
- this.offscreenCanvas = this.canvas;
156
- } else {
157
- // TODO - Node.js support is currently untested (was used for headless-gl in luma v8)
158
- this.id = props.id || 'node-canvas-context';
159
- this.type = 'node';
160
- }
161
-
162
- // Initialize size variables to some sane values (these will be updated by ResizeObserver)
163
- this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width;
164
- this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height;
165
- this.devicePixelWidth = this.canvas.width;
166
- this.devicePixelHeight = this.canvas.height;
167
- this.drawingBufferWidth = this.canvas.width;
168
- this.drawingBufferHeight = this.canvas.height;
169
- this.devicePixelRatio = globalThis.devicePixelRatio || 1;
170
- this._position = [0, 0];
171
-
172
- if (CanvasContext.isHTMLCanvas(this.canvas)) {
173
- // Track visibility changes
174
- this._intersectionObserver = new IntersectionObserver(entries =>
175
- this._handleIntersection(entries)
176
- );
177
- this._intersectionObserver.observe(this.canvas);
178
-
179
- // Track size changes
180
- this._resizeObserver = new ResizeObserver(entries => this._handleResize(entries));
181
- try {
182
- this._resizeObserver.observe(this.canvas, {box: 'device-pixel-content-box'});
183
- } catch {
184
- // Safari fallback
185
- this._resizeObserver.observe(this.canvas, {box: 'content-box'});
186
- }
187
-
188
- // Track device pixel ratio changes.
189
- // Defer call to after construction completes to ensure `this.device` is available.
190
- this._observeDevicePixelRatioTimeout = setTimeout(() => this._observeDevicePixelRatio(), 0);
191
-
192
- // Track top/left position changes
193
- if (this.props.trackPosition) {
194
- this._trackPosition();
195
- }
196
- }
197
- }
198
-
199
- destroy() {
200
- if (!this.destroyed) {
201
- this.destroyed = true;
202
- if (this._observeDevicePixelRatioTimeout) {
203
- clearTimeout(this._observeDevicePixelRatioTimeout);
204
- this._observeDevicePixelRatioTimeout = null;
205
- }
206
- // @ts-expect-error Clear the device to make sure we don't access it after destruction.
207
- this.device = null;
208
- // Disconnect observers to prevent callbacks from firing after destruction
209
- this._resizeObserver?.disconnect();
210
- this._intersectionObserver?.disconnect();
211
- }
212
- }
213
-
214
- setProps(props: MutableCanvasContextProps): this {
215
- if ('useDevicePixels' in props) {
216
- this.props.useDevicePixels = props.useDevicePixels || false;
217
- this._updateDrawingBufferSize();
218
- }
219
- return this;
220
- }
221
-
222
- /** Returns a framebuffer with properly resized current 'swap chain' textures */
223
- getCurrentFramebuffer(options?: {
224
- depthStencilFormat?: TextureFormatDepthStencil | false;
225
- }): Framebuffer {
226
- this._resizeDrawingBufferIfNeeded();
227
- return this._getCurrentFramebuffer(options);
228
- }
229
-
230
- // SIZE METHODS
231
-
232
- /**
233
- * Returns the size covered by the canvas in CSS pixels
234
- * @note This can be different from the actual device pixel size of a canvas due to DPR scaling, and rounding to integer pixels
235
- * @note This is independent of the canvas' internal drawing buffer size (.width, .height).
236
- */
237
- getCSSSize(): [number, number] {
238
- return [this.cssWidth, this.cssHeight];
239
- }
240
-
241
- getPosition() {
242
- return this._position;
243
- }
244
-
245
- /**
246
- * Returns the size covered by the canvas in actual device pixels.
247
- * @note This can be different from the 'CSS' size of a canvas due to DPR scaling, and rounding to integer pixels
248
- * @note This is independent of the canvas' internal drawing buffer size (.width, .height).
249
- */
250
- getDevicePixelSize(): [number, number] {
251
- return [this.devicePixelWidth, this.devicePixelHeight];
252
- }
253
-
254
- /** Get the drawing buffer size (number of pixels GPU is rendering into, can be different from CSS size) */
255
- getDrawingBufferSize(): [number, number] {
256
- return [this.drawingBufferWidth, this.drawingBufferHeight];
257
- }
258
-
259
- /** Returns the biggest allowed framebuffer size. @todo Allow the application to limit this? */
260
- getMaxDrawingBufferSize(): [number, number] {
261
- const maxTextureDimension = this.device.limits.maxTextureDimension2D;
262
- return [maxTextureDimension, maxTextureDimension];
263
- }
264
-
265
- /**
266
- * Update the canvas drawing buffer size.
267
- * @note - Called automatically if props.autoResize is true.
268
- * @note - Defers update of drawing buffer size until framebuffer is requested to avoid flicker
269
- * (resizing clears the drawing buffer)!
270
- */
271
- setDrawingBufferSize(width: number, height: number) {
272
- width = Math.floor(width);
273
- height = Math.floor(height);
274
- if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) {
275
- return;
276
- }
277
- // TODO(ib) - temporarily makes drawingBufferWidth/Height out of sync with canvas.width/height, could that cause issues?
278
- this.drawingBufferWidth = width;
279
- this.drawingBufferHeight = height;
280
- this._needsDrawingBufferResize = true;
281
- }
282
-
283
- /**
284
- * Returns the current DPR (number of physical pixels per CSS pixel), if props.useDevicePixels is true
285
- * @note This can be a fractional (non-integer) number, e.g. when the user zooms in the browser.
286
- * @note This function handles the non-HTML canvas cases
287
- */
288
- getDevicePixelRatio(): number {
289
- const dpr = typeof window !== 'undefined' && window.devicePixelRatio;
290
- return dpr || 1;
291
- }
292
-
293
- // DEPRECATED METHODS
294
-
295
- /**
296
- * Maps CSS pixel position to device pixel position
297
- */
298
- cssToDevicePixels(
299
- cssPixel: [number, number],
300
- yInvert: boolean = true
301
- ): {
302
- x: number;
303
- y: number;
304
- width: number;
305
- height: number;
306
- } {
307
- const ratio = this.cssToDeviceRatio();
308
- const [width, height] = this.getDrawingBufferSize();
309
- return scalePixels(cssPixel, ratio, width, height, yInvert);
310
- }
311
-
312
- /** @deprecated - use .getDevicePixelSize() */
313
- getPixelSize() {
314
- return this.getDevicePixelSize();
315
- }
316
-
317
- /** @deprecated - TODO which values should we use for aspect */
318
- getAspect(): number {
319
- const [width, height] = this.getDevicePixelSize();
320
- return width / height;
321
- }
322
-
323
- /** @deprecated Returns multiplier need to convert CSS size to Device size */
324
- cssToDeviceRatio(): number {
325
- try {
326
- const [drawingBufferWidth] = this.getDrawingBufferSize();
327
- const [cssWidth] = this.getCSSSize();
328
- return cssWidth ? drawingBufferWidth / cssWidth : 1;
329
- } catch {
330
- return 1;
331
- }
332
- }
333
-
334
- /** @deprecated Use canvasContext.setDrawingBufferSize() */
335
- resize(size: {width: number; height: number}): void {
336
- this.setDrawingBufferSize(size.width, size.height);
337
- }
338
-
339
- // SUBCLASS OVERRIDES
340
-
341
- /**
342
- * Performs platform specific updates (WebGPU vs WebGL)
343
- * Can be called after changes to size or props,
344
- * to give implementation an opportunity to update configurations.
345
- */
346
- protected abstract _configureDevice(): void;
347
-
348
- /** Returns a framebuffer with properly resized current 'swap chain' textures */
349
- protected abstract _getCurrentFramebuffer(options?: {
350
- depthStencilFormat?: TextureFormatDepthStencil | false;
351
- }): Framebuffer;
352
-
353
- // IMPLEMENTATION
354
-
355
- /**
356
- * Allows subclass constructor to override the canvas id for auto created canvases.
357
- * This can really help when debugging DOM in apps that create multiple devices
358
- */
359
- protected _setAutoCreatedCanvasId(id: string) {
360
- if (this.htmlCanvas?.id === 'lumagl-auto-created-canvas') {
361
- this.htmlCanvas.id = id;
362
- }
363
- }
364
-
365
- /** reacts to an observed intersection */
366
- protected _handleIntersection(entries: IntersectionObserverEntry[]) {
367
- if (this.destroyed) {
368
- return;
369
- }
370
-
371
- const entry = entries.find(entry_ => entry_.target === this.canvas);
372
- if (!entry) {
373
- return;
374
- }
375
- // TODO - store intersection rectangle?
376
- const isVisible = entry.isIntersecting;
377
- if (this.isVisible !== isVisible) {
378
- this.isVisible = isVisible;
379
- this.device.props.onVisibilityChange(this);
380
- }
381
- }
382
-
383
- /**
384
- * Reacts to an observed resize by using the most accurate pixel size information the browser can provide
385
- * @see https://web.dev/articles/device-pixel-content-box
386
- * @see https://webgpufundamentals.org/webgpu/lessons/webgpu-resizing-the-canvas.html
387
- */
388
- protected _handleResize(entries: ResizeObserverEntry[]) {
389
- if (this.destroyed) {
390
- return;
391
- }
392
-
393
- const entry = entries.find(entry_ => entry_.target === this.canvas);
394
- if (!entry) {
395
- return;
396
- }
397
-
398
- const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]);
399
- // Update CSS size using content box size
400
- this.cssWidth = contentBoxSize.inlineSize;
401
- this.cssHeight = contentBoxSize.blockSize;
402
-
403
- // Update our drawing buffer size variables, saving the old values for logging
404
- const oldPixelSize = this.getDevicePixelSize();
405
-
406
- // Use the most accurate drawing buffer size information the current browser can provide
407
- // Note: content box sizes are guaranteed to be integers
408
- // Note: Safari falls back to contentBoxSize
409
- const devicePixelWidth =
410
- entry.devicePixelContentBoxSize?.[0]?.inlineSize ||
411
- contentBoxSize.inlineSize * devicePixelRatio;
412
-
413
- const devicePixelHeight =
414
- entry.devicePixelContentBoxSize?.[0]?.blockSize ||
415
- contentBoxSize.blockSize * devicePixelRatio;
416
-
417
- // Make sure we don't overflow the maximum supported texture size
418
- const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize();
419
- this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth));
420
- this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight));
421
-
422
- this._updateDrawingBufferSize();
423
-
424
- // Inform the device
425
- this.device.props.onResize(this, {oldPixelSize});
426
- }
427
-
428
- /** Initiate a deferred update for the canvas drawing buffer size */
429
- protected _updateDrawingBufferSize() {
430
- // Update the canvas drawing buffer size
431
- if (this.props.autoResize) {
432
- if (typeof this.props.useDevicePixels === 'number') {
433
- const dpr = this.props.useDevicePixels;
434
- this.setDrawingBufferSize(this.cssWidth * dpr, this.cssHeight * dpr);
435
- } else if (this.props.useDevicePixels) {
436
- this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight);
437
- } else {
438
- this.setDrawingBufferSize(this.cssWidth, this.cssHeight);
439
- }
440
- }
441
-
442
- // Resolve the initialized promise
443
- this._initializedResolvers.resolve();
444
- this.isInitialized = true;
445
-
446
- this.updatePosition();
447
- }
448
-
449
- /** Perform a deferred resize of the drawing buffer if needed */
450
- _resizeDrawingBufferIfNeeded() {
451
- if (this._needsDrawingBufferResize) {
452
- this._needsDrawingBufferResize = false;
453
- const sizeChanged =
454
- this.drawingBufferWidth !== this.canvas.width ||
455
- this.drawingBufferHeight !== this.canvas.height;
456
- if (sizeChanged) {
457
- // Update the canvas size
458
- this.canvas.width = this.drawingBufferWidth;
459
- this.canvas.height = this.drawingBufferHeight;
460
- // Inform the subclass: WebGPU needs to call canvascontext.configure()
461
- this._configureDevice();
462
- }
463
- }
464
- }
465
-
466
- /** Monitor DPR changes */
467
- _observeDevicePixelRatio() {
468
- if (this.destroyed) {
469
- return;
470
- }
471
- const oldRatio = this.devicePixelRatio;
472
- this.devicePixelRatio = window.devicePixelRatio;
473
-
474
- this.updatePosition();
475
-
476
- // Inform the device
477
- this.device.props.onDevicePixelRatioChange?.(this, {oldRatio});
478
- // Set up a one time query against the current resolution.
479
- matchMedia(`(resolution: ${this.devicePixelRatio}dppx)`).addEventListener(
480
- 'change',
481
- () => this._observeDevicePixelRatio(),
482
- {once: true}
483
- );
484
- }
485
-
486
- /** Start tracking positions with a timer */
487
- _trackPosition(intervalMs: number = 100): void {
488
- const intervalId = setInterval(() => {
489
- if (this.destroyed) {
490
- clearInterval(intervalId);
491
- } else {
492
- this.updatePosition();
493
- }
494
- }, intervalMs);
495
- }
496
-
497
- /**
498
- * Calculated the absolute position of the canvas
499
- * @note - getBoundingClientRect() is normally cheap but can be expensive
500
- * if called before browser has finished a reflow. Should not be the case here.
501
- */
502
- updatePosition() {
503
- if (this.destroyed) {
504
- return;
505
- }
506
- const newRect = this.htmlCanvas?.getBoundingClientRect();
507
- if (newRect) {
508
- // We only track position since we rely on the more precise ResizeObserver for size
509
- const position: [number, number] = [newRect.left, newRect.top];
510
- this._position ??= position;
511
- const positionChanged =
512
- position[0] !== this._position[0] || position[1] !== this._position[1];
513
- if (positionChanged) {
514
- const oldPosition = this._position;
515
- this._position = position;
516
- this.device.props.onPositionChange?.(this, {oldPosition});
517
- }
518
- }
519
- }
520
- }
521
-
522
- // HELPER FUNCTIONS
523
-
524
- /** Get a container element from a string or DOM element */
525
- function getContainer(container: HTMLElement | string | null): HTMLElement {
526
- if (typeof container === 'string') {
527
- const element = document.getElementById(container);
528
- if (!element) {
529
- throw new Error(`${container} is not an HTML element`);
530
- }
531
- return element;
532
- }
533
- if (container) {
534
- return container;
535
- }
536
- return document.body;
537
- }
538
-
539
- /** Get a Canvas element from DOM id */
540
- function getCanvasFromDOM(canvasId: string): HTMLCanvasElement {
541
- const canvas = document.getElementById(canvasId);
542
- if (!CanvasContext.isHTMLCanvas(canvas)) {
543
- throw new Error('Object is not a canvas element');
544
- }
545
- return canvas;
546
- }
547
-
548
- /** Create a new canvas */
549
- function createCanvasElement(props: CanvasContextProps) {
550
- const {width, height} = props;
551
- const newCanvas = document.createElement('canvas');
552
- newCanvas.id = uid('lumagl-auto-created-canvas');
553
- newCanvas.width = width || 1;
554
- newCanvas.height = height || 1;
555
- newCanvas.style.width = Number.isFinite(width) ? `${width}px` : '100%';
556
- newCanvas.style.height = Number.isFinite(height) ? `${height}px` : '100%';
557
- if (!props?.visible) {
558
- newCanvas.style.visibility = 'hidden';
559
- }
560
- // Insert the canvas in the DOM
561
- const container = getContainer(props?.container || null);
562
- container.insertBefore(newCanvas, container.firstChild);
563
-
564
- return newCanvas;
565
- }
5
+ export type {CanvasContextProps, MutableCanvasContextProps} from './canvas-surface';
6
+ import {CanvasSurface} from './canvas-surface';
566
7
 
567
8
  /**
568
- * Scales pixels linearly, handles edge cases
569
- * @param pixel
570
- * @param ratio
571
- * @param width
572
- * @param height
573
- * @param yInvert
574
- * @returns
9
+ * Manages a renderable backend canvas. Supports both HTML or offscreen canvas
10
+ * and returns backend framebuffers sourced from the canvas itself.
575
11
  */
576
- function scalePixels(
577
- pixel: [number, number],
578
- ratio: number,
579
- width: number,
580
- height: number,
581
- yInvert: boolean
582
- ): {
583
- x: number;
584
- y: number;
585
- width: number;
586
- height: number;
587
- } {
588
- const point = pixel;
589
-
590
- const x = scaleX(point[0], ratio, width);
591
- let y = scaleY(point[1], ratio, height, yInvert);
592
-
593
- // Find boundaries of next pixel to provide valid range of device pixel locations
594
-
595
- let t = scaleX(point[0] + 1, ratio, width);
596
- // If next pixel's position is clamped to boundary, use it as is, otherwise subtract 1 for current pixel boundary
597
- const xHigh = t === width - 1 ? t : t - 1;
598
-
599
- t = scaleY(point[1] + 1, ratio, height, yInvert);
600
- let yHigh;
601
- if (yInvert) {
602
- // If next pixel's position is clamped to boundary, use it as is, otherwise clamp it to valid range
603
- t = t === 0 ? t : t + 1;
604
- // swap y and yHigh
605
- yHigh = y;
606
- y = t;
607
- } else {
608
- // If next pixel's position is clamped to boundary, use it as is, otherwise clamp it to valid range
609
- yHigh = t === height - 1 ? t : t - 1;
610
- // y remains same
611
- }
612
- return {
613
- x,
614
- y,
615
- // when ratio < 1, current css pixel and next css pixel may point to same device pixel, set width/height to 1 in those cases.
616
- width: Math.max(xHigh - x + 1, 1),
617
- height: Math.max(yHigh - y + 1, 1)
618
- };
619
- }
620
-
621
- function scaleX(x: number, ratio: number, width: number): number {
622
- // since we are rounding to nearest, when ratio > 1, edge pixels may point to out of bounds value, clamp to the limit
623
- const r = Math.min(Math.round(x * ratio), width - 1);
624
- return r;
625
- }
12
+ export abstract class CanvasContext extends CanvasSurface {
13
+ static override defaultProps = CanvasSurface.defaultProps;
626
14
 
627
- function scaleY(y: number, ratio: number, height: number, yInvert: boolean): number {
628
- // since we are rounding to nearest, when ratio > 1, edge pixels may point to out of bounds value, clamp to the limit
629
- return yInvert
630
- ? Math.max(0, height - 1 - Math.round(y * ratio))
631
- : Math.min(Math.round(y * ratio), height - 1);
15
+ abstract override readonly handle: unknown;
632
16
  }