@crysound/crychart 1.0.6 → 1.0.7

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.
package/README.md CHANGED
@@ -6,12 +6,12 @@ CRYChart is a **frontend rendering library built by CRYSOUND for OpenTest**, wri
6
6
 
7
7
  Designed for OpenTest's data visualization needs, CRYChart provides streaming data rendering, interactive axes, cursors, and 2D and 3D charts. It uses WebGL2 for rendering, with a Canvas fallback.
8
8
 
9
- Version `1.0.6` reduces 3D mesh and wireframe allocations by reusing unchanged topology while preserving sample values and ordered geometry.
9
+ Version `1.0.7` adds an opt-in `SharedWebGLContext` mode so multiple 2D charts (`ChartXY` and `Polar`) share a single WebGL2 context without hitting browser WebGL context limits, while keeping the default per-chart mode unchanged.
10
10
 
11
11
  ## Install in an application
12
12
 
13
13
  ```powershell
14
- pnpm add --save-exact @crysound/crychart@1.0.6 --registry=https://registry.npmjs.org/
14
+ pnpm add --save-exact @crysound/crychart@1.0.7 --registry=https://registry.npmjs.org/
15
15
  ```
16
16
 
17
17
  Commit the application's lockfile and use `pnpm install --frozen-lockfile` for repeatable installs. See the [npm usage guide](docs/npm-usage.md) for package entry points and migration from the old `crychart` name.
@@ -49,6 +49,28 @@ line.appendSamples({ y: new Float32Array([1, 2, 3]) }, { start: 0, step: 0.001 }
49
49
  context.dispose()
50
50
  ```
51
51
 
52
+ ### Shared WebGL2 context (opt-in for many 2D charts)
53
+
54
+ When rendering many `ChartXY` / `Polar` instances on one page, create a page-level `SharedWebGLContext` singleton and pass it to `cryChart({ sharedContext })`:
55
+
56
+ ```ts
57
+ import { cryChart, SharedWebGLContext } from '@crysound/crychart'
58
+
59
+ let shared: SharedWebGLContext | undefined
60
+ export function getAppSharedWebGLContext() {
61
+ return shared && !shared.isDisposed()
62
+ ? shared
63
+ : (shared = new SharedWebGLContext({ cullOffscreen: true }))
64
+ }
65
+
66
+ const context = cryChart({ sharedContext: getAppSharedWebGLContext() })
67
+ const chart = context.ChartXY({ container: document.getElementById('chart')! })
68
+ // Dispose charts/contexts before disposing an externally created SharedWebGLContext.
69
+ context.dispose()
70
+ ```
71
+
72
+ Notes: `SharedWebGLContext` applies to `ChartXY` and `Polar` only (`Chart3D` keeps its own WebGL2 context and throws `UnsupportedFeatureError` if passed `sharedContext` explicitly); `chart.canvas` uses a 2D presentation context in shared mode; MSAA is controlled by `SharedContextOptions.antialias`; offscreen charts pause scheduled redraws/animations until visible again. See [CHANGELOG.md](CHANGELOG.md) for full details.
73
+
52
74
  The package provides ES modules, CommonJS, a browser script, and TypeScript declarations. The browser script exposes the `CRYChart` global. Themes are available through `@crysound/crychart/themes`.
53
75
 
54
76
  ## Validation
package/README.zh-CN.md CHANGED
@@ -6,12 +6,12 @@ CRYChart 是 **CRYSOUND 为 OpenTest 定制的前端渲染库**,基于 TypeScr
6
6
 
7
7
  CRYChart 面向 OpenTest 的数据可视化场景,提供流式数据绘制、交互坐标轴、游标、二维和三维图表。绘图使用 WebGL2,并提供 Canvas 回退。
8
8
 
9
- `1.0.6` 通过复用未变化的拓扑,减少三维网格和线框绘制的内存分配,保留原始采样值及几何遍历顺序。
9
+ `1.0.7` 新增可选的共享 WebGL2 上下文模式(`SharedWebGLContext`),允许同一页面的多张二维图表(`ChartXY` / `Polar`)共用单个 WebGL2 上下文以突破浏览器上下文数量限制,默认独立上下文行为保持不变。
10
10
 
11
11
  ## 在应用中安装
12
12
 
13
13
  ```powershell
14
- pnpm add --save-exact @crysound/crychart@1.0.6 --registry=https://registry.npmjs.org/
14
+ pnpm add --save-exact @crysound/crychart@1.0.7 --registry=https://registry.npmjs.org/
15
15
  ```
16
16
 
17
17
  提交应用的锁文件,后续执行 `pnpm install --frozen-lockfile`。包入口和旧 `crychart` 包名的迁移方式见 [npm 使用说明](docs/npm-usage.md)。
@@ -47,6 +47,28 @@ line.appendSamples({ y: new Float32Array([1, 2, 3]) }, { start: 0, step: 0.001 }
47
47
  context.dispose()
48
48
  ```
49
49
 
50
+ ### 共享 WebGL2 上下文(多张二维图可选启用)
51
+
52
+ 同屏渲染大量 `ChartXY` / `Polar` 图表时,可维护页面级 `SharedWebGLContext` 单例并传给 `cryChart({ sharedContext })`:
53
+
54
+ ```ts
55
+ import { cryChart, SharedWebGLContext } from '@crysound/crychart'
56
+
57
+ let shared: SharedWebGLContext | undefined
58
+ export function getAppSharedWebGLContext() {
59
+ return shared && !shared.isDisposed()
60
+ ? shared
61
+ : (shared = new SharedWebGLContext({ cullOffscreen: true }))
62
+ }
63
+
64
+ const context = cryChart({ sharedContext: getAppSharedWebGLContext() })
65
+ const chart = context.ChartXY({ container: document.getElementById('chart')! })
66
+ // 请先销毁图表/上下文,再销毁外部创建的 SharedWebGLContext。
67
+ context.dispose()
68
+ ```
69
+
70
+ 说明:仅支持 `ChartXY` 和 `Polar`(`Chart3D` 保持独立上下文,显式传入 `sharedContext` 会抛出 `UnsupportedFeatureError`);共享模式下 `chart.canvas` 为 2D 展示画布;抗锯齿由共享上下文的 `antialias` 控制;离屏图表会暂停排帧及动画,回到视口后自动恢复。完整说明见 [CHANGELOG.md](CHANGELOG.md)。
71
+
50
72
  包提供 ES 模块、CommonJS、浏览器脚本和 TypeScript 类型声明。浏览器脚本的全局对象为 `CRYChart`。主题入口为 `@crysound/crychart/themes`。
51
73
 
52
74
  ## 验证
package/dist/crychart.cjs CHANGED
@@ -104,6 +104,7 @@ __export(index_exports, {
104
104
  SegmentFigure: () => SegmentFigure,
105
105
  SegmentSeries: () => SegmentSeries,
106
106
  Series3DBase: () => Series3DBase,
107
+ SharedWebGLContext: () => SharedWebGLContext,
107
108
  SimpleShadingStyle: () => SimpleShadingStyle,
108
109
  SlicedHierarchyChart: () => SlicedHierarchyChart,
109
110
  SolidFill: () => SolidFill,
@@ -16393,6 +16394,294 @@ var LineStripRenderer = class {
16393
16394
  }
16394
16395
  };
16395
16396
 
16397
+ // src/shared-webgl-context.ts
16398
+ var cores = /* @__PURE__ */ new WeakMap();
16399
+ var claimedCanvases = /* @__PURE__ */ new WeakMap();
16400
+ function sharedContextCore(context) {
16401
+ const core = cores.get(context);
16402
+ if (!core) throw new TypeError("Expected a valid SharedWebGLContext");
16403
+ return core;
16404
+ }
16405
+ function resetSharedBaseline(gl, width, height, maxVertexAttribs) {
16406
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
16407
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
16408
+ gl.drawBuffers([gl.BACK]);
16409
+ gl.readBuffer(gl.BACK);
16410
+ gl.bindVertexArray(null);
16411
+ for (let i = 0; i < maxVertexAttribs; i++) {
16412
+ gl.disableVertexAttribArray(i);
16413
+ gl.vertexAttribDivisor(i, 0);
16414
+ }
16415
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
16416
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
16417
+ gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, null);
16418
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
16419
+ gl.bindBuffer(gl.COPY_READ_BUFFER, null);
16420
+ gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
16421
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
16422
+ gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
16423
+ for (let unit = 2; unit >= 0; unit--) {
16424
+ gl.activeTexture(gl.TEXTURE0 + unit);
16425
+ gl.bindTexture(gl.TEXTURE_2D, null);
16426
+ gl.bindSampler(unit, null);
16427
+ }
16428
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
16429
+ gl.pixelStorei(gl.PACK_ALIGNMENT, 4);
16430
+ gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
16431
+ gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
16432
+ gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
16433
+ gl.pixelStorei(gl.UNPACK_IMAGE_HEIGHT, 0);
16434
+ gl.pixelStorei(gl.UNPACK_SKIP_IMAGES, 0);
16435
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
16436
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
16437
+ gl.useProgram(null);
16438
+ gl.colorMask(true, true, true, true);
16439
+ gl.depthMask(true);
16440
+ gl.stencilMask(255);
16441
+ for (const capability of [
16442
+ gl.DEPTH_TEST,
16443
+ gl.STENCIL_TEST,
16444
+ gl.CULL_FACE,
16445
+ gl.RASTERIZER_DISCARD,
16446
+ gl.SAMPLE_ALPHA_TO_COVERAGE,
16447
+ gl.SAMPLE_COVERAGE,
16448
+ gl.SCISSOR_TEST,
16449
+ gl.POLYGON_OFFSET_FILL
16450
+ ]) {
16451
+ gl.disable(capability);
16452
+ }
16453
+ gl.enable(gl.BLEND);
16454
+ gl.enable(gl.DITHER);
16455
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
16456
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
16457
+ gl.viewport(0, 0, width, height);
16458
+ gl.scissor(0, 0, width, height);
16459
+ }
16460
+ var SharedContextCore = class {
16461
+ canvas;
16462
+ cullOffscreen;
16463
+ antialias;
16464
+ ownsCanvas;
16465
+ clients = /* @__PURE__ */ new Set();
16466
+ observer;
16467
+ observedRoots = /* @__PURE__ */ new Map();
16468
+ offscreenClients = /* @__PURE__ */ new Set();
16469
+ gl = null;
16470
+ attempted = false;
16471
+ disposed = false;
16472
+ maxVertexAttribs = 0;
16473
+ pendingPresent;
16474
+ chartDraws = 0;
16475
+ blits = 0;
16476
+ backingResizes = 0;
16477
+ contextLosses = 0;
16478
+ contextRestores = 0;
16479
+ onLost = (event) => {
16480
+ event.preventDefault();
16481
+ this.contextLosses++;
16482
+ };
16483
+ onRestore = () => {
16484
+ this.contextRestores++;
16485
+ };
16486
+ constructor(options) {
16487
+ if (options !== void 0 && (typeof options !== "object" || options === null)) {
16488
+ throw new TypeError("SharedWebGLContext options must be an object");
16489
+ }
16490
+ if (options?.canvas !== void 0) {
16491
+ if (typeof options.canvas !== "object" || options.canvas === null || typeof options.canvas.getContext !== "function") {
16492
+ throw new TypeError("SharedWebGLContext canvas must provide getContext");
16493
+ }
16494
+ if (claimedCanvases.has(options.canvas)) {
16495
+ throw new Error("Canvas is already bound to an active SharedWebGLContext");
16496
+ }
16497
+ this.canvas = options.canvas;
16498
+ this.ownsCanvas = false;
16499
+ claimedCanvases.set(options.canvas, this);
16500
+ } else if (typeof document !== "undefined") {
16501
+ this.canvas = document.createElement("canvas");
16502
+ this.ownsCanvas = true;
16503
+ } else {
16504
+ this.canvas = void 0;
16505
+ this.ownsCanvas = false;
16506
+ }
16507
+ this.antialias = options?.antialias === true;
16508
+ this.cullOffscreen = options?.cullOffscreen !== false;
16509
+ }
16510
+ acquire() {
16511
+ if (this.disposed) return null;
16512
+ if (this.attempted) return this.gl;
16513
+ this.attempted = true;
16514
+ if (!this.canvas) return null;
16515
+ let gl = null;
16516
+ try {
16517
+ gl = this.canvas.getContext("webgl2", {
16518
+ alpha: true,
16519
+ antialias: this.antialias,
16520
+ depth: false,
16521
+ stencil: false,
16522
+ premultipliedAlpha: true,
16523
+ preserveDrawingBuffer: false
16524
+ });
16525
+ } catch {
16526
+ gl = null;
16527
+ }
16528
+ if (gl) {
16529
+ this.gl = gl;
16530
+ const maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
16531
+ this.maxVertexAttribs = typeof maxAttribs === "number" && maxAttribs > 0 ? maxAttribs : 0;
16532
+ this.canvas.addEventListener("webglcontextlost", this.onLost);
16533
+ this.canvas.addEventListener("webglcontextrestored", this.onRestore);
16534
+ }
16535
+ return this.gl;
16536
+ }
16537
+ isAvailable() {
16538
+ const gl = this.acquire();
16539
+ return gl !== null && !this.disposed && !gl.isContextLost();
16540
+ }
16541
+ isDisposed() {
16542
+ return this.disposed;
16543
+ }
16544
+ getChartCount() {
16545
+ return this.clients.size;
16546
+ }
16547
+ getStats() {
16548
+ const active2 = this.gl !== null && !this.disposed;
16549
+ return {
16550
+ available: active2 && !this.gl.isContextLost(),
16551
+ disposed: this.disposed,
16552
+ registeredCharts: this.clients.size,
16553
+ offscreenCharts: this.offscreenClients.size,
16554
+ backingWidth: active2 && this.canvas ? this.canvas.width : 0,
16555
+ backingHeight: active2 && this.canvas ? this.canvas.height : 0,
16556
+ chartDraws: this.chartDraws,
16557
+ blits: this.blits,
16558
+ backingResizes: this.backingResizes,
16559
+ contextLosses: this.contextLosses,
16560
+ contextRestores: this.contextRestores
16561
+ };
16562
+ }
16563
+ register(client) {
16564
+ if (this.disposed) throw new Error("SharedWebGLContext has been disposed");
16565
+ if (this.clients.has(client)) return;
16566
+ this.clients.add(client);
16567
+ if (this.cullOffscreen && typeof IntersectionObserver === "function") {
16568
+ if (!this.observer) {
16569
+ this.observer = new IntersectionObserver(
16570
+ (entries) => {
16571
+ for (const entry of entries) {
16572
+ const targetClient = this.observedRoots.get(entry.target);
16573
+ if (!targetClient) continue;
16574
+ const offscreen = !entry.isIntersecting;
16575
+ if (offscreen) this.offscreenClients.add(targetClient);
16576
+ else this.offscreenClients.delete(targetClient);
16577
+ targetClient.setOffscreen?.(offscreen);
16578
+ }
16579
+ },
16580
+ { threshold: 0 }
16581
+ );
16582
+ }
16583
+ this.observedRoots.set(client.root, client);
16584
+ this.observer.observe(client.root);
16585
+ }
16586
+ }
16587
+ unregister(client) {
16588
+ this.clients.delete(client);
16589
+ this.offscreenClients.delete(client);
16590
+ if (this.observedRoots.delete(client.root)) {
16591
+ this.observer?.unobserve(client.root);
16592
+ }
16593
+ }
16594
+ beginChartDraw(pixelWidth, pixelHeight) {
16595
+ this.pendingPresent = void 0;
16596
+ const gl = this.acquire();
16597
+ if (!gl || this.disposed || gl.isContextLost()) return false;
16598
+ const canvas = this.canvas;
16599
+ const width = Math.max(1, Math.round(pixelWidth));
16600
+ const height = Math.max(1, Math.round(pixelHeight));
16601
+ let resized = false;
16602
+ if (canvas.width !== width) {
16603
+ canvas.width = width;
16604
+ resized = true;
16605
+ }
16606
+ if (canvas.height !== height) {
16607
+ canvas.height = height;
16608
+ resized = true;
16609
+ }
16610
+ if (resized) this.backingResizes++;
16611
+ resetSharedBaseline(gl, width, height, this.maxVertexAttribs);
16612
+ gl.disable(gl.SCISSOR_TEST);
16613
+ gl.clearColor(0, 0, 0, 0);
16614
+ gl.clear(gl.COLOR_BUFFER_BIT);
16615
+ this.pendingPresent = { width, height };
16616
+ this.chartDraws++;
16617
+ return true;
16618
+ }
16619
+ present(target, pixelWidth, pixelHeight) {
16620
+ const pending = this.pendingPresent;
16621
+ this.pendingPresent = void 0;
16622
+ const width = Math.max(1, Math.round(pixelWidth));
16623
+ const height = Math.max(1, Math.round(pixelHeight));
16624
+ if (!pending || !target || !this.canvas || pending.width !== width || pending.height !== height) {
16625
+ return;
16626
+ }
16627
+ target.save();
16628
+ target.setTransform(1, 0, 0, 1, 0, 0);
16629
+ target.globalAlpha = 1;
16630
+ target.globalCompositeOperation = "copy";
16631
+ target.imageSmoothingEnabled = false;
16632
+ target.drawImage(this.canvas, 0, 0);
16633
+ target.restore();
16634
+ this.blits++;
16635
+ }
16636
+ dispose() {
16637
+ if (this.disposed) return;
16638
+ this.disposed = true;
16639
+ this.pendingPresent = void 0;
16640
+ this.observer?.disconnect();
16641
+ this.observer = void 0;
16642
+ this.observedRoots.clear();
16643
+ this.offscreenClients.clear();
16644
+ this.clients.clear();
16645
+ if (this.canvas) {
16646
+ if (this.gl) {
16647
+ this.canvas.removeEventListener("webglcontextlost", this.onLost);
16648
+ this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
16649
+ }
16650
+ if (this.ownsCanvas) {
16651
+ this.gl?.getExtension("WEBGL_lose_context")?.loseContext();
16652
+ this.canvas.width = 1;
16653
+ this.canvas.height = 1;
16654
+ } else {
16655
+ claimedCanvases.delete(this.canvas);
16656
+ }
16657
+ }
16658
+ this.gl = null;
16659
+ }
16660
+ };
16661
+ var SharedWebGLContext = class {
16662
+ constructor(options) {
16663
+ cores.set(this, new SharedContextCore(options));
16664
+ }
16665
+ /** Lazily acquires the shared WebGL2 context on first call and caches the result without retrying. */
16666
+ isAvailable() {
16667
+ return sharedContextCore(this).isAvailable();
16668
+ }
16669
+ isDisposed() {
16670
+ return sharedContextCore(this).isDisposed();
16671
+ }
16672
+ /** Number of charts currently registered with this shared context. */
16673
+ getChartCount() {
16674
+ return sharedContextCore(this).getChartCount();
16675
+ }
16676
+ getStats() {
16677
+ return sharedContextCore(this).getStats();
16678
+ }
16679
+ /** Idempotently disposes the shared context. Dispose all registered charts first. */
16680
+ dispose() {
16681
+ sharedContextCore(this).dispose();
16682
+ }
16683
+ };
16684
+
16396
16685
  // src/render.ts
16397
16686
  var iconVertex = `#version 300 es
16398
16687
  precision highp float;
@@ -16538,7 +16827,15 @@ var DataRenderer = class {
16538
16827
  this.ownedCoverageFrame = options.ownedCoverageFrame === true;
16539
16828
  this.gpuClipPolicy = options.gpuClipPolicy ?? "legacy";
16540
16829
  let gl = null;
16541
- try {
16830
+ let contextEvents = canvas;
16831
+ if (options.renderer !== "canvas2d" && options.sharedContext) {
16832
+ const core = sharedContextCore(options.sharedContext);
16833
+ gl = core.acquire();
16834
+ if (gl && core.canvas) {
16835
+ this.sharedContext = options.sharedContext;
16836
+ contextEvents = core.canvas;
16837
+ }
16838
+ } else try {
16542
16839
  if (options.renderer !== "canvas2d") gl = canvas.getContext("webgl2", {
16543
16840
  alpha: true,
16544
16841
  antialias: options.antialias ?? false,
@@ -16549,11 +16846,12 @@ var DataRenderer = class {
16549
16846
  }
16550
16847
  if (options.renderer === "webgl2" && !gl) throw new Error("CRYChart WebGL2 renderer is unavailable");
16551
16848
  this.gl = gl;
16849
+ this.contextEvents = contextEvents;
16552
16850
  this.backend = gl ? "webgl2" : "canvas2d";
16553
16851
  if (gl) {
16554
16852
  this.init(gl);
16555
- canvas.addEventListener("webglcontextlost", this.onLost);
16556
- canvas.addEventListener("webglcontextrestored", this.onRestore);
16853
+ this.contextEvents.addEventListener("webglcontextlost", this.onLost);
16854
+ this.contextEvents.addEventListener("webglcontextrestored", this.onRestore);
16557
16855
  } else
16558
16856
  try {
16559
16857
  this.ctx = canvas.getContext("2d");
@@ -16585,6 +16883,8 @@ var DataRenderer = class {
16585
16883
  lost = false;
16586
16884
  iconPipeline;
16587
16885
  iconTextures = /* @__PURE__ */ new Map();
16886
+ sharedContext;
16887
+ contextEvents;
16588
16888
  stats = {
16589
16889
  frames: 0,
16590
16890
  uploads: 0,
@@ -17309,8 +17609,8 @@ var DataRenderer = class {
17309
17609
  this.attributeBuffers.clear();
17310
17610
  if (this.program) this.gl.deleteProgram(this.program);
17311
17611
  }
17312
- this.canvas.removeEventListener("webglcontextlost", this.onLost);
17313
- this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
17612
+ this.contextEvents.removeEventListener("webglcontextlost", this.onLost);
17613
+ this.contextEvents.removeEventListener("webglcontextrestored", this.onRestore);
17314
17614
  }
17315
17615
  };
17316
17616
  function appendPointPath(ctx, x, y, size, shape, rotation) {
@@ -18188,8 +18488,9 @@ var DataRendererHeatmap = class {
18188
18488
  this.canvas = canvas;
18189
18489
  this.options = options;
18190
18490
  this.initialize();
18191
- canvas.addEventListener("webglcontextlost", this.contextLost);
18192
- canvas.addEventListener("webglcontextrestored", this.contextRestored);
18491
+ const events = this.options.contextEvents ?? this.canvas;
18492
+ events.addEventListener("webglcontextlost", this.contextLost);
18493
+ events.addEventListener("webglcontextrestored", this.contextRestored);
18193
18494
  }
18194
18495
  stats = { frames: 0, uploads: 0, textureUploads: 0, paletteUploads: 0, uploadedBytes: 0, drawCalls: 0, cells: 0, renderTimeMs: 0, cachedTextures: 0, cacheBytes: 0, contextRestores: 0 };
18195
18496
  entries = /* @__PURE__ */ new Map();
@@ -18480,8 +18781,9 @@ var DataRendererHeatmap = class {
18480
18781
  this.program = void 0;
18481
18782
  this.stats.cachedTextures = 0;
18482
18783
  this.stats.cacheBytes = 0;
18483
- this.canvas.removeEventListener("webglcontextlost", this.contextLost);
18484
- this.canvas.removeEventListener("webglcontextrestored", this.contextRestored);
18784
+ const events = this.options.contextEvents ?? this.canvas;
18785
+ events.removeEventListener("webglcontextlost", this.contextLost);
18786
+ events.removeEventListener("webglcontextrestored", this.contextRestored);
18485
18787
  }
18486
18788
  };
18487
18789
 
@@ -20791,6 +21093,11 @@ var ChartXY = class {
20791
21093
  observer;
20792
21094
  overlayContext;
20793
21095
  underlayContext;
21096
+ sharedCore;
21097
+ sharedPresent = null;
21098
+ sharedClient;
21099
+ sharedOffscreen = false;
21100
+ sharedDeferred = false;
20794
21101
  heatmapRenderer;
20795
21102
  heatmapPalettes = /* @__PURE__ */ new Map();
20796
21103
  heatCache = /* @__PURE__ */ new Map();
@@ -20877,7 +21184,7 @@ var ChartXY = class {
20877
21184
  this.underlay = underlay;
20878
21185
  this.overlay = overlay;
20879
21186
  try {
20880
- this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy });
21187
+ this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy, sharedContext: options.sharedContext ?? void 0 });
20881
21188
  } catch (error) {
20882
21189
  this.cssTextFonts?.dispose();
20883
21190
  root.remove();
@@ -20897,6 +21204,18 @@ var ChartXY = class {
20897
21204
  });
20898
21205
  this.observer.observe(container);
20899
21206
  }
21207
+ if (this.renderer?.sharedContext) {
21208
+ const sharedCore = sharedContextCore(this.renderer.sharedContext);
21209
+ this.sharedCore = sharedCore;
21210
+ this.sharedPresent = data.getContext("2d");
21211
+ const client = {
21212
+ root,
21213
+ setOffscreen: (offscreen) => this.setSharedOffscreen(offscreen)
21214
+ };
21215
+ this.sharedClient = client;
21216
+ sharedCore.register(client);
21217
+ this.cleanups.push(() => sharedCore.unregister(client));
21218
+ }
20900
21219
  }
20901
21220
  this.engine = {
20902
21221
  container: this.root ?? this.container,
@@ -21642,8 +21961,26 @@ var ChartXY = class {
21642
21961
  this.cancelAxisScrollAnimations();
21643
21962
  for (const series of this.series) series.cancelHighlightAnimation?.();
21644
21963
  }
21964
+ setSharedOffscreen(offscreen) {
21965
+ if (offscreen === this.sharedOffscreen || this.disposed) return;
21966
+ this.sharedOffscreen = offscreen;
21967
+ if (offscreen) {
21968
+ if (this.frame && typeof cancelAnimationFrame === "function") {
21969
+ cancelAnimationFrame(this.frame);
21970
+ this.frame = 0;
21971
+ this.sharedDeferred = true;
21972
+ }
21973
+ } else if (this.sharedDeferred) {
21974
+ this.sharedDeferred = false;
21975
+ this.invalidate();
21976
+ }
21977
+ }
21645
21978
  invalidate() {
21646
21979
  if (this.disposed || this.frame || this.rendering || !this.root) return;
21980
+ if (this.sharedOffscreen) {
21981
+ this.sharedDeferred = true;
21982
+ return;
21983
+ }
21647
21984
  if (typeof requestAnimationFrame === "function")
21648
21985
  this.frame = requestAnimationFrame((timestamp) => {
21649
21986
  this.frame = 0;
@@ -22097,6 +22434,8 @@ var ChartXY = class {
22097
22434
  ctx.drawImage(cache.canvas, r.left, r.top, r.width, r.height);
22098
22435
  }
22099
22436
  renderData(packets) {
22437
+ const shared = this.sharedCore;
22438
+ if (shared && !shared.beginChartDraw(this.canvas.width, this.canvas.height)) return;
22100
22439
  const grids = [];
22101
22440
  for (const s of this.series) {
22102
22441
  if (!(s instanceof HeatmapSeries) || !s.visible || s.disposed || !this.gpuHeatmap(s))
@@ -22167,7 +22506,7 @@ var ChartXY = class {
22167
22506
  this.heatmapRenderer = new DataRendererHeatmap(
22168
22507
  this.renderer.gl,
22169
22508
  this.canvas,
22170
- { clipPolicy: this.gpuClipPolicy }
22509
+ { clipPolicy: this.gpuClipPolicy, contextEvents: this.renderer.contextEvents }
22171
22510
  );
22172
22511
  const gl = this.renderer?.gl;
22173
22512
  const rasterTarget = this.gpuClipPolicy === "contained" && gl ? rasterTargetForRect(null, gl.drawingBufferWidth, gl.drawingBufferHeight, this.plot, this.dpr) : void 0;
@@ -22184,6 +22523,7 @@ var ChartXY = class {
22184
22523
  clear: grids.length === 0,
22185
22524
  rasterTarget
22186
22525
  });
22526
+ if (shared) shared.present(this.sharedPresent, this.canvas.width, this.canvas.height);
22187
22527
  }
22188
22528
  gpuHeatmap(s) {
22189
22529
  return !!this.renderer?.gl && s.axisX.type !== "logarithmic" && s.axisY.type !== "logarithmic";
@@ -23443,7 +23783,8 @@ var Chart3D = class extends ChartXY {
23443
23783
  gpuPackets = /* @__PURE__ */ new Map();
23444
23784
  gpuRevision = 0;
23445
23785
  constructor(options = {}) {
23446
- super({ ...options, antialias: options.antialias ?? true });
23786
+ if (options.sharedContext) throw new UnsupportedFeatureError("shared WebGL contexts for Chart3D");
23787
+ super({ ...options, sharedContext: null, antialias: options.antialias ?? true });
23447
23788
  this.cameraModel = options.experimental3DCameraModel === "legacy" ? "legacy" : "world";
23448
23789
  this.axesZ.push(new Axis(this, "z", options.defaultAxisZ));
23449
23790
  this.coordsAxis.z = this.axesZ[0];
@@ -25018,7 +25359,8 @@ function createCRYChartAdapter(container, options = {}) {
25018
25359
  const chart = new ChartXY({
25019
25360
  container,
25020
25361
  legend: { visible: false },
25021
- ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {}
25362
+ ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {},
25363
+ ...options.sharedContext ? { sharedContext: options.sharedContext } : {}
25022
25364
  });
25023
25365
  const entries = /* @__PURE__ */ new Map();
25024
25366
  let disposed = false;
@@ -25194,12 +25536,27 @@ function createCRYChartAdapter(container, options = {}) {
25194
25536
  }
25195
25537
 
25196
25538
  // src/index.ts
25197
- function cryChart(_options = {}) {
25539
+ function cryChart(options = {}) {
25540
+ if (options.sharedContext !== void 0 && options.sharedContextOptions !== void 0) {
25541
+ throw new TypeError(
25542
+ "Pass either sharedContext or sharedContextOptions, not both"
25543
+ );
25544
+ }
25545
+ if (options.sharedContext !== void 0 && !(options.sharedContext instanceof SharedWebGLContext)) {
25546
+ throw new TypeError("sharedContext must be a SharedWebGLContext");
25547
+ }
25548
+ if (options.sharedContext?.isDisposed()) {
25549
+ throw new Error("sharedContext has been disposed");
25550
+ }
25551
+ const shared = options.sharedContext ?? (options.sharedContextOptions ? new SharedWebGLContext(options.sharedContextOptions) : void 0);
25552
+ const ownsShared = !options.sharedContext && shared !== void 0;
25198
25553
  const owned2 = /* @__PURE__ */ new Set();
25199
25554
  let disposed = false;
25200
- const create = (ctor, options = {}) => {
25555
+ const create = (ctor, opts = {}) => {
25201
25556
  if (disposed) throw new Error("Chart context has been disposed");
25202
- const chart = new ctor(options);
25557
+ const injects = shared !== void 0 && (ctor === ChartXY || ctor === Polar || ctor === Dashboard) && !("sharedContext" in opts);
25558
+ const finalOptions = injects ? { ...opts, sharedContext: shared } : opts;
25559
+ const chart = new ctor(finalOptions);
25203
25560
  owned2.add(chart);
25204
25561
  chart.onDispose(() => owned2.delete(chart));
25205
25562
  return chart;
@@ -25230,17 +25587,25 @@ function cryChart(_options = {}) {
25230
25587
  } catch (error) {
25231
25588
  errors.push(error);
25232
25589
  }
25590
+ if (ownsShared) try {
25591
+ shared.dispose();
25592
+ } catch (error) {
25593
+ errors.push(error);
25594
+ }
25233
25595
  if (errors.length) throw new AggregateError(errors, "Some chart disposal callbacks failed");
25234
25596
  }
25235
25597
  },
25236
25598
  isDisposed: () => disposed,
25237
25599
  /** Live charts owned by this context; disposed charts are released immediately. */
25238
- getChartCount: () => owned2.size
25600
+ getChartCount: () => owned2.size,
25601
+ /** Shared WebGL2 context used by this context; undefined when not enabled. */
25602
+ getSharedContext: () => shared
25239
25603
  };
25240
25604
  }
25241
- var version = "1.0.6";
25605
+ var version = "1.0.7";
25242
25606
  var Dashboard = class {
25243
25607
  root;
25608
+ sharedContext;
25244
25609
  cells = /* @__PURE__ */ new Map();
25245
25610
  children = /* @__PURE__ */ new Set();
25246
25611
  events = new EventHub();
@@ -25252,6 +25617,7 @@ var Dashboard = class {
25252
25617
  throw new Error("Dashboard requires a DOM");
25253
25618
  const container = typeof options.container === "string" ? document.getElementById(options.container) : options.container ?? document.body;
25254
25619
  if (!container) throw new Error("Dashboard container was not found");
25620
+ this.sharedContext = options.sharedContext;
25255
25621
  this.root = document.createElement("div");
25256
25622
  this.columns = options.numberOfColumns ?? 2;
25257
25623
  this.rows = options.numberOfRows ?? 2;
@@ -25264,8 +25630,13 @@ var Dashboard = class {
25264
25630
  cell.style.cssText = `min-height:0;min-width:0;grid-column:${(options.columnIndex ?? 0) + 1}/span ${options.columnSpan ?? 1};grid-row:${(options.rowIndex ?? 0) + 1}/span ${options.rowSpan ?? 1}`;
25265
25631
  this.root.append(cell);
25266
25632
  let chart;
25633
+ const inject = this.sharedContext && (Ctor === ChartXY || Ctor === Polar) && !("sharedContext" in options);
25267
25634
  try {
25268
- chart = new Ctor({ ...options, container: cell });
25635
+ chart = new Ctor({
25636
+ ...options,
25637
+ ...inject ? { sharedContext: this.sharedContext } : {},
25638
+ container: cell
25639
+ });
25269
25640
  } catch (error) {
25270
25641
  cell.remove();
25271
25642
  throw error;