-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
3840 lines (3288 loc) · 113 KB
/
index.js
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 createDom2dCamera from 'dom-2d-camera';
import createPubSub from 'pub-sub-es';
import { mat4, vec4 } from 'gl-matrix';
import createLine from 'regl-line';
import {
max as maxArray,
hasSameElements,
identity,
rangeMap,
unionIntegers,
throttleAndDebounce,
} from '@flekschas/utils';
import createKdbush from './kdbush';
import createRenderer from './renderer';
import createLassoManager from './lasso-manager';
import BG_FS from './bg.fs';
import BG_VS from './bg.vs';
import POINT_FS from './point.fs';
import POINT_SIMPLE_FS from './point-simple.fs';
import createVertexShader from './point.vs';
import POINT_UPDATE_FS from './point-update.fs';
import POINT_UPDATE_VS from './point-update.vs';
import createSplineCurve from './spline-curve';
import {
AUTO,
COLOR_ACTIVE_IDX,
COLOR_BG_IDX,
COLOR_HOVER_IDX,
COLOR_NORMAL_IDX,
COLOR_NUM_STATES,
DEFAULT_BACKGROUND_IMAGE,
DEFAULT_COLOR_BG,
DEFAULT_COLOR_BY,
DEFAULT_COLOR_NORMAL,
DEFAULT_COLOR_ACTIVE,
DEFAULT_COLOR_HOVER,
DEFAULT_DATA_ASPECT_RATIO,
DEFAULT_DESELECT_ON_DBL_CLICK,
DEFAULT_DESELECT_ON_ESCAPE,
DEFAULT_DISTANCE,
DEFAULT_EASING,
DEFAULT_HEIGHT,
DEFAULT_LASSO_COLOR,
DEFAULT_LASSO_LINE_WIDTH,
DEFAULT_LASSO_MIN_DELAY,
DEFAULT_LASSO_MIN_DIST,
DEFAULT_LASSO_CLEAR_EVENT,
DEFAULT_LASSO_ON_LONG_PRESS,
DEFAULT_LASSO_LONG_PRESS_TIME,
DEFAULT_LASSO_LONG_PRESS_AFTER_EFFECT_TIME,
DEFAULT_LASSO_LONG_PRESS_EFFECT_DELAY,
DEFAULT_LASSO_LONG_PRESS_REVERT_EFFECT_TIME,
DEFAULT_SHOW_RETICLE,
DEFAULT_RETICLE_COLOR,
DEFAULT_POINT_CONNECTION_COLOR_NORMAL,
DEFAULT_POINT_CONNECTION_COLOR_ACTIVE,
DEFAULT_POINT_CONNECTION_COLOR_HOVER,
DEFAULT_POINT_CONNECTION_COLOR_BY,
DEFAULT_POINT_CONNECTION_OPACITY,
DEFAULT_POINT_CONNECTION_OPACITY_BY,
DEFAULT_POINT_CONNECTION_OPACITY_ACTIVE,
DEFAULT_POINT_CONNECTION_SIZE,
DEFAULT_POINT_CONNECTION_SIZE_ACTIVE,
DEFAULT_POINT_CONNECTION_SIZE_BY,
DEFAULT_POINT_CONNECTION_MAX_INT_POINTS_PER_SEGMENT,
DEFAULT_POINT_CONNECTION_INT_POINTS_TOLERANCE,
DEFAULT_SHOW_POINT_CONNECTIONS,
DEFAULT_POINT_OUTLINE_WIDTH,
MIN_POINT_SIZE,
DEFAULT_POINT_SIZE,
DEFAULT_POINT_SIZE_SELECTED,
DEFAULT_POINT_SIZE_MOUSE_DETECTION,
DEFAULT_SIZE_BY,
DEFAULT_ROTATION,
DEFAULT_TARGET,
DEFAULT_VIEW,
DEFAULT_WIDTH,
DEFAULT_PERFORMANCE_MODE,
EASING_FNS,
FLOAT_BYTES,
LASSO_CLEAR_EVENTS,
LASSO_CLEAR_ON_DESELECT,
LASSO_CLEAR_ON_END,
DEFAULT_LASSO_INITIATOR,
KEY_ACTION_LASSO,
KEY_ACTION_ROTATE,
KEY_ACTION_MERGE,
KEY_ACTIONS,
KEY_ALT,
KEY_CMD,
KEY_CTRL,
KEY_META,
KEY_SHIFT,
KEYS,
DEFAULT_KEY_MAP,
MOUSE_MODE_PANZOOM,
MOUSE_MODE_LASSO,
MOUSE_MODE_ROTATE,
MOUSE_MODES,
DEFAULT_MOUSE_MODE,
SINGLE_CLICK_DELAY,
LONG_CLICK_TIME,
DEFAULT_OPACITY_BY,
DEFAULT_OPACITY_BY_DENSITY_FILL,
DEFAULT_OPACITY_BY_DENSITY_DEBOUNCE_TIME,
DEFAULT_OPACITY_INACTIVE_MAX,
DEFAULT_OPACITY_INACTIVE_SCALE,
Z_NAMES,
W_NAMES,
DEFAULT_IMAGE_LOAD_TIMEOUT,
ERROR_POINTS_NOT_DRAWN,
CONTINUOUS,
CATEGORICAL,
VALUE_ZW_DATA_TYPES,
DEFAULT_SPATIAL_INDEX_USE_WORKER,
DEFAULT_ANNOTATION_LINE_COLOR,
DEFAULT_ANNOTATION_LINE_WIDTH,
DEFAULT_ANNOTATION_HVLINE_LIMIT,
} from './constants';
import {
createRegl,
createTextureFromUrl,
dist,
getBBox,
isValidBBox,
isConditionalArray,
isPositiveNumber,
isStrictlyPositiveNumber,
isMultipleColors,
isPointInPolygon,
isString,
limit,
toRgba,
max,
min,
flipObj,
rgbBrightness,
clip,
toArrayOrientedPoints,
isHorizontalLine,
isVerticalLine,
isDomRect,
isRect,
isPolygon,
} from './utils';
import { version } from '../package.json';
const deprecations = {
showRecticle: 'showReticle',
recticleColor: 'reticleColor',
};
const checkDeprecations = (properties) => {
Object.keys(properties)
.filter((prop) => deprecations[prop])
.forEach((name) => {
console.warn(
`regl-scatterplot: the "${name}" property is deprecated. Please use "${deprecations[name]}" instead.`
);
properties[deprecations[name]] = properties[name];
delete properties[name];
});
};
const getEncodingType = (
type,
defaultValue,
{ allowSegment = false, allowDensity = false, allowInherit = false } = {}
) => {
// Z refers to the 3rd component of the RGBA value
if (Z_NAMES.has(type)) return 'valueZ';
// W refers to the 4th component of the RGBA value
if (W_NAMES.has(type)) return 'valueW';
if (type === 'segment') return allowSegment ? 'segment' : defaultValue;
if (type === 'density') return allowDensity ? 'density' : defaultValue;
if (type === 'inherit') return allowInherit ? 'inherit' : defaultValue;
return defaultValue;
};
const getEncodingIdx = (type) => {
switch (type) {
case 'valueZ':
return 2;
case 'valueW':
return 3;
default:
return null;
}
};
const createScatterplot = (
/** @type {Partial<import('./types').Properties>} */ initialProperties = {}
) => {
/** @type {import('pub-sub-es').PubSub<import('./types').Events>} */
const pubSub = createPubSub({
async: !initialProperties.syncEvents,
caseInsensitive: true,
});
const scratch = new Float32Array(16);
const pvm = new Float32Array(16);
const mousePosition = [0, 0];
checkDeprecations(initialProperties);
let {
renderer,
backgroundColor = DEFAULT_COLOR_BG,
backgroundImage = DEFAULT_BACKGROUND_IMAGE,
canvas = document.createElement('canvas'),
colorBy = DEFAULT_COLOR_BY,
deselectOnDblClick = DEFAULT_DESELECT_ON_DBL_CLICK,
deselectOnEscape = DEFAULT_DESELECT_ON_ESCAPE,
lassoColor = DEFAULT_LASSO_COLOR,
lassoLineWidth = DEFAULT_LASSO_LINE_WIDTH,
lassoMinDelay = DEFAULT_LASSO_MIN_DELAY,
lassoMinDist = DEFAULT_LASSO_MIN_DIST,
lassoClearEvent = DEFAULT_LASSO_CLEAR_EVENT,
lassoInitiator = DEFAULT_LASSO_INITIATOR,
lassoInitiatorParentElement = document.body,
lassoOnLongPress = DEFAULT_LASSO_ON_LONG_PRESS,
lassoLongPressTime = DEFAULT_LASSO_LONG_PRESS_TIME,
lassoLongPressAfterEffectTime = DEFAULT_LASSO_LONG_PRESS_AFTER_EFFECT_TIME,
lassoLongPressEffectDelay = DEFAULT_LASSO_LONG_PRESS_EFFECT_DELAY,
lassoLongPressRevertEffectTime = DEFAULT_LASSO_LONG_PRESS_REVERT_EFFECT_TIME,
keyMap = DEFAULT_KEY_MAP,
mouseMode = DEFAULT_MOUSE_MODE,
showReticle = DEFAULT_SHOW_RETICLE,
reticleColor = DEFAULT_RETICLE_COLOR,
pointColor = DEFAULT_COLOR_NORMAL,
pointColorActive = DEFAULT_COLOR_ACTIVE,
pointColorHover = DEFAULT_COLOR_HOVER,
showPointConnections = DEFAULT_SHOW_POINT_CONNECTIONS,
pointConnectionColor = DEFAULT_POINT_CONNECTION_COLOR_NORMAL,
pointConnectionColorActive = DEFAULT_POINT_CONNECTION_COLOR_ACTIVE,
pointConnectionColorHover = DEFAULT_POINT_CONNECTION_COLOR_HOVER,
pointConnectionColorBy = DEFAULT_POINT_CONNECTION_COLOR_BY,
pointConnectionOpacity = DEFAULT_POINT_CONNECTION_OPACITY,
pointConnectionOpacityBy = DEFAULT_POINT_CONNECTION_OPACITY_BY,
pointConnectionOpacityActive = DEFAULT_POINT_CONNECTION_OPACITY_ACTIVE,
pointConnectionSize = DEFAULT_POINT_CONNECTION_SIZE,
pointConnectionSizeActive = DEFAULT_POINT_CONNECTION_SIZE_ACTIVE,
pointConnectionSizeBy = DEFAULT_POINT_CONNECTION_SIZE_BY,
pointConnectionMaxIntPointsPerSegment = DEFAULT_POINT_CONNECTION_MAX_INT_POINTS_PER_SEGMENT,
pointConnectionTolerance = DEFAULT_POINT_CONNECTION_INT_POINTS_TOLERANCE,
pointSize = DEFAULT_POINT_SIZE,
pointSizeSelected = DEFAULT_POINT_SIZE_SELECTED,
pointSizeMouseDetection = DEFAULT_POINT_SIZE_MOUSE_DETECTION,
pointOutlineWidth = DEFAULT_POINT_OUTLINE_WIDTH,
opacity = AUTO,
opacityBy = DEFAULT_OPACITY_BY,
opacityByDensityFill = DEFAULT_OPACITY_BY_DENSITY_FILL,
opacityInactiveMax = DEFAULT_OPACITY_INACTIVE_MAX,
opacityInactiveScale = DEFAULT_OPACITY_INACTIVE_SCALE,
sizeBy = DEFAULT_SIZE_BY,
height = DEFAULT_HEIGHT,
width = DEFAULT_WIDTH,
annotationLineColor = DEFAULT_ANNOTATION_LINE_COLOR,
annotationLineWidth = DEFAULT_ANNOTATION_LINE_WIDTH,
annotationHVLineLimit = DEFAULT_ANNOTATION_HVLINE_LIMIT,
} = initialProperties;
let currentWidth = width === AUTO ? 1 : width;
let currentHeight = height === AUTO ? 1 : height;
// The following properties cannot be changed after the initialization
const {
performanceMode = DEFAULT_PERFORMANCE_MODE,
opacityByDensityDebounceTime = DEFAULT_OPACITY_BY_DENSITY_DEBOUNCE_TIME,
spatialIndexUseWorker = DEFAULT_SPATIAL_INDEX_USE_WORKER,
} = initialProperties;
// Same as renderer ||= createRenderer({ ... }) but avoids having to rely on
// https://babeljs.io/docs/en/babel-plugin-proposal-logical-assignment-operators
// eslint-disable-next-line no-unused-expressions
renderer ||
(renderer = createRenderer({
regl: initialProperties.regl,
gamma: initialProperties.gamma,
}));
backgroundColor = toRgba(backgroundColor, true);
lassoColor = toRgba(lassoColor, true);
reticleColor = toRgba(reticleColor, true);
let isDestroyed = false;
let backgroundColorBrightness = rgbBrightness(backgroundColor);
let camera;
/** @type {ReturnType<createLine>} */
let lasso;
/** @type {ReturnType<createLine>} */
let annotations;
let mouseDown = false;
let mouseDownTime = null;
let mouseDownPosition = [0, 0];
let mouseDownTimeout = -1;
/** @type{number[]} */
let selectedPoints = [];
/** @type{Set<number>} */
const selectedPointsSet = new Set();
/** @type{Set<number>} */
const selectedPointsConnectionSet = new Set();
let isPointsFiltered = false;
/** @type{Set<number>} */
const filteredPointsSet = new Set();
let points = [];
let numPoints = 0;
let numPointsInView = 0;
let lassoActive = false;
let lassoPointsCurr = [];
let spatialIndex;
let viewAspectRatio;
let dataAspectRatio =
initialProperties.aspectRatio || DEFAULT_DATA_ASPECT_RATIO;
let projectionLocal;
let projection;
let model;
let pointConnections;
let pointConnectionMap;
let computingPointConnectionCurves;
let reticleHLine;
let reticleVLine;
let computedPointSizeMouseDetection;
let keyActionMap = flipObj(keyMap);
let lassoInitiatorTimeout;
let topRightNdc;
let bottomLeftNdc;
let preventEventView = false;
let draw = true;
let drawReticleOnce = false;
let canvasObserver;
pointColor = isMultipleColors(pointColor) ? [...pointColor] : [pointColor];
pointColorActive = isMultipleColors(pointColorActive)
? [...pointColorActive]
: [pointColorActive];
pointColorHover = isMultipleColors(pointColorHover)
? [...pointColorHover]
: [pointColorHover];
pointColor = pointColor.map((color) => toRgba(color, true));
pointColorActive = pointColorActive.map((color) => toRgba(color, true));
pointColorHover = pointColorHover.map((color) => toRgba(color, true));
opacity =
!Array.isArray(opacity) && Number.isNaN(+opacity)
? pointColor[0][3]
: opacity;
opacity = isConditionalArray(opacity, isPositiveNumber, {
minLength: 1,
})
? [...opacity]
: [opacity];
pointSize = isConditionalArray(pointSize, isPositiveNumber, {
minLength: 1,
})
? [...pointSize]
: [pointSize];
let minPointScale = MIN_POINT_SIZE / pointSize[0];
if (pointConnectionColor === 'inherit') {
pointConnectionColor = [...pointColor];
} else {
pointConnectionColor = isMultipleColors(pointConnectionColor)
? [...pointConnectionColor]
: [pointConnectionColor];
pointConnectionColor = pointConnectionColor.map((color) =>
toRgba(color, true)
);
}
if (pointConnectionColorActive === 'inherit') {
pointConnectionColorActive = [...pointColorActive];
} else {
pointConnectionColorActive = isMultipleColors(pointConnectionColorActive)
? [...pointConnectionColorActive]
: [pointConnectionColorActive];
pointConnectionColorActive = pointConnectionColorActive.map((color) =>
toRgba(color, true)
);
}
if (pointConnectionColorHover === 'inherit') {
pointConnectionColorHover = [...pointColorHover];
} else {
pointConnectionColorHover = isMultipleColors(pointConnectionColorHover)
? [...pointConnectionColorHover]
: [pointConnectionColorHover];
pointConnectionColorHover = pointConnectionColorHover.map((color) =>
toRgba(color, true)
);
}
if (pointConnectionOpacity === 'inherit') {
pointConnectionOpacity = [...opacity];
} else {
pointConnectionOpacity = isConditionalArray(
pointConnectionOpacity,
isPositiveNumber,
{
minLength: 1,
}
)
? [...pointConnectionOpacity]
: [pointConnectionOpacity];
}
if (pointConnectionSize === 'inherit') {
pointConnectionSize = [...pointSize];
} else {
pointConnectionSize = isConditionalArray(
pointConnectionSize,
isPositiveNumber,
{
minLength: 1,
}
)
? [...pointConnectionSize]
: [pointConnectionSize];
}
colorBy = getEncodingType(colorBy, DEFAULT_COLOR_BY);
opacityBy = getEncodingType(opacityBy, DEFAULT_OPACITY_BY, {
allowDensity: true,
});
sizeBy = getEncodingType(sizeBy, DEFAULT_SIZE_BY);
pointConnectionColorBy = getEncodingType(
pointConnectionColorBy,
DEFAULT_POINT_CONNECTION_COLOR_BY,
{ allowSegment: true, allowInherit: true }
);
pointConnectionOpacityBy = getEncodingType(
pointConnectionOpacityBy,
DEFAULT_POINT_CONNECTION_OPACITY_BY,
{ allowSegment: true }
);
pointConnectionSizeBy = getEncodingType(
pointConnectionSizeBy,
DEFAULT_POINT_CONNECTION_SIZE_BY,
{ allowSegment: true }
);
let stateTex; // Stores the point texture holding x, y, category, and value
let prevStateTex; // Stores the previous point texture. Used for transitions
let tmpStateTex; // Stores a temporary point texture. Used for transitions
let tmpStateBuffer; // Temporary frame buffer
let stateTexRes = 0; // Width and height of the texture
let stateTexEps = 0; // Half a texel
let normalPointsIndexBuffer; // Buffer holding the indices pointing to the correct texel
let selectedPointsIndexBuffer; // Used for pointing to the selected texels
let hoveredPointIndexBuffer; // Used for pointing to the hovered texels
let cameraZoomTargetStart; // Stores the start (i.e., current) camera target for zooming
let cameraZoomTargetEnd; // Stores the end camera target for zooming
let cameraZoomDistanceStart; // Stores the start camera distance for zooming
let cameraZoomDistanceEnd; // Stores the end camera distance for zooming
let isTransitioning = false;
let transitionStartTime = null;
let transitionDuration;
let transitionEasing;
let preTransitionShowReticle = showReticle;
let colorTex; // Stores the point color texture
let colorTexRes = 0; // Width and height of the texture
let encodingTex; // Stores the point sizes and opacity values
let encodingTexRes = 0; // Width and height of the texture
let isViewChanged = false;
let isPointsDrawn = false;
let isAnnotationsDrawn = false;
let isMouseOverCanvasChecked = false;
let valueZDataType = CATEGORICAL;
let valueWDataType = CATEGORICAL;
/** @type{number|undefined} */
let hoveredPoint;
let isMouseInCanvas = false;
let xScale = initialProperties.xScale || null;
let yScale = initialProperties.yScale || null;
let xDomainStart = 0;
let xDomainSize = 0;
let yDomainStart = 0;
let yDomainSize = 0;
if (xScale) {
xDomainStart = xScale.domain()[0];
xDomainSize = xScale.domain()[1] - xScale.domain()[0];
xScale.range([0, currentWidth]);
}
if (yScale) {
yDomainStart = yScale.domain()[0];
yDomainSize = yScale.domain()[1] - yScale.domain()[0];
yScale.range([currentHeight, 0]);
}
const getNdcX = (x) => -1 + (x / currentWidth) * 2;
const getNdcY = (y) => 1 + (y / currentHeight) * -2;
// Get relative WebGL position
const getMouseGlPos = () => [
getNdcX(mousePosition[0]),
getNdcY(mousePosition[1]),
];
const getScatterGlPos = (xGl, yGl) => {
// Homogeneous vector
const v = [xGl, yGl, 1, 1];
// projection^-1 * view^-1 * model^-1 is the same as
// model * view^-1 * projection
const mvp = mat4.invert(
scratch,
mat4.multiply(
scratch,
projectionLocal,
mat4.multiply(scratch, camera.view, model)
)
);
// Translate vector
vec4.transformMat4(v, v, mvp);
return v.slice(0, 2);
};
const getPointSizeNdc = (pointSizeIncrease = 0) => {
// eslint-disable-next-line no-use-before-define
const pointScale = getPointScale();
// The height of the view in normalized device coordinates
const heightNdc = topRightNdc[1] - bottomLeftNdc[1];
// The size of a pixel in the current view in normalized device coordinates
const pxNdc = heightNdc / canvas.height;
// The scaled point size in normalized device coordinates
return (
(computedPointSizeMouseDetection * pointScale + pointSizeIncrease) * pxNdc
);
};
const getPoints = () => {
if (isPointsFiltered)
return points.filter((_, i) => filteredPointsSet.has(i));
return points;
};
const getPointsInBBox = (x0, y0, x1, y1) => {
const pointsInBBox = spatialIndex.range(x0, y0, x1, y1);
if (isPointsFiltered)
return pointsInBBox.filter((i) => filteredPointsSet.has(i));
return pointsInBBox;
};
const raycast = () => {
const [xGl, yGl] = getMouseGlPos();
const [xNdc, yNdc] = getScatterGlPos(xGl, yGl);
const pointSizeNdc = getPointSizeNdc(4);
// Get all points within a close range
const pointsInBBox = getPointsInBBox(
xNdc - pointSizeNdc,
yNdc - pointSizeNdc,
xNdc + pointSizeNdc,
yNdc + pointSizeNdc
);
// Find the closest point
let minDist = pointSizeNdc;
let clostestPoint = -1;
pointsInBBox.forEach((idx) => {
const [ptX, ptY] = points[idx];
const d = dist(ptX, ptY, xNdc, yNdc);
if (d < minDist) {
minDist = d;
clostestPoint = idx;
}
});
return clostestPoint;
};
const lassoExtend = (lassoPoints, lassoPointsFlat) => {
lassoPointsCurr = lassoPoints;
lasso.setPoints(lassoPointsFlat);
pubSub.publish('lassoExtend', { coordinates: lassoPoints });
};
const findPointsInLasso = (lassoPolygon) => {
// get the bounding box of the lasso selection...
const bBox = getBBox(lassoPolygon);
if (!isValidBBox(bBox)) return [];
// ...to efficiently preselect potentially selected points
const pointsInBBox = getPointsInBBox(...bBox);
// next we test each point in the bounding box if it is in the polygon too
const pointsInPolygon = [];
pointsInBBox.forEach((pointIdx) => {
if (isPointInPolygon(lassoPolygon, points[pointIdx]))
pointsInPolygon.push(pointIdx);
});
return pointsInPolygon;
};
const lassoClear = () => {
lassoPointsCurr = [];
if (lasso) lasso.clear();
};
const hasPointConnections = (point) => point && point.length > 4;
const setPointConnectionColorState = (pointIdxs, stateIndex) => {
if (
computingPointConnectionCurves ||
!showPointConnections ||
!hasPointConnections(points[pointIdxs[0]])
)
return;
const isNormal = stateIndex === 0;
const lineIdCacher =
stateIndex === 1
? (lineId) => selectedPointsConnectionSet.add(lineId)
: identity;
// Get line IDs
const lineIds = Object.keys(
pointIdxs.reduce((ids, pointIdx) => {
const point = points[pointIdx];
const isStruct = Array.isArray(point[4]);
const lineId = isStruct ? point[4][0] : point[4];
ids[lineId] = true;
return ids;
}, {})
);
const buffer = pointConnections.getData().opacities;
lineIds
.filter((lineId) => !selectedPointsConnectionSet.has(+lineId))
.forEach((lineId) => {
const index = pointConnectionMap[lineId][0];
const numPointPerLine = pointConnectionMap[lineId][2];
const pointOffset = pointConnectionMap[lineId][3];
const bufferStart = index * 4 + pointOffset * 2;
const bufferEnd = bufferStart + numPointPerLine * 2 + 4;
// eslint-disable-next-line no-underscore-dangle
if (buffer.__original__ === undefined) {
// eslint-disable-next-line no-underscore-dangle
buffer.__original__ = buffer.slice();
}
for (let i = bufferStart; i < bufferEnd; i++) {
// buffer[i] = Math.floor(buffer[i] / 4) * 4 + stateIndex;
buffer[i] = isNormal
? // eslint-disable-next-line no-underscore-dangle
buffer.__original__[i]
: pointConnectionOpacityActive;
}
lineIdCacher(lineId);
});
pointConnections.getBuffer().opacities.subdata(buffer, 0);
};
const indexToStateTexCoord = (index) => [
(index % stateTexRes) / stateTexRes + stateTexEps,
Math.floor(index / stateTexRes) / stateTexRes + stateTexEps,
];
const isPointsFilteredOut = (pointIdx) =>
isPointsFiltered && !filteredPointsSet.has(pointIdx);
const deselect = ({ preventEvent = false } = {}) => {
if (lassoClearEvent === LASSO_CLEAR_ON_DESELECT) lassoClear();
if (selectedPoints.length) {
if (!preventEvent) pubSub.publish('deselect');
selectedPointsConnectionSet.clear();
setPointConnectionColorState(selectedPoints, 0);
selectedPoints = [];
selectedPointsSet.clear();
draw = true;
}
};
/**
* Select and highlight a set of points
* @param {number | number[]} pointIdxs
* @param {import('./types').ScatterplotMethodOptions['select']}
*/
const select = (pointIdxs, { merge = false, preventEvent = false } = {}) => {
const newSelectedPoints = Array.isArray(pointIdxs)
? pointIdxs
: [pointIdxs];
const currSelectedPoints = [...selectedPoints];
if (merge) {
selectedPoints = unionIntegers(selectedPoints, newSelectedPoints);
if (currSelectedPoints.length === selectedPoints.length) {
draw = true;
return;
}
} else {
// Unset previously highlight point connections
if (selectedPoints && selectedPoints.length)
setPointConnectionColorState(selectedPoints, 0);
if (currSelectedPoints.length > 0 && newSelectedPoints.length === 0) {
deselect({ preventEvent });
return;
}
selectedPoints = newSelectedPoints;
}
if (hasSameElements(currSelectedPoints, selectedPoints)) {
draw = true;
return;
}
const selectedPointsBuffer = [];
selectedPointsSet.clear();
selectedPointsConnectionSet.clear();
for (let i = selectedPoints.length - 1; i >= 0; i--) {
const pointIdx = selectedPoints[i];
if (
pointIdx < 0 ||
pointIdx >= numPoints ||
isPointsFilteredOut(pointIdx)
) {
// Remove invalid selected points
selectedPoints.splice(i, 1);
continue;
}
selectedPointsSet.add(pointIdx);
selectedPointsBuffer.push.apply(
selectedPointsBuffer,
indexToStateTexCoord(pointIdx)
);
}
selectedPointsIndexBuffer({
usage: 'dynamic',
type: 'float',
data: selectedPointsBuffer,
});
setPointConnectionColorState(selectedPoints, 1);
if (!preventEvent) pubSub.publish('select', { points: selectedPoints });
draw = true;
};
/**
* @param {number} point
* @param {import('./types').ScatterplotMethodOptions['hover']} options
*/
const hover = (
point,
{ showReticleOnce = false, preventEvent = false } = {}
) => {
let needsRedraw = false;
const isFilteredOut = isPointsFiltered && !filteredPointsSet.has(point);
if (!isFilteredOut && point >= 0 && point < numPoints) {
needsRedraw = true;
const oldHoveredPoint = hoveredPoint;
const newHoveredPoint = point !== hoveredPoint;
if (
+oldHoveredPoint >= 0 &&
newHoveredPoint &&
!selectedPointsSet.has(oldHoveredPoint)
) {
setPointConnectionColorState([oldHoveredPoint], 0);
}
hoveredPoint = point;
hoveredPointIndexBuffer.subdata(indexToStateTexCoord(point));
if (!selectedPointsSet.has(point))
setPointConnectionColorState([point], 2);
if (newHoveredPoint && !preventEvent)
pubSub.publish('pointover', hoveredPoint);
} else {
needsRedraw = +hoveredPoint >= 0;
if (needsRedraw) {
if (!selectedPointsSet.has(hoveredPoint)) {
setPointConnectionColorState([hoveredPoint], 0);
}
if (!preventEvent) {
pubSub.publish('pointout', hoveredPoint);
}
}
hoveredPoint = undefined;
}
if (needsRedraw) {
draw = true;
drawReticleOnce = showReticleOnce;
}
};
const getRelativeMousePosition = (event) => {
const rect = canvas.getBoundingClientRect();
mousePosition[0] = event.clientX - rect.left;
mousePosition[1] = event.clientY - rect.top;
return [...mousePosition];
};
const lassoStart = () => {
// Fix camera for the lasso selection
camera.config({ isFixed: true });
mouseDown = true;
lassoActive = true;
lassoClear();
if (mouseDownTimeout >= 0) {
clearTimeout(mouseDownTimeout);
mouseDownTimeout = -1;
}
pubSub.publish('lassoStart');
};
const lassoEnd = (lassoPoints, lassoPointsFlat, { merge = false } = {}) => {
camera.config({ isFixed: false });
lassoPointsCurr = [...lassoPoints];
const pointsInLasso = findPointsInLasso(lassoPointsFlat);
select(pointsInLasso, { merge });
pubSub.publish('lassoEnd', {
coordinates: lassoPointsCurr,
});
if (lassoClearEvent === LASSO_CLEAR_ON_END) lassoClear();
};
const lassoManager = createLassoManager(canvas, {
onStart: lassoStart,
onDraw: lassoExtend,
onEnd: lassoEnd,
enableInitiator: lassoInitiator,
initiatorParentElement: lassoInitiatorParentElement,
pointNorm: ([x, y]) => getScatterGlPos(getNdcX(x), getNdcY(y)),
});
const checkLassoMode = () => mouseMode === MOUSE_MODE_LASSO;
const checkModKey = (event, action) => {
switch (keyActionMap[action]) {
case KEY_ALT:
return event.altKey;
case KEY_CMD:
return event.metaKey;
case KEY_CTRL:
return event.ctrlKey;
case KEY_META:
return event.metaKey;
case KEY_SHIFT:
return event.shiftKey;
default:
return false;
}
};
const checkIfMouseIsOverCanvas = (event) =>
document
.elementsFromPoint(event.clientX, event.clientY)
.some((element) => element === canvas);
const mouseDownHandler = (event) => {
if (!isPointsDrawn || event.buttons !== 1) return;
mouseDown = true;
mouseDownTime = performance.now();
mouseDownPosition = getRelativeMousePosition(event);
lassoActive = checkLassoMode() || checkModKey(event, KEY_ACTION_LASSO);
if (!lassoActive && lassoOnLongPress) {
lassoManager.showLongPressIndicator(event.clientX, event.clientY, {
time: lassoLongPressTime,
extraTime: lassoLongPressAfterEffectTime,
delay: lassoLongPressEffectDelay,
});
mouseDownTimeout = setTimeout(() => {
mouseDownTimeout = -1;
lassoActive = true;
}, lassoLongPressTime);
}
};
const mouseUpHandler = (event) => {
if (!isPointsDrawn) return;
mouseDown = false;
if (mouseDownTimeout >= 0) {
clearTimeout(mouseDownTimeout);
mouseDownTimeout = -1;
}
if (lassoActive) {
event.preventDefault();
lassoActive = false;
lassoManager.end({
merge: checkModKey(event, KEY_ACTION_MERGE),
});
}
if (lassoOnLongPress) {
lassoManager.hideLongPressIndicator({
time: lassoLongPressRevertEffectTime,
});
}
};
const mouseClickHandler = (event) => {
if (!isPointsDrawn) return;
event.preventDefault();
const currentMousePosition = getRelativeMousePosition(event);
if (dist(...currentMousePosition, ...mouseDownPosition) >= lassoMinDist)
return;
const clickTime = performance.now() - mouseDownTime;
if (!lassoInitiator || clickTime < LONG_CLICK_TIME) {
// If the user clicked normally (i.e., fast) we'll only show the lasso
// initiator if the use click into the void
const clostestPoint = raycast();
if (clostestPoint >= 0) {
if (
selectedPoints.length &&
lassoClearEvent === LASSO_CLEAR_ON_DESELECT
) {
// Special case where we silently "deselect" the previous points by
// overriding the selected points. Hence, we need to clear the lasso.
lassoClear();
}
select([clostestPoint], {
merge: checkModKey(event, KEY_ACTION_MERGE),
});
} else if (!lassoInitiatorTimeout) {
// We'll also wait to make sure the user didn't double click
lassoInitiatorTimeout = setTimeout(() => {
lassoInitiatorTimeout = null;
lassoManager.showInitiator(event);
}, SINGLE_CLICK_DELAY);
}
}
};
const mouseDblClickHandler = (event) => {
lassoManager.hideInitiator();
if (lassoInitiatorTimeout) {
clearTimeout(lassoInitiatorTimeout);
lassoInitiatorTimeout = null;
}
if (deselectOnDblClick) {
event.preventDefault();
deselect();
}
};
const mouseMoveHandler = (event) => {
if (!isMouseOverCanvasChecked) {
isMouseInCanvas = checkIfMouseIsOverCanvas(event);
isMouseOverCanvasChecked = true;
}