Repository navigation
Expand file tree
/
Copy pathChartGPU.ts
More file actions
3649 lines (3292 loc) · 139 KB
/
Copy pathChartGPU.ts
File metadata and controls
3649 lines (3292 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { GPUContext } from './core/GPUContext';
import { getBufferMemoryStats } from './core/gpu/bufferAllocationTracker';
import { createRenderCoordinator } from './core/createRenderCoordinator';
import type { RenderCoordinator, RenderCoordinatorCallbacks } from './core/createRenderCoordinator';
import { resolveOptionsForChart } from './config/OptionResolver';
import type { ResolvedChartGPUOptions, ResolvedPieSeriesConfig } from './config/OptionResolver';
import type {
CartesianSeriesData,
ChartGPUOptions,
DataPoint,
DataPointTuple,
OHLCDataPoint,
OHLCDataPointTuple,
PieCenter,
PieRadius,
RenderMode,
} from './config/types';
import { createDataZoomSlider } from './components/createDataZoomSlider';
import type { DataZoomSlider } from './components/createDataZoomSlider';
import { createZoomResetButton } from './components/createZoomResetButton';
import type { ZoomResetButton } from './components/createZoomResetButton';
import type { ZoomRange, ZoomState } from './interaction/createZoomState';
import {
computeCandlestickBodyWidthRange,
findCandlestick,
type FinanceOhlcHitSeriesConfig,
} from './interaction/findCandlestick';
import { findNearestPoint } from './interaction/findNearestPoint';
import type { NearestPointMatch } from './interaction/findNearestPoint';
import { findPieSlice } from './interaction/findPieSlice';
import { createAxisScale } from './utils/scales';
import type { LinearScale } from './utils/scales';
import { checkWebGPUSupport } from './utils/checkWebGPU';
import type { PipelineCache } from './core/PipelineCache';
export type { PipelineCache, PipelineCacheStats } from './core/PipelineCache';
import type {
PerformanceMetrics,
PerformanceCapabilities,
ExactFPS,
Milliseconds,
Bytes,
FrameTimeStats,
GPUTimingStats,
MemoryStats,
FrameDropStats,
} from './config/types';
import {
appendIntoRingXY,
computeRawBoundsFromCartesianData,
createRingXYColumns,
dropPrefixXY,
getPointCount as getCartesianPointCount,
getSize as getCartesianSize,
getX as getCartesianX,
getY as getCartesianY,
isRingXYColumns,
isStagingRingView,
stagingRingViewToRingXYColumns,
type RingXYColumns,
type StagingRingView,
} from './data/cartesianData';
import { normalizeMaxPoints, planMaxPointsWindow, resolveEffectiveMaxPointsForAppend } from './data/maxPointsWindow';
import {
getBandLength,
getBandPoint,
getBandX,
appendBandIntoXYYColumns,
asBandXYYArrays,
bandBounds,
bandDataToMutableXYY,
extendBoundsWithBandData,
isBandShapedPayload,
} from './data/bandData';
import {
appendErrorBarIntoHlcColumns,
asErrorBarHlcArrays,
errorBarBounds,
errorBarDataToMutableHlc,
extendBoundsWithErrorBarData,
getErrorBarLength,
getErrorBarPoint,
isErrorBarShapedPayload,
type MutableErrorBarHlcColumns,
} from './data/errorBarData';
import type { BandSeriesData, ErrorBarSeriesData } from './config/types';
import { pointerClientToLayoutCss } from './core/renderCoordinator/utils/canvasUtils';
import { findErrorBarAtPointer } from './interaction/findErrorBar';
import { findImpulseAtPointer } from './interaction/findImpulse';
import type { ResolvedErrorBarSeriesConfig, ResolvedImpulseSeriesConfig } from './config/OptionResolver';
import { impulseBounds } from './data/impulseGeometry';
// --- Instance registry for auto-dispose on page unload (CGPU-OOM-139) ---
const activeInstances = new Set<{ dispose(): void; disposed: boolean }>();
let unloadListenersRegistered = false;
function disposeAllInstances(): void {
// Snapshot to avoid mutation during iteration
const instances = [...activeInstances];
for (const inst of instances) {
try {
inst.dispose();
} catch {
// Best-effort cleanup during page teardown — swallow errors
}
}
}
function handlePageHide(event: PageTransitionEvent): void {
if (event.persisted) return;
disposeAllInstances();
}
function ensureUnloadListeners(): void {
if (unloadListenersRegistered) return;
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
unloadListenersRegistered = true;
window.addEventListener('pagehide', handlePageHide);
}
/** @internal — exposed for test cleanup only. Not part of the public API. */
export function _resetInstanceRegistryForTesting(): void {
activeInstances.clear();
if (typeof window !== 'undefined' && unloadListenersRegistered) {
window.removeEventListener('pagehide', handlePageHide);
unloadListenersRegistered = false;
}
}
/**
* Circular buffer size for frame timestamps (120 frames = 2 seconds at 60fps).
*/
const FRAME_BUFFER_SIZE = 120;
/**
* Expected frame time at 60fps (16.67ms).
*/
const EXPECTED_FRAME_TIME_MS = 1000 / 60;
/**
* Frame drop threshold multiplier (1.5x expected frame time).
*/
const FRAME_DROP_THRESHOLD_MULTIPLIER = 1.5;
/**
* Source kind for zoom range changes.
*
* Used to distinguish zoom change sources:
* - `'user'`: Direct user interaction (pan, pinch, wheel, slider)
* - `'auto-scroll'`: Automatic zoom adjustment from streaming data with auto-scroll enabled
* - `'api'`: Programmatic zoom via `setZoomRange(..., source)` calls
*/
export type ZoomChangeSourceKind = 'user' | 'auto-scroll' | 'api';
/**
* Hit-test match for a chart element.
*/
export type ChartGPUHitTestMatch = Readonly<{
readonly kind: 'cartesian' | 'candlestick' | 'ohlc' | 'pie' | 'errorBar' | 'impulse' | 'pointCloud3d' | 'surface3d';
readonly seriesIndex: number;
readonly dataIndex: number;
/**
* - cartesian: [x, y]
* - candlestick / ohlc: still reported as [timestamp, close] at the ChartGPU wrapper (see hitTest)
* - pie: [slice index proxy via value] (see pie hit path)
* - errorBar: [x, y] center (see also high/low on TooltipParams)
* - impulse: [x, y] tip (see also baseline on TooltipParams)
* - pointCloud3d: [x, y, z]
* - surface3d: [x, y, z] world hit (height along Y)
*/
readonly value: readonly [number, number] | readonly [number, number, number];
/** Point-cloud colormap/scalar channel when present (3D only). */
readonly valueChannel?: number;
/** surface3d cell column index. */
readonly i?: number;
/** surface3d cell row index. */
readonly j?: number;
/** surface3d height (same as value[1] under Y-up). */
readonly height?: number;
}>;
/**
* Result of a hit-test operation on a chart.
*/
export type ChartGPUHitTestResult = Readonly<{
readonly isInGrid: boolean;
readonly canvasX: number;
readonly canvasY: number;
readonly gridX: number;
readonly gridY: number;
readonly match: ChartGPUHitTestMatch | null;
}>;
export interface ChartGPUInstance {
readonly options: Readonly<ChartGPUOptions>;
readonly disposed: boolean;
setOption(options: ChartGPUOptions): void;
/**
* 3D only (`coordinateSystem: 'cartesian3d'`): re-fit camera to data AABB.
* No-op on 2D charts.
*/
resetCamera?(): void;
/**
* 3D only: partial camera update (eye/target/type/fov/…).
* No-op on 2D charts.
*/
setCamera?(partial: import('./config/types').Chart3DCameraOptions): void;
/**
* 3D only: current resolved camera pose. Returns `null` on 2D charts.
*/
getCamera?(): import('./core/3d/camera').ResolvedCamera | null;
/**
* 3D only: streaming / partial update for a `surface3d` series (resolved index).
* Modes: `replaceY`, `appendColumns` (+scrollX), `appendRows` (+scrollZ).
* No-op on 2D charts.
*/
updateSurface3D?(seriesIndex: number, update: import('./config/types').Surface3DUpdate): void;
/**
* 2D only: streaming / partial update for a `heatmap` series (resolved index).
* Modes: `replaceZ`, `appendColumns` (+scrollX), `appendRows` (+scrollY).
* Full field is row-major `z[j * columns + i]`; appendColumns strips are column-major
* `z[c * rows + r]`. No-op / omitted on 3D charts (use updateSurface3D for surfaces).
*/
updateHeatmap?(seriesIndex: number, update: import('./config/types').HeatmapUpdate): void;
/**
* @internal Test/debug: how many times the hit-test columnar store was fully rebuilt.
*/
getHitTestStoreRebuildCount(): number;
/**
* @internal Test/debug: retained point count in the ChartGPU hit-test store for a series.
* Used to assert dual-store windowing (device auto-window / maxPoints) matches GPU policy.
*/
getHitTestSeriesPointCount(seriesIndex: number): number;
/**
* Appends new points to a cartesian series at runtime (streaming).
*
* Accepts multiple formats for efficient data append without per-point object allocations:
* - `DataPoint[]`: Traditional array of point objects/tuples (existing behavior)
* - `XYArraysData`: Separate x/y/size arrays (`{x: ArrayLike<number>, y: ArrayLike<number>, size?: ArrayLike<number>}`)
* - `InterleavedXYData`: Typed array with [x0,y0,x1,y1,...] layout (e.g. `Float32Array`)
* - `OHLCDataPoint[]`: For candlestick and ohlc series
*
* Point count is derived via `getPointCount()` from `cartesianData.ts`:
* - `XYArraysData`: min(x.length, y.length)
* - `InterleavedXYData`: floor(length / 2), ignoring trailing odd element
* - `DataView` is unsupported and throws an error
*
* Optional `options.maxPoints` is an **opt-in per call** fixed-capacity ring
* (not sticky series state — omit it later and growth is unbounded again). Policy
* matches DataStore / coordinator (`planMaxPointsWindow`):
* - if the new batch alone is ≥ `maxPoints`, keep only that batch’s tail
* (strict replace; previous points discarded);
* - else fill up to `maxPoints`, then drop oldest points on each overflow
* (GPU uses modular ring writes — O(append), no full retained-window rewrite).
* Peak retained length is **`maxPoints`**. Prefer this over sliding-window
* full `setOption`.
*
* When both `maxPoints` is set and `tooltip.show === false`, the ChartGPU
* hit-test columnar store is not updated on append (dual-store relief for
* high-rate FIFO). Re-enabling tooltips via `setOption({ tooltip: { show: true } })`
* (or calling `hitTest` after that) resyncs from the coordinator ring/raw.
* With tooltip on, hit-test uses the same ring policy as the GPU path.
*
* Pie series are non-cartesian and are not supported by streaming append.
*/
appendData(
seriesIndex: number,
newPoints: CartesianSeriesData | OHLCDataPoint[],
options?: Readonly<{ maxPoints?: number }>
): void;
resize(): void;
dispose(): void;
on(eventName: 'crosshairMove', callback: ChartGPUCrosshairMoveCallback): void;
on(eventName: 'zoomRangeChange', callback: ChartGPUZoomRangeChangeCallback): void;
on(eventName: 'deviceLost', callback: ChartGPUDeviceLostCallback): void;
on(eventName: 'dataAppend', callback: ChartGPUDataAppendCallback): void;
on(eventName: ChartGPUEventName, callback: ChartGPUEventCallback): void;
off(eventName: 'crosshairMove', callback: ChartGPUCrosshairMoveCallback): void;
off(eventName: 'zoomRangeChange', callback: ChartGPUZoomRangeChangeCallback): void;
off(eventName: 'deviceLost', callback: ChartGPUDeviceLostCallback): void;
off(eventName: 'dataAppend', callback: ChartGPUDataAppendCallback): void;
off(eventName: ChartGPUEventName, callback: ChartGPUEventCallback): void;
/**
* Gets the current “interaction x” in domain units (or `null` when inactive).
*
* This is derived from pointer movement inside the plot grid and can also be driven
* externally via `setInteractionX(...)` (e.g. chart sync).
*/
getInteractionX(): number | null;
/**
* Drives the chart’s crosshair + tooltip from a domain-space x value.
*
* Passing `null` clears the interaction (hides crosshair/tooltip).
*/
setInteractionX(x: number | null, source?: unknown): void;
/**
* Alias for `setInteractionX(...)` for chart sync semantics.
*/
setCrosshairX(x: number | null, source?: unknown): void;
/**
* Subscribes to interaction x changes (domain units).
*
* Returns an unsubscribe function.
*/
onInteractionXChange(callback: (x: number | null, source?: unknown) => void): () => void;
/**
* Returns the current percent-space zoom window (or `null` when zoom is disabled).
*/
getZoomRange(): Readonly<{ start: number; end: number }> | null;
/**
* Sets the percent-space zoom window.
*
* No-op when zoom is disabled.
*/
setZoomRange(start: number, end: number, source?: unknown): void;
/**
* Gets the latest performance metrics.
* Returns exact FPS and detailed frame statistics.
*
* @returns Current performance metrics, or null if not available
*/
getPerformanceMetrics(): Readonly<PerformanceMetrics> | null;
/**
* Gets the performance capabilities of the current environment.
* Indicates which performance features are supported.
*
* @returns Performance capabilities, or null if not initialized
*/
getPerformanceCapabilities(): Readonly<PerformanceCapabilities> | null;
/**
* Registers a callback to be notified of performance metric updates.
* Callback is invoked every frame with the latest metrics.
*
* @param callback - Function to call with updated metrics
* @returns Unsubscribe function to remove the callback
*/
onPerformanceUpdate(callback: (metrics: Readonly<PerformanceMetrics>) => void): () => void;
/**
* Performs hit-testing on a pointer or mouse event.
*
* Returns coordinates and matched chart element (if any).
* Accepts both `PointerEvent` (for hover/click) and `MouseEvent` (for contextmenu/right-click).
*
* @param e - Pointer or mouse event to test
* @returns Hit-test result with coordinates and optional match
*/
hitTest(e: PointerEvent | MouseEvent): ChartGPUHitTestResult;
/**
* Gets the current render mode ('auto' | 'external').
*/
getRenderMode(): RenderMode;
/**
* Sets the render mode. In 'auto' mode, ChartGPU schedules renders automatically.
* In 'external' mode, the application must call renderFrame() on each frame.
*/
setRenderMode(mode: RenderMode): void;
/**
* Renders a single frame (external mode only).
*
* In 'auto' mode, this is a no-op and logs a warning in development.
* In 'external' mode, executes a render if the chart is dirty.
*
* **GPU submit is deferred** to a microtask after this returns so multi-chart
* dashboards that share one `GPUDevice` can coalesce N encodes into one
* `queue.submit`. If you need queue visibility before
* `device.queue.onSubmittedWorkDone()`, await one microtask first:
* `chart.renderFrame(); await Promise.resolve(); await device.queue.onSubmittedWorkDone();`
*
* @returns true if a frame was rendered, false if the chart was already clean
*/
renderFrame(): boolean;
/**
* Checks if the chart needs rendering (has pending changes).
*
* @returns true if the chart is dirty and needs a render
*/
needsRender(): boolean;
}
// Type-only alias so callsites can write `ChartGPU[]` for chart instances (while `ChartGPU` the value
// remains the creation API exported from `src/index.ts`).
export type ChartGPU = ChartGPUInstance;
export type ChartGPUEventName =
| 'click'
| 'mouseover'
| 'mouseout'
| 'crosshairMove'
| 'zoomRangeChange'
| 'deviceLost'
| 'dataAppend';
export type ChartGPUEventPayload = Readonly<{
readonly seriesIndex: number | null;
readonly dataIndex: number | null;
readonly value: readonly [number, number] | null;
readonly seriesName: string | null;
readonly event: PointerEvent;
}>;
export type ChartGPUDeviceLostPayload = Readonly<{
readonly reason: GPUDeviceLostReason;
readonly message: string;
}>;
export type ChartGPUCrosshairMovePayload = Readonly<{
readonly x: number | null;
readonly source?: unknown;
}>;
export type ChartGPUZoomRangeChangePayload = Readonly<{
readonly start: number;
readonly end: number;
readonly source?: unknown;
readonly sourceKind?: ZoomChangeSourceKind;
}>;
export type ChartGPUDataAppendPayload = Readonly<{
readonly seriesIndex: number;
readonly count: number;
readonly xExtent: { readonly min: number; readonly max: number };
}>;
export type ChartGPUEventCallback = (payload: ChartGPUEventPayload) => void;
export type ChartGPUCrosshairMoveCallback = (payload: ChartGPUCrosshairMovePayload) => void;
export type ChartGPUZoomRangeChangeCallback = (payload: ChartGPUZoomRangeChangePayload) => void;
export type ChartGPUDeviceLostCallback = (payload: ChartGPUDeviceLostPayload) => void;
export type ChartGPUDataAppendCallback = (payload: ChartGPUDataAppendPayload) => void;
type AnyChartGPUEventCallback =
| ChartGPUEventCallback
| ChartGPUCrosshairMoveCallback
| ChartGPUZoomRangeChangeCallback
| ChartGPUDeviceLostCallback
| ChartGPUDataAppendCallback;
type ListenerRegistry = Readonly<Record<ChartGPUEventName, Set<AnyChartGPUEventCallback>>>;
// Pipeline cache types are defined in `src/core/PipelineCache.ts` and re-exported near the top
// of this file so public API uses a single canonical definition.
/**
* Context for creating a ChartGPU instance with shared WebGPU device and adapter.
* Use this to share a single GPU device across multiple chart instances for improved resource efficiency.
*
* Optionally provide a `pipelineCache` to share compiled pipelines across charts, reducing
* shader compilation overhead during initialization.
*/
export type ChartGPUCreateContext = Readonly<{
readonly device: GPUDevice;
readonly adapter: GPUAdapter;
/**
* Optional pipeline cache for sharing compiled pipelines across charts.
* Must be created for the same GPUDevice as the context.
*
* @example
* ```ts
* const cache = createPipelineCache(device);
* const chart1 = await ChartGPU.create(container1, options, { adapter, device, pipelineCache: cache });
* const chart2 = await ChartGPU.create(container2, options, { adapter, device, pipelineCache: cache });
* ```
*/
readonly pipelineCache?: PipelineCache;
}>;
type TapCandidate = {
readonly pointerId: number;
readonly startClientX: number;
readonly startClientY: number;
readonly startTimeMs: number;
};
const DEFAULT_TAP_MAX_DISTANCE_CSS_PX = 6;
const DEFAULT_TAP_MAX_TIME_MS = 500;
type Bounds = Readonly<{
xMin: number;
xMax: number;
yMin: number;
yMax: number;
}>;
/**
* Mutable columnar store for cartesian series data in the hit-test runtime.
* Supports efficient append without per-point DataPoint object allocations.
*
* Note: size array is aligned with x/y arrays (same length), with undefined for points without size values.
*/
type MutableXYColumns = {
x: number[];
y: number[];
size?: (number | undefined)[];
};
const isTupleDataPoint = (p: DataPoint): p is DataPointTuple => Array.isArray(p);
const isTupleOHLCDataPoint = (p: OHLCDataPoint): p is OHLCDataPointTuple => Array.isArray(p);
const getPointXY = (p: DataPoint): { readonly x: number; readonly y: number } => {
if (isTupleDataPoint(p)) return { x: p[0], y: p[1] };
return { x: p.x, y: p.y };
};
/**
* Converts CartesianSeriesData to MutableXYColumns for the runtime hit-test store.
* Extracts x, y, and optional size values into separate mutable arrays.
* Size array is aligned with x/y arrays (same length), with undefined for points without size values.
*/
const cartesianDataToMutableColumns = (data: CartesianSeriesData): MutableXYColumns => {
const n = getCartesianPointCount(data);
if (n === 0) return { x: [], y: [] };
const x: number[] = new Array(n);
const y: number[] = new Array(n);
const sizeValues: (number | undefined)[] = [];
let hasSizeValues = false;
for (let i = 0; i < n; i++) {
x[i] = getCartesianX(data, i);
y[i] = getCartesianY(data, i);
const size = getCartesianSize(data, i);
sizeValues[i] = size;
if (size !== undefined) {
hasSizeValues = true;
}
}
return hasSizeValues ? { x, y, size: sizeValues } : { x, y };
};
const getOHLCTimestamp = (p: OHLCDataPoint): number => (isTupleOHLCDataPoint(p) ? p[0] : p.timestamp);
const getOHLCClose = (p: OHLCDataPoint): number => (isTupleOHLCDataPoint(p) ? p[2] : p.close);
const hasSliderDataZoom = (options: ChartGPUOptions): boolean =>
options.dataZoom?.some((z) => z?.type === 'slider') ?? false;
const hasInsideDataZoom = (options: ChartGPUOptions): boolean =>
options.dataZoom?.some((z) => z?.type === 'inside') ?? false;
const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
type InteractionScalesCache = {
rectWidthCss: number;
rectHeightCss: number;
plotWidthCss: number;
plotHeightCss: number;
xDomainMin: number;
xDomainMax: number;
yDomainMin: number;
yDomainMax: number;
xScale: LinearScale;
yScale: LinearScale;
};
/**
* Extends bounds with new CartesianSeriesData (any format).
* Optimized to avoid per-point type checks for typed arrays.
*/
const extendBoundsWithCartesianData = (bounds: Bounds | null, data: CartesianSeriesData): Bounds | null => {
const n = getCartesianPointCount(data);
if (n === 0) return bounds;
let b = bounds;
if (!b) {
// No existing bounds - compute from scratch (already optimized)
return computeRawBoundsFromCartesianData(data);
}
let xMin = b.xMin;
let xMax = b.xMax;
let yMin = b.yMin;
let yMax = b.yMax;
// Hoist type detection outside loop to avoid per-point type checks
// NOTE: Format detection logic is duplicated in 2 places and must stay in sync:
// 1. extendBoundsWithCartesianData (here) - for bounds updates
// 2. appendData method - for columnar store appends (also computes xExtent inline)
const isXYArrays = typeof data === 'object' && data !== null && !Array.isArray(data) && 'x' in data && 'y' in data;
const isInterleaved = typeof data === 'object' && data !== null && !Array.isArray(data) && ArrayBuffer.isView(data);
if (isXYArrays) {
// Fast path for XYArraysData
const xyData = data as { x: ArrayLike<number>; y: ArrayLike<number> };
for (let i = 0; i < n; i++) {
const x = xyData.x[i]!;
const y = xyData.y[i]!;
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
} else if (isInterleaved) {
// Fast path for InterleavedXYData
const arr = data as Float32Array | Float64Array;
for (let i = 0; i < n; i++) {
const x = arr[i * 2]!;
const y = arr[i * 2 + 1]!;
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
} else {
// Array<DataPoint> path: use helper functions
for (let i = 0; i < n; i++) {
const x = getCartesianX(data, i);
const y = getCartesianY(data, i);
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
}
// Keep bounds usable for downstream scale derivation.
if (xMin === xMax) xMax = xMin + 1;
if (yMin === yMax) yMax = yMin + 1;
return { xMin, xMax, yMin, yMax };
};
const extendBoundsWithOHLCDataPoints = (bounds: Bounds | null, points: ReadonlyArray<OHLCDataPoint>): Bounds | null => {
if (points.length === 0) return bounds;
let xMin = bounds?.xMin ?? Number.POSITIVE_INFINITY;
let xMax = bounds?.xMax ?? Number.NEGATIVE_INFINITY;
let yMin = bounds?.yMin ?? Number.POSITIVE_INFINITY;
let yMax = bounds?.yMax ?? Number.NEGATIVE_INFINITY;
for (let i = 0; i < points.length; i++) {
const p = points[i]!;
const timestamp = getOHLCTimestamp(p);
const low = isTupleOHLCDataPoint(p) ? p[3] : p.low;
const high = isTupleOHLCDataPoint(p) ? p[4] : p.high;
if (!Number.isFinite(timestamp) || !Number.isFinite(low) || !Number.isFinite(high)) continue;
if (timestamp < xMin) xMin = timestamp;
if (timestamp > xMax) xMax = timestamp;
if (low < yMin) yMin = low;
if (high > yMax) yMax = high;
}
if (!Number.isFinite(xMin) || !Number.isFinite(xMax) || !Number.isFinite(yMin) || !Number.isFinite(yMax)) {
return bounds;
}
// Keep bounds usable for downstream scale derivation.
if (xMin === xMax) xMax = xMin + 1;
if (yMin === yMax) yMax = yMin + 1;
return { xMin, xMax, yMin, yMax };
};
const computeGlobalBounds = (
series: ResolvedChartGPUOptions['series'],
runtimeRawBoundsByIndex?: ReadonlyArray<Bounds | null> | null
): Bounds => {
let xMin = Number.POSITIVE_INFINITY;
let xMax = Number.NEGATIVE_INFINITY;
let yMin = Number.POSITIVE_INFINITY;
let yMax = Number.NEGATIVE_INFINITY;
for (let s = 0; s < series.length; s++) {
const seriesConfig = series[s]!;
// Pie series are non-cartesian; they don't participate in x/y bounds.
if (seriesConfig.type === 'pie') continue;
// Prefer the chart-owned runtime bounds (kept up to date by appendData()).
const runtimeBoundsCandidate = runtimeRawBoundsByIndex?.[s] ?? null;
if (runtimeBoundsCandidate) {
const b = runtimeBoundsCandidate;
if (Number.isFinite(b.xMin) && Number.isFinite(b.xMax) && Number.isFinite(b.yMin) && Number.isFinite(b.yMax)) {
if (b.xMin < xMin) xMin = b.xMin;
if (b.xMax > xMax) xMax = b.xMax;
if (b.yMin < yMin) yMin = b.yMin;
if (b.yMax > yMax) yMax = b.yMax;
continue;
}
}
// Prefer resolver-provided bounds when available (avoids O(n) scans on initial setOption()).
// (Resolved series types include `rawBounds` for cartesian series; keep this defensive.)
const rawBoundsCandidate = (seriesConfig as unknown as { rawBounds?: Bounds | null }).rawBounds ?? null;
if (rawBoundsCandidate) {
const b = rawBoundsCandidate;
if (Number.isFinite(b.xMin) && Number.isFinite(b.xMax) && Number.isFinite(b.yMin) && Number.isFinite(b.yMax)) {
if (b.xMin < xMin) xMin = b.xMin;
if (b.xMax > xMax) xMax = b.xMax;
if (b.yMin < yMin) yMin = b.yMin;
if (b.yMax > yMax) yMax = b.yMax;
continue;
}
}
if (seriesConfig.type === 'candlestick' || seriesConfig.type === 'ohlc') {
// Fallback scan when resolver-provided bounds aren't present.
const data = seriesConfig.data as ReadonlyArray<OHLCDataPoint>;
for (let i = 0; i < data.length; i++) {
const p = data[i]!;
const timestamp = getOHLCTimestamp(p);
const low = isTupleOHLCDataPoint(p) ? p[3] : p.low;
const high = isTupleOHLCDataPoint(p) ? p[4] : p.high;
if (!Number.isFinite(timestamp) || !Number.isFinite(low) || !Number.isFinite(high)) continue;
if (timestamp < xMin) xMin = timestamp;
if (timestamp > xMax) xMax = timestamp;
if (low < yMin) yMin = low;
if (high > yMax) yMax = high;
}
continue;
}
if (seriesConfig.type === 'band') {
const bb = bandBounds((seriesConfig.rawData ?? seriesConfig.data) as BandSeriesData);
if (!bb) continue;
if (bb.xMin < xMin) xMin = bb.xMin;
if (bb.xMax > xMax) xMax = bb.xMax;
if (bb.yMin < yMin) yMin = bb.yMin;
if (bb.yMax > yMax) yMax = bb.yMax;
continue;
}
if (seriesConfig.type === 'errorBar') {
const direction =
(seriesConfig as { direction?: 'vertical' | 'horizontal' }).direction === 'horizontal'
? 'horizontal'
: 'vertical';
const eb = errorBarBounds((seriesConfig.rawData ?? seriesConfig.data) as ErrorBarSeriesData, direction);
if (!eb) continue;
if (eb.xMin < xMin) xMin = eb.xMin;
if (eb.xMax > xMax) xMax = eb.xMax;
if (eb.yMin < yMin) yMin = eb.yMin;
if (eb.yMax > yMax) yMax = eb.yMax;
continue;
}
if (seriesConfig.type === 'impulse') {
const baseline =
typeof (seriesConfig as { baseline?: number }).baseline === 'number' &&
Number.isFinite((seriesConfig as { baseline?: number }).baseline)
? ((seriesConfig as { baseline: number }).baseline as number)
: 0;
const ib = impulseBounds((seriesConfig.rawData ?? seriesConfig.data) as CartesianSeriesData, baseline);
if (!ib) continue;
if (ib.xMin < xMin) xMin = ib.xMin;
if (ib.xMax > xMax) xMax = ib.xMax;
if (ib.yMin < yMin) yMin = ib.yMin;
if (ib.yMax > yMax) yMax = ib.yMax;
continue;
}
const b = computeRawBoundsFromCartesianData(seriesConfig.data as CartesianSeriesData);
if (!b) continue;
if (b.xMin < xMin) xMin = b.xMin;
if (b.xMax > xMax) xMax = b.xMax;
if (b.yMin < yMin) yMin = b.yMin;
if (b.yMax > yMax) yMax = b.yMax;
}
if (!Number.isFinite(xMin) || !Number.isFinite(xMax) || !Number.isFinite(yMin) || !Number.isFinite(yMax)) {
return { xMin: 0, xMax: 1, yMin: 0, yMax: 1 };
}
if (xMin === xMax) xMax = xMin + 1;
if (yMin === yMax) yMax = yMin + 1;
return { xMin, xMax, yMin, yMax };
};
const normalizeDomain = (
minCandidate: number,
maxCandidate: number
): { readonly min: number; readonly max: number } => {
let min = minCandidate;
let max = maxCandidate;
if (!Number.isFinite(min) || !Number.isFinite(max)) {
min = 0;
max = 1;
}
if (min === max) {
max = min + 1;
} else if (min > max) {
const t = min;
min = max;
max = t;
}
return { min, max };
};
type CartesianHitTestMatch = Readonly<{
kind: 'cartesian';
match: NearestPointMatch;
}>;
type PieHitTestMatch = Readonly<{
kind: 'pie';
seriesIndex: number;
dataIndex: number;
sliceValue: number;
}>;
type CandlestickHitTestMatch = Readonly<{
kind: 'candlestick' | 'ohlc';
seriesIndex: number;
dataIndex: number;
point: OHLCDataPoint;
}>;
type ErrorBarHitTestMatch = Readonly<{
kind: 'errorBar';
seriesIndex: number;
dataIndex: number;
point: { readonly x: number; readonly y: number; readonly high: number; readonly low: number };
}>;
type ImpulseHitTestMatch = Readonly<{
kind: 'impulse';
seriesIndex: number;
dataIndex: number;
point: { readonly x: number; readonly y: number; readonly baseline: number };
}>;
type HitTestMatch =
| CartesianHitTestMatch
| PieHitTestMatch
| CandlestickHitTestMatch
| ErrorBarHitTestMatch
| ImpulseHitTestMatch;
const parseNumberOrPercent = (value: number | string, basis: number): number | null => {
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
if (typeof value !== 'string') return null;
const s = value.trim();
if (s.length === 0) return null;
if (s.endsWith('%')) {
const pct = Number.parseFloat(s.slice(0, -1));
if (!Number.isFinite(pct)) return null;
return (pct / 100) * basis;
}
// Be permissive: allow numeric strings like "120" even though the public type primarily documents percent strings.
const n = Number.parseFloat(s);
return Number.isFinite(n) ? n : null;
};
const resolvePieCenterPlotCss = (
center: PieCenter | undefined,
plotWidthCss: number,
plotHeightCss: number
): { readonly x: number; readonly y: number } => {
const xRaw = center?.[0] ?? '50%';
const yRaw = center?.[1] ?? '50%';
const x = parseNumberOrPercent(xRaw, plotWidthCss);
const y = parseNumberOrPercent(yRaw, plotHeightCss);
return {
x: Number.isFinite(x) ? x! : plotWidthCss * 0.5,
y: Number.isFinite(y) ? y! : plotHeightCss * 0.5,
};
};
const isPieRadiusTuple = (radius: PieRadius): radius is readonly [inner: number | string, outer: number | string] =>
Array.isArray(radius);
const resolvePieRadiiCss = (
radius: PieRadius | undefined,
maxRadiusCss: number
): { readonly inner: number; readonly outer: number } => {
// Default similar to common chart libs (mirrors `createPieRenderer.ts` and coordinator helpers).
if (radius == null) return { inner: 0, outer: maxRadiusCss * 0.7 };
if (isPieRadiusTuple(radius)) {
const inner = parseNumberOrPercent(radius[0], maxRadiusCss);
const outer = parseNumberOrPercent(radius[1], maxRadiusCss);
const innerCss = Math.max(0, Number.isFinite(inner) ? inner! : 0);
const outerCss = Math.max(innerCss, Number.isFinite(outer) ? outer! : maxRadiusCss * 0.7);
return { inner: innerCss, outer: Math.min(maxRadiusCss, outerCss) };
}
const outer = parseNumberOrPercent(radius, maxRadiusCss);
const outerCss = Math.max(0, Number.isFinite(outer) ? outer! : maxRadiusCss * 0.7);
return { inner: 0, outer: Math.min(maxRadiusCss, outerCss) };
};
/**
* Creates a ChartGPU instance with default WebGPU initialization.
*/
export async function createChartGPU(container: HTMLElement, options: ChartGPUOptions): Promise<ChartGPUInstance>;
/**
* Creates a ChartGPU instance with a shared WebGPU device and adapter.
* Use this overload to share a single GPU device across multiple chart instances.
*
* @param container - HTML container element for the chart
* @param options - Chart configuration options
* @param context - Shared GPU context with device and adapter
*/
export async function createChartGPU(
container: HTMLElement,
options: ChartGPUOptions,
context: ChartGPUCreateContext
): Promise<ChartGPUInstance>;
export async function createChartGPU(
container: HTMLElement,
options: ChartGPUOptions,
context?: ChartGPUCreateContext
): Promise<ChartGPUInstance> {
// 3D modality: fully separate create path (depth + camera coordinator).
if (options.coordinateSystem === 'cartesian3d') {
const { createChartGPU3D } = await import('./createChartGPU3D');
return createChartGPU3D(container, options, context, (inst) => {
activeInstances.add(inst);
ensureUnloadListeners();
});
}
// Check WebGPU support before creating canvas or any resources.
// When the caller injects an adapter+device, avoid requesting another adapter during the
// support check (shared device mode).
if (!context) {
const supportCheck = await checkWebGPUSupport();
if (!supportCheck.supported) {
const reason = supportCheck.reason || 'Unknown reason';
throw new Error(
`ChartGPU: WebGPU is not available.\n` +
`Reason: ${reason}\n` +
`Browser support: Chrome/Edge 113+, Safari 18+, Firefox not yet supported.\n` +
`Resources:\n` +
` - MDN WebGPU API: https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API\n` +
` - Browser compatibility: https://caniuse.com/webgpu\n` +
` - WebGPU specification: https://www.w3.org/TR/webgpu/\n` +
` - Check your system: https://webgpureport.org/`
);
}
} else {
// Minimal sanity checks: the injected device path still requires WebGPU globals for canvas format negotiation.
if (typeof navigator === 'undefined' || !navigator.gpu) {
throw new Error('ChartGPU: Shared device mode requires WebGPU globals (navigator.gpu) to be available.');
}
}
// Fail fast: pipeline cache (if provided) must be created for the same GPUDevice this chart will use.
if (context?.pipelineCache && context.pipelineCache.device !== context.device) {
throw new Error(
'ChartGPU: pipelineCache.device must match the GPUDevice in the creation context. ' +
'Create the pipeline cache with the same device: createPipelineCache(device).'
);
}
const canvas = document.createElement('canvas');
// Ensure the canvas participates in layout and can size via the container.
canvas.style.display = 'block';
canvas.style.width = '100%';
canvas.style.height = '100%';
// Append before awaiting so it appears immediately and has measurable size.
container.appendChild(canvas);
const isSharedDevice = !!context;
let disposed = false;
let renderMode: RenderMode = options.renderMode ?? 'auto';
let isRendering = false;
let deviceIsLost = false;
let gpuContext: GPUContext | null = null;
let coordinator: RenderCoordinator | null = null;
let coordinatorTargetFormat: GPUTextureFormat | null = null;
let unsubscribeCoordinatorInteractionXChange: (() => void) | null = null;
let unsubscribeCoordinatorZoomRangeChange: (() => void) | null = null;
// For chart-sync loop prevention: when `setZoomRange(..., source)` is called, we "arm" the next
// coordinator zoom-change notification with the provided source token so downstream listeners
// can skip rebroadcast.
let pendingZoomSource: unknown = undefined;
let pendingZoomSourceArmed = false;
let dataZoomSliderHost: HTMLDivElement | null = null;
let dataZoomSlider: DataZoomSlider | null = null;
let zoomResetButton: ZoomResetButton | null = null;
let currentOptions: ChartGPUOptions = options;
let resolvedOptions: ResolvedChartGPUOptions = resolveOptionsForChart(currentOptions);
/**
* Create-time DPR policy (issue #155 / create-only contract).
* - Finite > 0: freeze this explicit DPR for buffer sizing + GPUContext layout on every resize
* (setOption cannot change it; dispose/recreate to change).