@crysound/crychart 1.0.5 → 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.
@@ -105,6 +105,7 @@ var CRYChart = (() => {
105
105
  SegmentFigure: () => SegmentFigure,
106
106
  SegmentSeries: () => SegmentSeries,
107
107
  Series3DBase: () => Series3DBase,
108
+ SharedWebGLContext: () => SharedWebGLContext,
108
109
  SimpleShadingStyle: () => SimpleShadingStyle,
109
110
  SlicedHierarchyChart: () => SlicedHierarchyChart,
110
111
  SolidFill: () => SolidFill,
@@ -16393,6 +16394,294 @@ void main(){
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 @@ void main(){
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 @@ void main(){
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 @@ void main(){
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 @@ void main(){
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 @@ void main() {
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 @@ void main() {
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
 
@@ -19035,6 +19337,35 @@ void main() {
19035
19337
  var rgba = (color2) => [color2.r, color2.g, color2.b, color2.a];
19036
19338
  var meshFillColor = (fill, fallback) => fill.kind === "empty" ? ColorRGBA(0, 0, 0, 0) : fill.getColor?.() ?? fallback;
19037
19339
  var finiteVertex2 = (values, index) => Number.isFinite(values[index * 3]) && Number.isFinite(values[index * 3 + 1]) && Number.isFinite(values[index * 3 + 2]);
19340
+ function structuredWireEdges(indices, count) {
19341
+ const columns = indices[1], rows = count / columns;
19342
+ if (!Number.isInteger(columns) || columns < 2 || !Number.isInteger(rows) || rows < 2 || indices.length !== (rows - 1) * (columns - 1) * 6) return void 0;
19343
+ let offset = 0;
19344
+ for (let row = 0; row + 1 < rows; row++) for (let col = 0; col + 1 < columns; col++, offset += 6) {
19345
+ const i = row * columns + col, below = i + columns;
19346
+ if (indices[offset] !== i || indices[offset + 1] !== below || indices[offset + 2] !== i + 1 || indices[offset + 3] !== i + 1 || indices[offset + 4] !== below || indices[offset + 5] !== below + 1) return void 0;
19347
+ }
19348
+ const pairs = new Uint32Array((rows * (columns - 1) + (rows - 1) * columns + (rows - 1) * (columns - 1)) * 2);
19349
+ let length = 0;
19350
+ for (let row = 0; row + 1 < rows; row++) for (let col = 0; col + 1 < columns; col++) {
19351
+ const i = row * columns + col, below = i + columns;
19352
+ if (col === 0) {
19353
+ pairs[length++] = i;
19354
+ pairs[length++] = below;
19355
+ }
19356
+ pairs[length++] = below;
19357
+ pairs[length++] = i + 1;
19358
+ if (row === 0) {
19359
+ pairs[length++] = i + 1;
19360
+ pairs[length++] = i;
19361
+ }
19362
+ pairs[length++] = below;
19363
+ pairs[length++] = below + 1;
19364
+ pairs[length++] = below + 1;
19365
+ pairs[length++] = i + 1;
19366
+ }
19367
+ return pairs;
19368
+ }
19038
19369
  function mergedRanges(ranges, width = 1) {
19039
19370
  const sorted = ranges.filter((range) => range.count > 0).map((range) => ({ start: range.start, count: range.count })).sort((a, b) => a.start - b.start), out = [];
19040
19371
  for (const range of sorted) {
@@ -19261,28 +19592,34 @@ void main() {
19261
19592
  dirty = [];
19262
19593
  styleDirty = true;
19263
19594
  compiled;
19595
+ wireTopology;
19264
19596
  boundsCache;
19265
19597
  setGeometry(input) {
19266
19598
  this.assertAlive();
19267
19599
  if (!input?.positions || input.positions.length % 3) throw new RangeError("Mesh positions require complete XYZ vertices");
19268
19600
  const positions = Float64Array.from(input.positions), count = positions.length / 3;
19269
- const indices = input.indices ? Uint32Array.from(input.indices, (index) => {
19270
- if (!Number.isSafeInteger(index) || index < 0 || index >= count) throw new RangeError("Mesh index outside vertex range");
19271
- return index;
19272
- }) : Uint32Array.from({ length: Math.floor(count / 3) * 3 }, (_, index) => index);
19601
+ const unsignedIndices = input.indices instanceof Uint32Array;
19602
+ if (input.indices) for (let i = 0; i < input.indices.length; i++) {
19603
+ const index = input.indices[i];
19604
+ if (index >= count || !unsignedIndices && (!Number.isSafeInteger(index) || index < 0)) throw new RangeError("Mesh index outside vertex range");
19605
+ }
19606
+ const indices = input.indices ? Uint32Array.from(input.indices) : Uint32Array.from({ length: Math.floor(count / 3) * 3 }, (_, index) => index);
19273
19607
  if (indices.length % 3) throw new RangeError("Mesh indices require complete triangles");
19274
19608
  if (input.values && input.values.length !== count || input.colors && input.colors.length !== count * 4) throw new RangeError("Mesh values/colors do not match vertex count");
19275
19609
  const colors = input.colors ? Float32Array.from(input.colors) : void 0;
19276
19610
  if (colors && !colors.every((value) => Number.isFinite(value) && value >= 0 && value <= 1)) throw new RangeError("Mesh colors require normalized finite RGBA");
19611
+ const sameTopology = positions.length === this.vertices.length && indices.length === this.indices.length && indices.every((value, index) => value === this.indices[index]);
19277
19612
  this.vertices = positions;
19278
- this.indices = indices;
19613
+ if (!sameTopology) {
19614
+ this.indices = indices;
19615
+ this.topologyRevision++;
19616
+ this.compiled = void 0;
19617
+ }
19279
19618
  this.scalarValues = input.values ? Float32Array.from(input.values) : void 0;
19280
19619
  this.vertexColors = colors;
19281
- this.topologyRevision++;
19282
19620
  this.geometryRevision++;
19283
19621
  this.dirty = [{ start: 0, count }];
19284
19622
  this.styleDirty = true;
19285
- this.compiled = void 0;
19286
19623
  this.changed();
19287
19624
  return this;
19288
19625
  }
@@ -19371,28 +19708,62 @@ void main() {
19371
19708
  for (const range of ranges) for (let i = range.start; i < range.start + range.count; i++) {
19372
19709
  if (!all && !finiteVertex2(positions, i)) invalidVertices--;
19373
19710
  const point = this.normalizedVertex(i, normalize);
19374
- positions.set([point.x, point.y, point.z], i * 3);
19711
+ positions[i * 3] = point.x;
19712
+ positions[i * 3 + 1] = point.y;
19713
+ positions[i * 3 + 2] = point.z;
19375
19714
  if (!finiteVertex2(positions, i)) invalidVertices++;
19376
19715
  }
19377
19716
  const colorRanges = all || this.styleDirty ? [{ start: 0, count }] : ranges;
19378
- for (const range of colorRanges) for (let i = range.start; i < range.start + range.count; i++) colors.set(rgba(this.colorAt(i)), i * 4);
19717
+ for (const range of colorRanges) for (let i = range.start; i < range.start + range.count; i++) {
19718
+ const color2 = this.colorAt(i);
19719
+ colors[i * 4] = color2.r;
19720
+ colors[i * 4 + 1] = color2.g;
19721
+ colors[i * 4 + 2] = color2.b;
19722
+ colors[i * 4 + 3] = color2.a;
19723
+ }
19379
19724
  const normal = ranges.length ? this.updateNormals(positions, all ? void 0 : previous?.packet.normals, ranges) : { values: previous?.packet.normals ?? meshNormals(positions, this.indices), ranges: [] };
19380
19725
  const packet = { id: this.id, revision: ++this.packetRevision, previousRevision: previous?.packet.revision, count, mode: "triangles", positions, colors, normals: normal.values, indices: this.indices, indexRevision: this.topologyRevision, allFinite: invalidVertices === 0, lighting: this.lighting, ...this.renderingState(), color: [1, 1, 1, 1], thickness: 0, pointSize: 0, positionUpdateRanges: all ? void 0 : mergedRanges(ranges, 3), colorUpdateRanges: all ? void 0 : mergedRanges(colorRanges, 4), normalUpdateRanges: all ? void 0 : normal.ranges };
19381
19726
  const packets = [packet];
19382
19727
  let wire;
19383
19728
  if (this.wireframe.getThickness() > 0 && meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0)).a > 0) {
19384
- const edges = /* @__PURE__ */ new Set(), values = [];
19385
- for (let i = 0; i < this.indices.length; i += 3) {
19386
- const triangle2 = [this.indices[i], this.indices[i + 1], this.indices[i + 2]];
19387
- if (!triangle2.every((index) => finiteVertex2(positions, index))) continue;
19388
- for (let j = 0; j < 3; j++) {
19389
- const a = triangle2[j], b = triangle2[(j + 1) % 3], key = a < b ? `${a}:${b}` : `${b}:${a}`;
19390
- if (edges.has(key)) continue;
19391
- edges.add(key);
19392
- values.push(positions[a * 3], positions[a * 3 + 1], positions[a * 3 + 2], positions[b * 3], positions[b * 3 + 1], positions[b * 3 + 2], NaN, NaN, NaN);
19729
+ const valid2 = new Uint8Array(this.indices.length / 3);
19730
+ if (invalidVertices === 0) valid2.fill(1);
19731
+ else for (let i = 0; i < this.indices.length; i += 3) valid2[i / 3] = finiteVertex2(positions, this.indices[i]) && finiteVertex2(positions, this.indices[i + 1]) && finiteVertex2(positions, this.indices[i + 2]) ? 1 : 0;
19732
+ let topology = this.wireTopology;
19733
+ if (!topology || topology.indices.length !== this.indices.length || !this.indices.every((value, index) => value === topology.indices[index]) || !valid2.every((value, index) => value === topology.valid[index])) {
19734
+ const gridPairs = invalidVertices === 0 ? structuredWireEdges(this.indices, count) : void 0;
19735
+ if (gridPairs) topology = this.wireTopology = { indices: this.indices.slice(), valid: valid2, pairs: gridPairs };
19736
+ else {
19737
+ const edges = /* @__PURE__ */ new Set(), pairs = new Uint32Array(this.indices.length * 2);
19738
+ const numericKeys = Number.isSafeInteger(count * count);
19739
+ let length = 0;
19740
+ for (let i = 0; i < this.indices.length; i += 3) {
19741
+ if (!valid2[i / 3]) continue;
19742
+ for (let j = 0; j < 3; j++) {
19743
+ const a = this.indices[i + j], b = this.indices[i + (j + 1) % 3];
19744
+ const low = Math.min(a, b), high = Math.max(a, b);
19745
+ const key = numericKeys ? low * count + high : `${low}:${high}`;
19746
+ if (edges.has(key)) continue;
19747
+ edges.add(key);
19748
+ pairs[length++] = a;
19749
+ pairs[length++] = b;
19750
+ }
19751
+ }
19752
+ topology = this.wireTopology = { indices: this.indices.slice(), valid: valid2, pairs: pairs.subarray(0, length) };
19393
19753
  }
19394
19754
  }
19395
- wire = { id: -this.id, revision: packet.revision, count: values.length / 3, mode: "line", positions: Float32Array.from(values), ...this.renderingState(), color: rgba(meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0))), thickness: this.wireframe.getThickness(), pointSize: 0 };
19755
+ const values = new Float32Array(topology.pairs.length / 2 * 9);
19756
+ for (let i = 0, out = 0; i < topology.pairs.length; i += 2, out += 9) {
19757
+ const a = topology.pairs[i] * 3, b = topology.pairs[i + 1] * 3;
19758
+ values[out] = positions[a];
19759
+ values[out + 1] = positions[a + 1];
19760
+ values[out + 2] = positions[a + 2];
19761
+ values[out + 3] = positions[b];
19762
+ values[out + 4] = positions[b + 1];
19763
+ values[out + 5] = positions[b + 2];
19764
+ values[out + 6] = values[out + 7] = values[out + 8] = NaN;
19765
+ }
19766
+ wire = { id: -this.id, revision: packet.revision, count: values.length / 3, mode: "line", positions: values, ...this.renderingState(), color: rgba(meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0))), thickness: this.wireframe.getThickness(), pointSize: 0 };
19396
19767
  packets.push(wire);
19397
19768
  }
19398
19769
  this.compiled = { key: axisKey, revision: this.revision, packet, wire, packets, invalidVertices };
@@ -19402,6 +19773,7 @@ void main() {
19402
19773
  }
19403
19774
  dispose() {
19404
19775
  this.compiled = void 0;
19776
+ this.wireTopology = void 0;
19405
19777
  this.vertices = new Float64Array(0);
19406
19778
  this.indices = new Uint32Array(0);
19407
19779
  this.scalarValues = void 0;
@@ -20721,6 +21093,11 @@ void main() {
20721
21093
  observer;
20722
21094
  overlayContext;
20723
21095
  underlayContext;
21096
+ sharedCore;
21097
+ sharedPresent = null;
21098
+ sharedClient;
21099
+ sharedOffscreen = false;
21100
+ sharedDeferred = false;
20724
21101
  heatmapRenderer;
20725
21102
  heatmapPalettes = /* @__PURE__ */ new Map();
20726
21103
  heatCache = /* @__PURE__ */ new Map();
@@ -20807,7 +21184,7 @@ void main() {
20807
21184
  this.underlay = underlay;
20808
21185
  this.overlay = overlay;
20809
21186
  try {
20810
- 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 });
20811
21188
  } catch (error) {
20812
21189
  this.cssTextFonts?.dispose();
20813
21190
  root.remove();
@@ -20827,6 +21204,18 @@ void main() {
20827
21204
  });
20828
21205
  this.observer.observe(container);
20829
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
+ }
20830
21219
  }
20831
21220
  this.engine = {
20832
21221
  container: this.root ?? this.container,
@@ -21572,8 +21961,26 @@ void main() {
21572
21961
  this.cancelAxisScrollAnimations();
21573
21962
  for (const series of this.series) series.cancelHighlightAnimation?.();
21574
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
+ }
21575
21978
  invalidate() {
21576
21979
  if (this.disposed || this.frame || this.rendering || !this.root) return;
21980
+ if (this.sharedOffscreen) {
21981
+ this.sharedDeferred = true;
21982
+ return;
21983
+ }
21577
21984
  if (typeof requestAnimationFrame === "function")
21578
21985
  this.frame = requestAnimationFrame((timestamp) => {
21579
21986
  this.frame = 0;
@@ -22027,6 +22434,8 @@ void main() {
22027
22434
  ctx.drawImage(cache.canvas, r.left, r.top, r.width, r.height);
22028
22435
  }
22029
22436
  renderData(packets) {
22437
+ const shared = this.sharedCore;
22438
+ if (shared && !shared.beginChartDraw(this.canvas.width, this.canvas.height)) return;
22030
22439
  const grids = [];
22031
22440
  for (const s of this.series) {
22032
22441
  if (!(s instanceof HeatmapSeries) || !s.visible || s.disposed || !this.gpuHeatmap(s))
@@ -22097,7 +22506,7 @@ void main() {
22097
22506
  this.heatmapRenderer = new DataRendererHeatmap(
22098
22507
  this.renderer.gl,
22099
22508
  this.canvas,
22100
- { clipPolicy: this.gpuClipPolicy }
22509
+ { clipPolicy: this.gpuClipPolicy, contextEvents: this.renderer.contextEvents }
22101
22510
  );
22102
22511
  const gl = this.renderer?.gl;
22103
22512
  const rasterTarget = this.gpuClipPolicy === "contained" && gl ? rasterTargetForRect(null, gl.drawingBufferWidth, gl.drawingBufferHeight, this.plot, this.dpr) : void 0;
@@ -22114,6 +22523,7 @@ void main() {
22114
22523
  clear: grids.length === 0,
22115
22524
  rasterTarget
22116
22525
  });
22526
+ if (shared) shared.present(this.sharedPresent, this.canvas.width, this.canvas.height);
22117
22527
  }
22118
22528
  gpuHeatmap(s) {
22119
22529
  return !!this.renderer?.gl && s.axisX.type !== "logarithmic" && s.axisY.type !== "logarithmic";
@@ -23373,7 +23783,8 @@ void main() {
23373
23783
  gpuPackets = /* @__PURE__ */ new Map();
23374
23784
  gpuRevision = 0;
23375
23785
  constructor(options = {}) {
23376
- 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 });
23377
23788
  this.cameraModel = options.experimental3DCameraModel === "legacy" ? "legacy" : "world";
23378
23789
  this.axesZ.push(new Axis(this, "z", options.defaultAxisZ));
23379
23790
  this.coordsAxis.z = this.axesZ[0];
@@ -24948,7 +25359,8 @@ ${sample.position[0].toFixed(4)}, ${sample.position[1].toFixed(4)}`, contains: (
24948
25359
  const chart = new ChartXY({
24949
25360
  container,
24950
25361
  legend: { visible: false },
24951
- ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {}
25362
+ ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {},
25363
+ ...options.sharedContext ? { sharedContext: options.sharedContext } : {}
24952
25364
  });
24953
25365
  const entries = /* @__PURE__ */ new Map();
24954
25366
  let disposed = false;
@@ -25124,12 +25536,27 @@ ${sample.position[0].toFixed(4)}, ${sample.position[1].toFixed(4)}`, contains: (
25124
25536
  }
25125
25537
 
25126
25538
  // src/index.ts
25127
- 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;
25128
25553
  const owned2 = /* @__PURE__ */ new Set();
25129
25554
  let disposed = false;
25130
- const create = (ctor, options = {}) => {
25555
+ const create = (ctor, opts = {}) => {
25131
25556
  if (disposed) throw new Error("Chart context has been disposed");
25132
- 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);
25133
25560
  owned2.add(chart);
25134
25561
  chart.onDispose(() => owned2.delete(chart));
25135
25562
  return chart;
@@ -25160,17 +25587,25 @@ ${sample.position[0].toFixed(4)}, ${sample.position[1].toFixed(4)}`, contains: (
25160
25587
  } catch (error) {
25161
25588
  errors.push(error);
25162
25589
  }
25590
+ if (ownsShared) try {
25591
+ shared.dispose();
25592
+ } catch (error) {
25593
+ errors.push(error);
25594
+ }
25163
25595
  if (errors.length) throw new AggregateError(errors, "Some chart disposal callbacks failed");
25164
25596
  }
25165
25597
  },
25166
25598
  isDisposed: () => disposed,
25167
25599
  /** Live charts owned by this context; disposed charts are released immediately. */
25168
- getChartCount: () => owned2.size
25600
+ getChartCount: () => owned2.size,
25601
+ /** Shared WebGL2 context used by this context; undefined when not enabled. */
25602
+ getSharedContext: () => shared
25169
25603
  };
25170
25604
  }
25171
- var version = "1.0.5";
25605
+ var version = "1.0.7";
25172
25606
  var Dashboard = class {
25173
25607
  root;
25608
+ sharedContext;
25174
25609
  cells = /* @__PURE__ */ new Map();
25175
25610
  children = /* @__PURE__ */ new Set();
25176
25611
  events = new EventHub();
@@ -25182,6 +25617,7 @@ ${sample.position[0].toFixed(4)}, ${sample.position[1].toFixed(4)}`, contains: (
25182
25617
  throw new Error("Dashboard requires a DOM");
25183
25618
  const container = typeof options.container === "string" ? document.getElementById(options.container) : options.container ?? document.body;
25184
25619
  if (!container) throw new Error("Dashboard container was not found");
25620
+ this.sharedContext = options.sharedContext;
25185
25621
  this.root = document.createElement("div");
25186
25622
  this.columns = options.numberOfColumns ?? 2;
25187
25623
  this.rows = options.numberOfRows ?? 2;
@@ -25194,8 +25630,13 @@ ${sample.position[0].toFixed(4)}, ${sample.position[1].toFixed(4)}`, contains: (
25194
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}`;
25195
25631
  this.root.append(cell);
25196
25632
  let chart;
25633
+ const inject = this.sharedContext && (Ctor === ChartXY || Ctor === Polar) && !("sharedContext" in options);
25197
25634
  try {
25198
- chart = new Ctor({ ...options, container: cell });
25635
+ chart = new Ctor({
25636
+ ...options,
25637
+ ...inject ? { sharedContext: this.sharedContext } : {},
25638
+ container: cell
25639
+ });
25199
25640
  } catch (error) {
25200
25641
  cell.remove();
25201
25642
  throw error;