-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
layer.ts
1336 lines (1153 loc) · 45 KB
/
layer.ts
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
// deck.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
/* eslint-disable react/no-direct-mutation-state */
import {Buffer, TypedArray} from '@luma.gl/core';
import {WebGLDevice} from '@luma.gl/webgl';
import {COORDINATE_SYSTEM} from './constants';
import AttributeManager from './attribute/attribute-manager';
import UniformTransitionManager from './uniform-transition-manager';
import {diffProps, validateProps} from '../lifecycle/props';
import {LIFECYCLE, Lifecycle} from '../lifecycle/constants';
import {count} from '../utils/count';
import log from '../utils/log';
import debug from '../debug/index';
import assert from '../utils/assert';
import memoize from '../utils/memoize';
import {mergeShaders} from '../utils/shader';
import {projectPosition, getWorldPosition} from '../shaderlib/project/project-functions';
import typedArrayManager from '../utils/typed-array-manager';
import Component from '../lifecycle/component';
import LayerState, {ChangeFlags} from './layer-state';
import {worldToPixels} from '@math.gl/web-mercator';
import {load} from '@loaders.gl/core';
import type {Loader} from '@loaders.gl/loader-utils';
import type {CoordinateSystem} from './constants';
import type Attribute from './attribute/attribute';
import type {Model} from '@luma.gl/engine';
import type {PickingInfo, GetPickingInfoParams} from './picking/pick-info';
import type Viewport from '../viewports/viewport';
import type {NumericArray} from '../types/types';
import type {DefaultProps} from '../lifecycle/prop-types';
import type {LayerData, LayerProps} from '../types/layer-props';
import type {LayerContext} from './layer-manager';
import type {BinaryAttribute} from './attribute/attribute';
import {RenderPass} from '@luma.gl/core';
import {PickingProps} from '@luma.gl/shadertools';
const TRACE_CHANGE_FLAG = 'layer.changeFlag';
const TRACE_INITIALIZE = 'layer.initialize';
const TRACE_UPDATE = 'layer.update';
const TRACE_FINALIZE = 'layer.finalize';
const TRACE_MATCHED = 'layer.matched';
const MAX_PICKING_COLOR_CACHE_SIZE = 2 ** 24 - 1;
const EMPTY_ARRAY = Object.freeze([]);
// Only compare the same two viewports once
const areViewportsEqual = memoize(
({oldViewport, viewport}: {oldViewport: Viewport; viewport: Viewport}): boolean => {
return oldViewport.equals(viewport);
}
);
let pickingColorCache = new Uint8ClampedArray(0);
const defaultProps: DefaultProps<LayerProps> = {
// data: Special handling for null, see below
data: {type: 'data', value: EMPTY_ARRAY, async: true},
dataComparator: {type: 'function', value: null, optional: true},
_dataDiff: {
type: 'function',
// @ts-ignore __diff is not defined on data
value: data => data && data.__diff,
optional: true
},
dataTransform: {type: 'function', value: null, optional: true},
onDataLoad: {type: 'function', value: null, optional: true},
onError: {type: 'function', value: null, optional: true},
fetch: {
type: 'function',
value: <LayerT extends Layer>(
url: string,
{
propName,
layer,
loaders,
loadOptions,
signal
}: {
propName: string;
layer: LayerT;
loaders?: Loader[];
loadOptions?: any;
signal?: AbortSignal;
}
) => {
const {resourceManager} = layer.context;
loadOptions = loadOptions || layer.getLoadOptions();
loaders = loaders || layer.props.loaders;
if (signal) {
loadOptions = {
...loadOptions,
fetch: {
...loadOptions?.fetch,
signal
}
};
}
let inResourceManager = resourceManager.contains(url);
if (!inResourceManager && !loadOptions) {
// If there is no layer-specific load options, then attempt to cache this resource in the data manager
resourceManager.add({resourceId: url, data: load(url, loaders), persistent: false});
inResourceManager = true;
}
if (inResourceManager) {
return resourceManager.subscribe({
resourceId: url,
onChange: data => layer.internalState?.reloadAsyncProp(propName, data),
consumerId: layer.id,
requestId: propName
});
}
return load(url, loaders, loadOptions);
}
},
updateTriggers: {}, // Update triggers: a core change detection mechanism in deck.gl
visible: true,
pickable: false,
opacity: {type: 'number', min: 0, max: 1, value: 1},
operation: 'draw',
onHover: {type: 'function', value: null, optional: true},
onClick: {type: 'function', value: null, optional: true},
onDragStart: {type: 'function', value: null, optional: true},
onDrag: {type: 'function', value: null, optional: true},
onDragEnd: {type: 'function', value: null, optional: true},
coordinateSystem: COORDINATE_SYSTEM.DEFAULT,
coordinateOrigin: {type: 'array', value: [0, 0, 0], compare: true},
modelMatrix: {type: 'array', value: null, compare: true, optional: true},
wrapLongitude: false,
positionFormat: 'XYZ',
colorFormat: 'RGBA',
parameters: {type: 'object', value: {}, optional: true, compare: 2},
loadOptions: {type: 'object', value: null, optional: true, ignore: true},
transitions: null,
extensions: [],
loaders: {type: 'array', value: [], optional: true, ignore: true},
// Offset depth based on layer index to avoid z-fighting.
// Negative values pull layer towards the camera
// https://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm
getPolygonOffset: {
type: 'function',
value: ({layerIndex}) => [0, -layerIndex * 100]
},
// Selection/Highlighting
highlightedObjectIndex: null,
autoHighlight: false,
highlightColor: {type: 'accessor', value: [0, 0, 128, 128]}
};
export type UpdateParameters<LayerT extends Layer> = {
props: LayerT['props'];
oldProps: LayerT['props'];
context: LayerContext;
changeFlags: ChangeFlags;
};
type DrawOptions = {
renderPass: RenderPass;
shaderModuleProps: any;
uniforms: any;
parameters: any;
context: LayerContext;
};
type SharedLayerState = {
[key: string]: unknown;
};
export default abstract class Layer<PropsT extends {} = {}> extends Component<
PropsT & Required<LayerProps>
> {
static defaultProps: DefaultProps = defaultProps;
static layerName: string = 'Layer';
static override get componentName() {
return Object.prototype.hasOwnProperty.call(this, 'layerName') ? this.layerName : '';
}
internalState: LayerState<this> | null = null;
lifecycle: Lifecycle = LIFECYCLE.NO_STATE; // Helps track and debug the life cycle of the layers
// context and state can technically be null before a layer is initialized/matched.
// However, they are most extensively accessed in a layer's lifecycle methods, where they are always defined.
// Checking for null state constantly in layer implementation is unnecessarily verbose.
context!: LayerContext; // Will reference layer manager's context, contains state shared by layers
state!: SharedLayerState; // Will be set to the shared layer state object during layer matching
parent: Layer | null = null;
get root(): Layer {
// eslint-disable-next-line
let layer: Layer = this;
while (layer.parent) {
layer = layer.parent;
}
return layer;
}
toString(): string {
const className = (this.constructor as typeof Layer).layerName || this.constructor.name;
return `${className}({id: '${this.props.id}'})`;
}
// Public API for users
/** Projects a point with current view state from the current layer's coordinate system to screen */
project(xyz: number[]): number[] {
assert(this.internalState);
const viewport = this.internalState.viewport || this.context.viewport;
const worldPosition = getWorldPosition(xyz, {
viewport,
modelMatrix: this.props.modelMatrix,
coordinateOrigin: this.props.coordinateOrigin,
coordinateSystem: this.props.coordinateSystem
});
const [x, y, z] = worldToPixels(worldPosition, viewport.pixelProjectionMatrix);
return xyz.length === 2 ? [x, y] : [x, y, z];
}
/** Unprojects a screen pixel to the current view's default coordinate system
Note: this does not reverse `project`. */
unproject(xy: number[]): number[] {
assert(this.internalState);
const viewport = this.internalState.viewport || this.context.viewport;
return viewport.unproject(xy);
}
/** Projects a point with current view state from the current layer's coordinate system to the world space */
projectPosition(
xyz: number[],
params?: {
/** The viewport to use */
viewport?: Viewport;
/** The coordinate system that the supplied position is in. Default to the same as `coordinateSystem`. */
fromCoordinateSystem?: CoordinateSystem;
/** The coordinate origin that the supplied position is in. Default to the same as `coordinateOrigin`. */
fromCoordinateOrigin?: [number, number, number];
/** Whether to apply offset mode automatically as does the project shader module.
* Offset mode places the origin of the common space at the given viewport's center. It is used in some use cases
* to improve precision in the vertex shader due to the fp32 float limitation.
* Use `autoOffset:false` if the returned position should not be dependent on the current viewport.
* Default `true` */
autoOffset?: boolean;
}
): [number, number, number] {
assert(this.internalState);
const viewport = this.internalState.viewport || this.context.viewport;
return projectPosition(xyz, {
viewport,
modelMatrix: this.props.modelMatrix,
coordinateOrigin: this.props.coordinateOrigin,
coordinateSystem: this.props.coordinateSystem,
...params
});
}
// Public API for custom layer implementation
/** `true` if this layer renders other layers */
get isComposite(): boolean {
return false;
}
/** `true` if the layer renders to screen */
get isDrawable(): boolean {
return true;
}
/** Updates selected state members and marks the layer for redraw */
setState(partialState: any): void {
this.setChangeFlags({stateChanged: true});
Object.assign(this.state, partialState);
this.setNeedsRedraw();
}
/** Sets the redraw flag for this layer, will trigger a redraw next animation frame */
setNeedsRedraw(): void {
if (this.internalState) {
this.internalState.needsRedraw = true;
}
}
/** Mark this layer as needs a deep update */
setNeedsUpdate() {
if (this.internalState) {
this.context.layerManager.setNeedsUpdate(String(this));
this.internalState.needsUpdate = true;
}
}
/** Returns true if all async resources are loaded */
get isLoaded(): boolean {
return this.internalState ? !this.internalState.isAsyncPropLoading() : false;
}
/** Returns true if using shader-based WGS84 longitude wrapping */
get wrapLongitude(): boolean {
return this.props.wrapLongitude;
}
/** @deprecated Returns true if the layer is visible in the picking pass */
isPickable(): boolean {
return this.props.pickable && this.props.visible;
}
/** Returns an array of models used by this layer, can be overriden by layer subclass */
getModels(): Model[] {
const state = this.state as {
models?: Model[];
model: Model;
};
return (state && (state.models || (state.model && [state.model]))) || [];
}
/** Update shader input parameters */
setShaderModuleProps(...props: Parameters<Model['shaderInputs']['setProps']>): void {
for (const model of this.getModels()) {
model.shaderInputs.setProps(...props);
}
}
/** Returns the attribute manager of this layer */
getAttributeManager(): AttributeManager | null {
return this.internalState && this.internalState.attributeManager;
}
/** Returns the most recent layer that matched to this state
(When reacting to an async event, this layer may no longer be the latest) */
getCurrentLayer(): Layer<PropsT> | null {
return this.internalState && this.internalState.layer;
}
/** Returns the default parse options for async props */
getLoadOptions(): any {
return this.props.loadOptions;
}
use64bitPositions(): boolean {
const {coordinateSystem} = this.props;
return (
coordinateSystem === COORDINATE_SYSTEM.DEFAULT ||
coordinateSystem === COORDINATE_SYSTEM.LNGLAT ||
coordinateSystem === COORDINATE_SYSTEM.CARTESIAN
);
}
// Event handling
onHover(info: PickingInfo, pickingEvent): boolean {
if (this.props.onHover) {
return this.props.onHover(info, pickingEvent) || false;
}
return false;
}
onClick(info: PickingInfo, pickingEvent): boolean {
if (this.props.onClick) {
return this.props.onClick(info, pickingEvent) || false;
}
return false;
}
// Returns the picking color that doesn't match any subfeature
// Use if some graphics do not belong to any pickable subfeature
// @return {Array} - a black color
nullPickingColor() {
return [0, 0, 0];
}
// Returns the picking color that doesn't match any subfeature
// Use if some graphics do not belong to any pickable subfeature
encodePickingColor(i, target: number[] = []): [number, number, number] {
target[0] = (i + 1) & 255;
target[1] = ((i + 1) >> 8) & 255;
target[2] = (((i + 1) >> 8) >> 8) & 255;
return target as [number, number, number];
}
// Returns the index corresponding to a picking color that doesn't match any subfeature
// @param {Uint8Array} color - color array to be decoded
// @return {Array} - the decoded picking color
decodePickingColor(color) {
assert(color instanceof Uint8Array);
const [i1, i2, i3] = color;
// 1 was added to seperate from no selection
const index = i1 + i2 * 256 + i3 * 65536 - 1;
return index;
}
/** Deduces number of instances. Intention is to support:
- Explicit setting of numInstances
- Auto-deduction for ES6 containers that define a size member
- Auto-deduction for Classic Arrays via the built-in length attribute
- Auto-deduction via arrays */
getNumInstances(): number {
// First Check if app has provided an explicit value
if (Number.isFinite(this.props.numInstances)) {
return this.props.numInstances as number;
}
// Second check if the layer has set its own value
if (this.state && this.state.numInstances !== undefined) {
return this.state.numInstances as number;
}
// Use container library to get a count for any ES6 container or object
return count(this.props.data);
}
/** Buffer layout describes how many attribute values are packed for each data object
The default (null) is one value each object.
Some data formats (e.g. paths, polygons) have various length. Their buffer layout
is in the form of [L0, L1, L2, ...] */
getStartIndices(): NumericArray | null {
// First Check if startIndices is provided as an explicit value
if (this.props.startIndices) {
return this.props.startIndices;
}
// Second check if the layer has set its own value
if (this.state && this.state.startIndices) {
return this.state.startIndices as NumericArray;
}
return null;
}
// Default implementation
getBounds(): [number[], number[]] | null {
return this.getAttributeManager()?.getBounds(['positions', 'instancePositions']);
}
// / LIFECYCLE METHODS - overridden by the layer subclasses
/** Called once to set up the initial state. Layers can create WebGL resources here. */
abstract initializeState(context: LayerContext): void;
getShaders(shaders: any): any {
shaders = mergeShaders(shaders, {
disableWarnings: true,
modules: this.context.defaultShaderModules
});
for (const extension of this.props.extensions) {
shaders = mergeShaders(shaders, extension.getShaders.call(this, extension));
}
return shaders;
}
/** Controls if updateState should be called. By default returns true if any prop has changed */
shouldUpdateState(params: UpdateParameters<Layer<PropsT>>): boolean {
return params.changeFlags.propsOrDataChanged;
}
/** Default implementation, all attributes will be invalidated and updated when data changes */
// eslint-disable-next-line complexity
updateState(params: UpdateParameters<Layer<PropsT>>): void {
const attributeManager = this.getAttributeManager();
const {dataChanged} = params.changeFlags;
if (dataChanged && attributeManager) {
if (Array.isArray(dataChanged)) {
// is partial update
for (const dataRange of dataChanged) {
attributeManager.invalidateAll(dataRange);
}
} else {
attributeManager.invalidateAll();
}
}
// Enable/disable picking buffer
if (attributeManager) {
const {props} = params;
const hasPickingBuffer = this.internalState!.hasPickingBuffer;
const needsPickingBuffer =
Number.isInteger(props.highlightedObjectIndex) ||
props.pickable ||
props.extensions.some(extension => extension.getNeedsPickingBuffer.call(this, extension));
// Only generate picking buffer if needed
if (hasPickingBuffer !== needsPickingBuffer) {
this.internalState!.hasPickingBuffer = needsPickingBuffer;
const {pickingColors, instancePickingColors} = attributeManager.attributes;
const pickingColorsAttribute = pickingColors || instancePickingColors;
if (pickingColorsAttribute) {
if (needsPickingBuffer && pickingColorsAttribute.constant) {
pickingColorsAttribute.constant = false;
attributeManager.invalidate(pickingColorsAttribute.id);
}
if (!pickingColorsAttribute.value && !needsPickingBuffer) {
pickingColorsAttribute.constant = true;
pickingColorsAttribute.value = [0, 0, 0];
}
}
}
}
}
/** Called once when layer is no longer matched and state will be discarded. Layers can destroy WebGL resources here. */
finalizeState(context: LayerContext): void {
for (const model of this.getModels()) {
model.destroy();
}
const attributeManager = this.getAttributeManager();
if (attributeManager) {
attributeManager.finalize();
}
if (this.context) {
this.context.resourceManager.unsubscribe({consumerId: this.id});
}
if (this.internalState) {
this.internalState.uniformTransitions.clear();
this.internalState.finalize();
}
}
// If state has a model, draw it with supplied uniforms
draw(opts: DrawOptions) {
for (const model of this.getModels()) {
model.draw(opts.renderPass);
}
}
// called to populate the info object that is passed to the event handler
// @return null to cancel event
getPickingInfo({info, mode, sourceLayer}: GetPickingInfoParams) {
const {index} = info;
if (index >= 0) {
// If props.data is an indexable array, get the object
if (Array.isArray(this.props.data)) {
info.object = this.props.data[index];
}
}
return info;
}
// END LIFECYCLE METHODS
// / INTERNAL METHODS - called by LayerManager, DeckRenderer and DeckPicker
/** (Internal) Propagate an error event through the system */
raiseError(error: Error, message: string): void {
if (message) {
// Duplicating error message for backward compatibility, see #7986
// TODO - revisit in v9
error = new Error(`${message}: ${error.message}`, {cause: error});
}
if (!this.props.onError?.(error)) {
this.context?.onError?.(error, this);
}
}
/** (Internal) Checks if this layer needs redraw */
getNeedsRedraw(
opts: {
/** Reset redraw flags to false after the check */
clearRedrawFlags: boolean;
} = {clearRedrawFlags: false}
): string | false {
return this._getNeedsRedraw(opts);
}
/** (Internal) Checks if this layer needs a deep update */
needsUpdate(): boolean {
if (!this.internalState) {
return false;
}
// Call subclass lifecycle method
return (
this.internalState.needsUpdate ||
this.hasUniformTransition() ||
this.shouldUpdateState(this._getUpdateParams())
);
// End lifecycle method
}
/** Checks if this layer has ongoing uniform transition */
hasUniformTransition(): boolean {
return this.internalState?.uniformTransitions.active || false;
}
/** Called when this layer is rendered into the given viewport */
activateViewport(viewport: Viewport): void {
if (!this.internalState) {
return;
}
const oldViewport = this.internalState.viewport;
this.internalState.viewport = viewport;
if (!oldViewport || !areViewportsEqual({oldViewport, viewport})) {
this.setChangeFlags({viewportChanged: true});
if (this.isComposite) {
if (this.needsUpdate()) {
// Composite layers may add/remove sublayers on viewport change
// Because we cannot change the layers list during a draw cycle, we don't want to update sublayers right away
// This will not call update immediately, but mark the layerManager as needs update on the next frame
this.setNeedsUpdate();
}
} else {
this._update();
}
}
}
/** Default implementation of attribute invalidation, can be redefined */
protected invalidateAttribute(name = 'all'): void {
const attributeManager = this.getAttributeManager();
if (!attributeManager) {
return;
}
if (name === 'all') {
attributeManager.invalidateAll();
} else {
attributeManager.invalidate(name);
}
}
/** Send updated attributes to the WebGL model */
protected updateAttributes(changedAttributes: {[id: string]: Attribute}) {
// If some buffer layout changed
let bufferLayoutChanged = false;
for (const id in changedAttributes) {
if (changedAttributes[id].layoutChanged()) {
bufferLayoutChanged = true;
}
}
for (const model of this.getModels()) {
this._setModelAttributes(model, changedAttributes, bufferLayoutChanged);
}
}
/** Recalculate any attributes if needed */
protected _updateAttributes(): void {
const attributeManager = this.getAttributeManager();
if (!attributeManager) {
return;
}
const props = this.props;
// Figure out data length
const numInstances = this.getNumInstances();
const startIndices = this.getStartIndices();
attributeManager.update({
data: props.data,
numInstances,
startIndices,
props,
transitions: props.transitions,
// @ts-ignore (TS2339) property attribute is not present on some acceptable data types
buffers: props.data.attributes,
context: this
});
const changedAttributes = attributeManager.getChangedAttributes({clearChangedFlags: true});
this.updateAttributes(changedAttributes);
}
/** Update attribute transitions. This is called in drawLayer, no model updates required. */
private _updateAttributeTransition() {
const attributeManager = this.getAttributeManager();
if (attributeManager) {
attributeManager.updateTransition();
}
}
/** Update uniform (prop) transitions. This is called in updateState, may result in model updates. */
private _updateUniformTransition(): Layer<PropsT>['props'] {
// @ts-ignore (TS2339) internalState is alwasy defined when this method is called
const {uniformTransitions} = this.internalState;
if (uniformTransitions.active) {
// clone props
const propsInTransition = uniformTransitions.update();
const props = Object.create(this.props);
for (const key in propsInTransition) {
Object.defineProperty(props, key, {value: propsInTransition[key]});
}
return props;
}
return this.props;
}
/** Updater for the automatically populated instancePickingColors attribute */
protected calculateInstancePickingColors(
attribute: Attribute,
{numInstances}: {numInstances: number}
) {
if (attribute.constant) {
return;
}
// calculateInstancePickingColors always generates the same sequence.
// pickingColorCache saves the largest generated sequence for reuse
const cacheSize = Math.floor(pickingColorCache.length / 4);
// Record when using the picking buffer cache, so that layers can always point at the most recently allocated cache
// @ts-ignore (TS2531) internalState is always defined when this method is called
this.internalState.usesPickingColorCache = true;
if (cacheSize < numInstances) {
if (numInstances > MAX_PICKING_COLOR_CACHE_SIZE) {
log.warn(
'Layer has too many data objects. Picking might not be able to distinguish all objects.'
)();
}
pickingColorCache = typedArrayManager.allocate(pickingColorCache, numInstances, {
size: 4,
copy: true,
maxCount: Math.max(numInstances, MAX_PICKING_COLOR_CACHE_SIZE)
});
// If the attribute is larger than the cache, resize the cache and populate the missing chunk
const newCacheSize = Math.floor(pickingColorCache.length / 4);
const pickingColor: [number, number, number] = [0, 0, 0];
for (let i = cacheSize; i < newCacheSize; i++) {
this.encodePickingColor(i, pickingColor);
pickingColorCache[i * 4 + 0] = pickingColor[0];
pickingColorCache[i * 4 + 1] = pickingColor[1];
pickingColorCache[i * 4 + 2] = pickingColor[2];
pickingColorCache[i * 4 + 3] = 0;
}
}
attribute.value = pickingColorCache.subarray(0, numInstances * 4);
}
/** Apply changed attributes to model */
protected _setModelAttributes(
model: Model,
changedAttributes: {
[id: string]: Attribute;
},
bufferLayoutChanged = false
) {
if (!Object.keys(changedAttributes).length) {
return;
}
if (bufferLayoutChanged) {
// AttributeManager is always defined when this method is called
const attributeManager = this.getAttributeManager()!;
model.setBufferLayout(attributeManager.getBufferLayouts(model));
// All attributes must be reset after buffer layout change
changedAttributes = attributeManager.getAttributes();
}
// @ts-ignore luma.gl type issue
const excludeAttributes = model.userData?.excludeAttributes || {};
const attributeBuffers: Record<string, Buffer> = {};
const constantAttributes: Record<string, TypedArray> = {};
for (const name in changedAttributes) {
if (excludeAttributes[name]) {
continue;
}
const values = changedAttributes[name].getValue();
for (const attributeName in values) {
const value = values[attributeName];
if (value instanceof Buffer) {
if (changedAttributes[name].settings.isIndexed) {
model.setIndexBuffer(value);
} else {
attributeBuffers[attributeName] = value;
}
} else if (value) {
constantAttributes[attributeName] = value;
}
}
}
// TODO - update buffer map?
model.setAttributes(attributeBuffers);
model.setConstantAttributes(constantAttributes);
}
/** (Internal) Sets the picking color at the specified index to null picking color. Used for multi-depth picking.
This method may be overriden by layer implementations */
disablePickingIndex(objectIndex: number) {
const data = this.props.data as LayerData<any>;
if (!('attributes' in data)) {
this._disablePickingIndex(objectIndex);
return;
}
// @ts-ignore (TS2531) this method is only called internally with attributeManager defined
const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;
const colors = pickingColors || instancePickingColors;
const externalColorAttribute =
colors && data.attributes && (data.attributes[colors.id] as BinaryAttribute);
if (externalColorAttribute && externalColorAttribute.value) {
const values = externalColorAttribute.value;
const objectColor = this.encodePickingColor(objectIndex);
for (let index = 0; index < data.length; index++) {
const i = colors.getVertexOffset(index);
if (
values[i] === objectColor[0] &&
values[i + 1] === objectColor[1] &&
values[i + 2] === objectColor[2]
) {
this._disablePickingIndex(index);
}
}
} else {
this._disablePickingIndex(objectIndex);
}
}
// TODO - simplify subclassing interface
protected _disablePickingIndex(objectIndex: number): void {
// @ts-ignore (TS2531) this method is only called internally with attributeManager defined
const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;
const colors = pickingColors || instancePickingColors;
if (!colors) {
return;
}
const start = colors.getVertexOffset(objectIndex);
const end = colors.getVertexOffset(objectIndex + 1);
// Fill the sub buffer with 0s, 1 byte per element
colors.buffer.write(new Uint8Array(end - start), start);
}
/** (Internal) Re-enable all picking indices after multi-depth picking */
restorePickingColors(): void {
// @ts-ignore (TS2531) this method is only called internally with attributeManager defined
const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;
const colors = pickingColors || instancePickingColors;
if (!colors) {
return;
}
// The picking color cache may have been freed and then reallocated. This ensures we read from the currently allocated cache.
if (
// @ts-ignore (TS2531) this method is only called internally with internalState defined
this.internalState.usesPickingColorCache &&
(colors.value as Uint8ClampedArray).buffer !== pickingColorCache.buffer
) {
colors.value = pickingColorCache.subarray(0, (colors.value as Uint8ClampedArray).length);
}
colors.updateSubBuffer({startOffset: 0});
}
/* eslint-disable max-statements */
/* (Internal) Called by layer manager when a new layer is found */
_initialize() {
assert(!this.internalState); // finalized layer cannot be reused
assert(Number.isFinite(this.props.coordinateSystem)); // invalid coordinateSystem
debug(TRACE_INITIALIZE, this);
const attributeManager = this._getAttributeManager();
if (attributeManager) {
// All instanced layers get instancePickingColors attribute by default
// Their shaders can use it to render a picking scene
// TODO - this slightly slows down non instanced layers
attributeManager.addInstanced({
instancePickingColors: {
type: 'uint8',
size: 4,
noAlloc: true,
// Updaters are always called with `this` pointing to the layer
// eslint-disable-next-line @typescript-eslint/unbound-method
update: this.calculateInstancePickingColors
}
});
}
this.internalState = new LayerState<this>({
attributeManager,
layer: this
});
this._clearChangeFlags(); // populate this.internalState.changeFlags
this.state = {};
// for backwards compatibility with older layers
// TODO - remove in next release
/* eslint-disable accessor-pairs */
Object.defineProperty(this.state, 'attributeManager', {
get: () => {
log.deprecated('layer.state.attributeManager', 'layer.getAttributeManager()')();
return attributeManager;
}
});
/* eslint-enable accessor-pairs */
this.internalState.uniformTransitions = new UniformTransitionManager(this.context.timeline);
this.internalState.onAsyncPropUpdated = this._onAsyncPropUpdated.bind(this);
// Ensure any async props are updated
this.internalState.setAsyncProps(this.props);
// Call subclass lifecycle methods
this.initializeState(this.context);
// Initialize extensions
for (const extension of this.props.extensions) {
extension.initializeState.call(this, this.context, extension);
}
// End subclass lifecycle methods
// initializeState callback tends to clear state
this.setChangeFlags({
dataChanged: 'init',
propsChanged: 'init',
viewportChanged: true,
extensionsChanged: true
});
this._update();
}
/** (Internal) Called by layer manager to transfer state from an old layer */
_transferState(oldLayer: Layer<PropsT>): void {
debug(TRACE_MATCHED, this, this === oldLayer);
const {state, internalState} = oldLayer;
if (this === oldLayer) {
return;
}
// Move internalState
this.internalState = internalState as LayerState<this>;
// Move state
this.state = state;
// We keep the state ref on old layers to support async actions
// oldLayer.state = null;
// Ensure any async props are updated
this.internalState.setAsyncProps(this.props);
this._diffProps(this.props, this.internalState.getOldProps() as Layer<PropsT>['props']);
}
/** (Internal) Called by layer manager when a new layer is added or an existing layer is matched with a new instance */
_update(): void {
// Call subclass lifecycle method
const stateNeedsUpdate = this.needsUpdate();
// End lifecycle method
debug(TRACE_UPDATE, this, stateNeedsUpdate);
if (!stateNeedsUpdate) {
return;
}
const currentProps = this.props;
const context = this.context;
const internalState = this.internalState as LayerState<this>;
const currentViewport = context.viewport;
const propsInTransition = this._updateUniformTransition();
internalState.propsInTransition = propsInTransition;
// Overwrite this.context.viewport during update to use the last activated viewport on this layer
// In multi-view applications, a layer may only be drawn in one of the views
// Which would make the "active" viewport different from the shared context
context.viewport = internalState.viewport || currentViewport;
// Overwrite this.props during update to use in-transition prop values
this.props = propsInTransition;
try {
const updateParams = this._getUpdateParams();
const oldModels = this.getModels();
// Safely call subclass lifecycle methods
if (context.device) {
this.updateState(updateParams);
} else {
try {
this.updateState(updateParams);
} catch (error) {
// ignore error if gl context is missing
}
}
// Execute extension updates
for (const extension of this.props.extensions) {
extension.updateState.call(this, updateParams, extension);