/
RenderSchedule.ts
1461 lines (1234 loc) · 62.1 KB
/
RenderSchedule.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module DisplayStyles
*/
import {
assert, compareBooleans, compareNumbers, comparePossiblyUndefined, compareStrings, compareStringsOrUndefined,
CompressedId64Set, Constructor, Id64, Id64String, OrderedId64Iterable,
} from "@itwin/core-bentley";
import { EntityReferenceSet } from "./EntityReference";
import {
ClipPlane, ClipPrimitive, ClipVector, ConvexClipPlaneSet, Matrix3d, Plane3dByOriginAndUnitNormal, Point3d, Point4d, Range1d, Transform, UnionOfConvexClipPlaneSets, Vector3d, XYAndZ,
} from "@itwin/core-geometry";
import { RgbColor } from "./RgbColor";
import { FeatureAppearance, FeatureOverrides } from "./FeatureSymbology";
import {PackedFeatureWithIndex} from "./FeatureTable";
function interpolate(start: number, end: number, fraction: number): number {
return start + fraction * (end - start);
}
function interpolateRgb(start: RgbColor, end: RgbColor, fraction: number): RgbColor {
return new RgbColor(interpolate(start.r, end.r, fraction), interpolate(start.g, end.g, fraction), interpolate(start.b, end.b, fraction));
}
function compareXYZ(lhs: XYAndZ, rhs: XYAndZ): number {
return compareNumbers(lhs.x, rhs.x) || compareNumbers(lhs.y, rhs.y) || compareNumbers(lhs.z, rhs.z);
}
function compare4d(lhs: Point4d, rhs: Point4d): number {
return compareNumbers(lhs.x, rhs.x) || compareNumbers(lhs.y, rhs.y) || compareNumbers(lhs.z, rhs.z) || compareNumbers(lhs.w, rhs.w);
}
const scratchVec3a = new Vector3d();
const scratchVec3b = new Vector3d();
function compareMatrices(lhs: Matrix3d, rhs: Matrix3d): number {
return compareXYZ(lhs.columnX(scratchVec3a), rhs.columnX(scratchVec3b))
|| compareXYZ(lhs.columnY(scratchVec3a), rhs.columnY(scratchVec3b))
|| compareXYZ(lhs.columnZ(scratchVec3a), rhs.columnZ(scratchVec3b));
}
function compareDurations(lhs: Range1d, rhs: Range1d): number {
return compareNumbers(lhs.low, rhs.low) || compareNumbers(lhs.high, rhs.high);
}
/** Namespace containing types that collectively define a script that animates the contents of a view by adjusting the visibility, position,
* and/or symbology of groups of elements over time. A [[RenderSchedule.Script]] is hosted by a [RenderTimeline]($backend) element. The script
* can be associated with a [DisplayStyleState]($frontend) by way of its [[DisplayStyleSettings.renderTimeline]] property.
* @public
*/
export namespace RenderSchedule {
/** Defines how two interpolate between two entries in a [[RenderSchedule.Timeline]].
* @note Currently only Linear and Step are supported. Any other value is treated as Step.
* @see [[RenderSchedule.TimelineEntry]].
*/
export enum Interpolation {
/** Each timeline entry's value is discrete - the timeline jumps from one entry's value directly to another. */
Step = 1,
/** Given two entries on the timeline and a timepoint in between them, linearly interpolate based on the timepoint's distance between the
* two entries.
*/
Linear = 2,
}
/** JSON representation of a [[RenderSchedule.TimelineEntry]]. */
export interface TimelineEntryProps {
/** The time point in seconds in the [Unix Epoch](https://en.wikipedia.org/wiki/Unix_time). */
time: number;
/** How to interpolate from this entry to the next entry in the timeline.
* Currently, anything other than [[RenderSchedule.Interpolation.Linear]] is treated as [[RenderSchedule.Interpolation.Step]].
* Additional interpolation modes may become supported in the future.
*/
interpolation?: Interpolation;
}
/** JSON representation of a [[RenderSchedule.VisibilityEntry]]. */
export interface VisibilityEntryProps extends TimelineEntryProps {
/** Visibility of the geometry from 0 (invisible) to 100 (fully visible), with intermediate values appearing increasingly less transparent.
* Default: 100 (fully visible).
*/
value?: number;
}
/** JSON representation of a [[RenderSchedule.ColorEntry]]. */
export interface ColorEntryProps extends TimelineEntryProps {
/** The color applied to the geometry, with each component specified as an integer in [0, 255].
* e.g., (0, 0, 0) represents black and (255, 255, 255) represents white.
* If `undefined`, the geometry is displayed in its actual color.
*/
value?: { red: number, green: number, blue: number };
}
/** JSON representation of a [[RenderSchedule.CuttingPlane]]. */
export interface CuttingPlaneProps {
/** (x,y,z) of a point on the plane. */
position: number[];
/** (x, y, z) of the plane direction (towards the clip) */
direction: number[];
/** If true, the clip plane is ignored and the geometry is displayed unclipped. */
visible?: boolean;
/** If true, the clip plane is ignored and the geometry is not displayed. */
hidden?: boolean;
}
/** JSON representation of a [[RenderSchedule.CuttingPlaneEntry]]. */
export interface CuttingPlaneEntryProps extends TimelineEntryProps {
/** The clip plane, or undefined if the geometry is not clipped. */
value?: CuttingPlaneProps;
}
/** JSON representation of a [[RenderSchedule.TransformComponents]]. */
export interface TransformComponentsProps {
/** (x, y, z) of position - applied after rotation. */
position?: number[];
/** Quaternion representing rotation. */
orientation?: number[];
/** (x, y, z) of pivot - applied before rotation. */
pivot?: number[];
}
/** JSON representation of a [Transform]($core-geometry) associated with a [[RenderSchedule.TransformEntryProps]]. */
export interface TransformProps extends TransformComponentsProps {
/** 3 X 4 transformation matrix containing 3 arrays of matrix rows consisting of 4 numbers each: [qx qy qz ax]
* where the fourth columnn in each row holds the translation.
* `undefined` is equivalent to an identity transform.
* This transform is only used if position, orientation, and/or pivot are undefined.
*/
transform?: number[][];
}
/** JSON representation of a [[RenderSchedule.TransformEntry]]. */
export interface TransformEntryProps extends TimelineEntryProps {
/** The transformation matrix, with `undefined` corresponding to an identity matrix. */
value?: TransformProps;
}
/** JSON representation of a [[RenderSchedule.Timeline]]. */
export interface TimelineProps {
/** Timeline controlling the visibility of the associated geometry. */
visibilityTimeline?: VisibilityEntryProps[];
/** Timeline controlling the colors of the associated geometry. */
colorTimeline?: ColorEntryProps[];
/** Timeline applying transforms to the associated geometry. */
transformTimeline?: TransformEntryProps[];
/** Timeline applying [ClipVector]($core-geometry)s to the associated geometry. */
cuttingPlaneTimeline?: CuttingPlaneEntryProps[];
}
/** JSON representation of an [[RenderSchedule.ElementTimeline]]. */
export interface ElementTimelineProps extends TimelineProps {
/** A positive integer that uniquely identifies this timeline among all element timelines in the [[RenderSchedule.Script]]. */
batchId: number;
/** The Ids of the elements to which this timeline applies.
* @note Prefer the compressed representation - lists of element Ids can be comparatively enormous.
* @note For a [[DisplayStyleSettingsProps]] associated with a [DisplayStyleState]($frontend) obtained via [IModelConnection.Views.load]($frontend),
* this property will be an empty `CompressedId64Set`. They are omitted to conserve bandwidth and memory because they are not needed for display on the frontend.
*/
elementIds: Id64String[] | CompressedId64Set;
}
/** JSON representation of a [[RenderSchedule.ModelTimeline]]. */
export interface ModelTimelineProps extends TimelineProps {
/** The Id of the [GeometricModelState]($frontend) to which the timeline applies. */
modelId: Id64String;
/** @alpha */
realityModelUrl?: string; // defined only for "context" reality models (attached through display style)
/** Timelines affecting groups of elements. */
elementTimelines: ElementTimelineProps[];
}
/** JSON representation of a [[RenderSchedule.Script]]. */
export type ScriptProps = ModelTimelineProps[];
/** Describes the value of some property at a specific point along a [[RenderSchedule.Timeline]].
* @see [[RenderSchedule.VisibilityEntry]]
* @see [[RenderSchedule.ColorEntry]]
* @see [[RenderSchedule.TransformEntry]]
* @see [[RenderSchedule.CuttingPlaneEntry]]
*/
export class TimelineEntry {
/** The time point in seconds in the [Unix Epoch](https://en.wikipedia.org/wiki/Unix_time). */
public readonly time: number;
/** How to interpolate from this entry to the next entry in the timeline. */
public readonly interpolation: Interpolation;
public constructor(props: TimelineEntryProps) {
this.time = props.time;
this.interpolation = props.interpolation === Interpolation.Linear ? props.interpolation : Interpolation.Step;
}
public toJSON(): TimelineEntryProps {
const props: TimelineEntryProps = {
time: this.time,
};
if (this.interpolation === Interpolation.Linear)
props.interpolation = this.interpolation;
return props;
}
public compareTo(other: TimelineEntry): number {
return compareNumbers(this.interpolation, other.interpolation) || compareNumbers(this.time, other.time);
}
public equals(other: TimelineEntry): boolean {
return 0 === this.compareTo(other);
}
}
/** A timeline entry that controls the visibility of the associated geometry. */
export class VisibilityEntry extends TimelineEntry {
/** The visibility of the geometry at this point on the timeline, in the range [0, 100] where 0 is completely invisible, 100 is completely visible,
* and values in between indicate increasing opacity.
*/
public readonly value: number;
public constructor(props: VisibilityEntryProps) {
super(props);
if (typeof props.value !== "number")
this.value = 100;
else
this.value = Math.max(0, Math.min(100, props.value));
}
public override toJSON(): VisibilityEntryProps {
const props = super.toJSON() as VisibilityEntryProps;
if (100 !== this.value)
props.value = this.value;
return props;
}
public override compareTo(other: VisibilityEntry): number {
assert(other instanceof VisibilityEntry);
return super.compareTo(other) || compareNumbers(this.value, other.value);
}
}
/** A timeline entry controlling the color of the affected geometry. */
export class ColorEntry extends TimelineEntry {
/** If defined, the color in which to draw the geometry. If undefined, the geometry is drawn in its actual color. */
public readonly value: RgbColor | undefined;
public constructor(props: ColorEntryProps) {
super(props);
if (props.value)
this.value = new RgbColor(props.value.red, props.value.green, props.value.blue);
}
public override toJSON(): ColorEntryProps {
const props = super.toJSON() as ColorEntryProps;
if (this.value) {
props.value = {
red: this.value.r,
green: this.value.g,
blue: this.value.b,
};
}
return props;
}
public override compareTo(other: ColorEntry): number {
assert(other instanceof ColorEntry);
return super.compareTo(other) || comparePossiblyUndefined((lhs, rhs) => lhs.compareTo(rhs), this.value, other.value);
}
}
/** Describes the components of a [[RenderSchedule.TransformEntry]] as a rotation around a pivot point followed by a translation. */
export class TransformComponents {
/** Pivot point - applied before rotation. */
public readonly pivot: Vector3d;
/** Quaternion rotation. */
public readonly orientation: Point4d;
/** Translation - applied after rotation. */
public readonly position: Vector3d;
public constructor(position: Vector3d, pivot: Vector3d, orientation: Point4d) {
this.position = position;
this.pivot = pivot;
this.orientation = orientation;
}
public static fromJSON(props: TransformComponentsProps): TransformComponents | undefined {
if (props.pivot && props.position && props.orientation)
return new TransformComponents(Vector3d.fromJSON(props.position), Vector3d.fromJSON(props.pivot), Point4d.fromJSON(props.orientation));
else
return undefined;
}
public toJSON(): TransformComponentsProps {
return {
position: [this.position.x, this.position.y, this.position.z],
pivot: [this.pivot.x, this.pivot.y, this.pivot.z],
orientation: [this.orientation.x, this.orientation.y, this.orientation.z, this.orientation.w],
};
}
public compareTo(other: TransformComponents): number {
return compareXYZ(this.pivot, other.pivot) || compareXYZ(this.position, other.position) || compare4d(this.orientation, other.orientation);
}
public equals(other: TransformComponents): boolean {
return this.pivot.isAlmostEqual(other.pivot) && this.position.isAlmostEqual(other.position) && this.orientation.isAlmostEqual(other.orientation);
}
}
/** A timeline entry that applies rotation, scaling, and/or translation to the affected geometry. */
export class TransformEntry extends TimelineEntry {
/** The transform matrix to be applied to the geometry, used only if [[components]] is not defined. */
public readonly value: Readonly<Transform>;
/** The transform represented as a rotation about a pivot point followed by a translation. If undefined, [[value]] is used instead. */
public readonly components?: TransformComponents;
public constructor(props: TransformEntryProps) {
super(props);
this.value = props.value ? Transform.fromJSON(props.value.transform) : Transform.identity;
if (props.value)
this.components = TransformComponents.fromJSON(props.value);
}
public override toJSON(): TransformEntryProps {
const props = super.toJSON() as TransformEntryProps;
if (this.components) {
props.value = this.components.toJSON();
props.value.transform = this.value.toRows();
} else {
props.value = { transform: this.value.toRows() };
}
return props;
}
public override compareTo(other: TransformEntry): number {
assert(other instanceof TransformEntry);
const cmp = super.compareTo(other);
if (0 !== cmp)
return cmp;
if (this.components || other.components) {
if (!this.components || !other.components)
return this.components ? 1 : -1;
return this.components.compareTo(other.components);
}
return compareXYZ(this.value.origin, other.value.origin) || compareMatrices(this.value.matrix, other.value.matrix);
}
}
/** Defines a [ClipPlane]($core-geometry) associated with a [[RenderSchedule.CuttingPlaneEntry]]. */
export class CuttingPlane {
/** A point on the plane. */
public readonly position: XYAndZ;
/** The direction perpendicular to the plane pointing toward the clip. */
public readonly direction: XYAndZ;
/** If true, the clip plane is ignored and the geometry is never clipped. */
public readonly visible: boolean;
/** If true, the clip plane is ignored and the geometry is always clipped. */
public readonly hidden: boolean;
public constructor(props: CuttingPlaneProps) {
this.position = Point3d.fromJSON(props.position);
this.direction = Point3d.fromJSON(props.direction);
this.hidden = true === props.hidden;
this.visible = true === props.visible;
}
public toJSON(): CuttingPlaneProps {
const props: CuttingPlaneProps = {
position: [this.position.x, this.position.y, this.position.z],
direction: [this.direction.x, this.direction.y, this.direction.z],
};
if (this.visible)
props.visible = true;
if (this.hidden)
props.hidden = true;
return props;
}
public compareTo(other: CuttingPlane): number {
return compareXYZ(this.position, other.position) || compareXYZ(this.direction, other.direction) || compareBooleans(this.visible, other.visible) || compareBooleans(this.hidden, other.hidden);
}
public equals(other: CuttingPlane): boolean {
return 0 === this.compareTo(other);
}
}
/** A timeline entry that applies a [ClipPlane]($core-geometry) to the affected geometry. */
export class CuttingPlaneEntry extends TimelineEntry {
/** The definition of the [ClipPlane]($core-geometry), or undefined if this entry applies no clipping. */
public readonly value: CuttingPlane | undefined;
public constructor(props: CuttingPlaneEntryProps) {
super(props);
if (props.value)
this.value = new CuttingPlane(props.value);
}
public override toJSON(): CuttingPlaneEntryProps {
const props = super.toJSON() as CuttingPlaneEntryProps;
if (this.value)
props.value = this.value.toJSON();
return props;
}
public override compareTo(other: CuttingPlaneEntry): number {
assert(other instanceof CuttingPlaneEntry);
return super.compareTo(other) || comparePossiblyUndefined((x, y) => x.compareTo(y), this.value, other.value);
}
}
/** Identifies a fractional position along a [[RenderSchedule.Timeline]] between any two [[RenderSchedule.TimelineEntry]]'s within a [[RenderSchedule.TimelineEntryList]].
* @internal
*/
export class Interval {
/** The index of the first timeline entry within the list. */
public lowerIndex!: number;
/** The index of the second timeline entry within the list. */
public upperIndex!: number;
/** The normalized distance between the two timeline entries. */
public fraction!: number;
public constructor(lower = 0, upper = 0, fraction = 0) {
this.init(lower, upper, fraction);
}
public init(lower = 0, upper = 0, fraction = 0): void {
this.lowerIndex = lower;
this.upperIndex = upper;
this.fraction = fraction;
}
}
/** A list of the [[RenderSchedule.TimelineEntry]] objects within a [[RenderSchedule.Timeline]]. The type parameters are:
* - T, a subclass of TimelineEntry with a `value` property specifying the value of the property controlled by the timeline at that entry's time point.
* - P, the JSON representation from which T is to be constructed.
* - V, the type of `T.value`.
*/
export class TimelineEntryList<T extends TimelineEntry & { readonly value: V }, P extends TimelineEntryProps, V> implements Iterable<T> {
private readonly _entries: ReadonlyArray<T>;
/** The total time period represented by the entries in this list. */
public readonly duration: Range1d;
public constructor(props: P[], ctor: Constructor<T>) {
this.duration = Range1d.createNull();
this._entries = props.map((x) => {
const entry = new ctor(x);
this.duration.extendX(entry.time);
return entry;
});
}
/** The number of entries in the list. */
public get length(): number {
return this._entries.length;
}
/** An iterator over the entries in the list. */
public [Symbol.iterator](): Iterator<T> {
return this._entries[Symbol.iterator]();
}
/** Look up an entry by its position in the list. */
public getEntry(index: number): T | undefined {
return this._entries[index];
}
/** Look up the value of an entry by its position in the list. */
public getValue(index: number): V | undefined {
return this.getEntry(index)?.value;
}
public toJSON(): P[] {
return this._entries.map((x) => x.toJSON() as P);
}
public compareTo(other: TimelineEntryList<T, P, V>): number {
let cmp = compareNumbers(this._entries.length, other._entries.length) || compareDurations(this.duration, other.duration);
if (0 === cmp) {
for (let i = 0; i < this.length; i++)
if (0 !== (cmp = this._entries[i].compareTo(other._entries[i])))
break;
}
return cmp;
}
public equals(other: TimelineEntryList<T, P, V>): boolean {
return 0 === this.compareTo(other);
}
/** @internal */
public findInterval(time: number, interval?: Interval): Interval | undefined {
if (this.length === 0)
return undefined;
interval = interval ?? new Interval();
if (time < this._entries[0].time) {
interval.init(0, 0, 0);
return interval;
}
const last = this.length - 1;
if (time >= this._entries[last].time) {
interval.init(last, last, 0);
return interval;
}
for (let i = 0; i < last; i++) {
const time0 = this._entries[i].time;
const time1 = this._entries[i + 1].time;
if (time0 <= time && time1 >= time) {
let fraction;
if (Interpolation.Linear === this._entries[i].interpolation)
fraction = (time - time0) / (time1 - time0);
else
fraction = 0;
interval.init(i, i + 1, fraction);
return interval;
}
}
return undefined;
}
}
const scratchInterval = new Interval();
/** A list of [[RenderSchedule.VisibilityEntry]]s within a [[RenderSchedule.Timeline]]. */
export class VisibilityTimelineEntries extends TimelineEntryList<VisibilityEntry, VisibilityEntryProps, number> {
/** Returns the visibility value for the entry at the specified position in the list, or 100 (fully-visible) if no such entry exists. */
public override getValue(index: number): number {
return super.getValue(index) ?? 100;
}
}
/** A list of [[RenderSchedule.TransformEntry]]s within a [[RenderSchedule.Timeline]]. */
export class TransformTimelineEntries extends TimelineEntryList<TransformEntry, TransformEntryProps, Readonly<Transform>> {
/** Returns the transform for the entry at the specified position in the list, or an identity transform if no such entry exists. */
public override getValue(index: number): Readonly<Transform> {
return super.getValue(index) ?? Transform.identity;
}
}
/** Specifies how to animate a set of geometry over time within a [[RenderSchedule.Script]].
* A [[RenderSchedule.Script]] can contain any number of [[RenderSchedule.Timeline]]s, each affecting different sets of geometry.
* @see [[RenderSchedule.ElementTimeline]] and [[RenderSchedule.ModelTimeline]].
*/
export class Timeline {
/** Sequence controlling the visibility of the geometry. */
public readonly visibility?: VisibilityTimelineEntries;
/** Sequence controlling the color of the geometry. */
public readonly color?: TimelineEntryList<ColorEntry, ColorEntryProps, RgbColor | undefined>;
/** Sequence controlling the position, orientation, and/or scale of the geometry. */
public readonly transform?: TransformTimelineEntries;
/** Sequence controlling how the geometry is clipped. */
public readonly cuttingPlane?: TimelineEntryList<CuttingPlaneEntry, CuttingPlaneEntryProps, CuttingPlane | undefined>;
/** The total time period represented by this timeline. */
public readonly duration: Range1d;
public constructor(props: TimelineProps) {
this.duration = Range1d.createNull();
if (props.visibilityTimeline) {
this.visibility = new VisibilityTimelineEntries(props.visibilityTimeline, VisibilityEntry);
this.duration.extendRange(this.visibility.duration);
}
if (props.colorTimeline) {
this.color = new TimelineEntryList(props.colorTimeline, ColorEntry);
this.duration.extendRange(this.color.duration);
}
if (props.transformTimeline) {
this.transform = new TransformTimelineEntries(props.transformTimeline, TransformEntry);
this.duration.extendRange(this.transform.duration);
}
if (props.cuttingPlaneTimeline) {
this.cuttingPlane = new TimelineEntryList(props.cuttingPlaneTimeline, CuttingPlaneEntry);
this.duration.extendRange(this.cuttingPlane.duration);
}
}
public toJSON(): TimelineProps {
return {
visibilityTimeline: this.visibility?.toJSON(),
colorTimeline: this.color?.toJSON(),
transformTimeline: this.transform?.toJSON(),
cuttingPlaneTimeline: this.cuttingPlane?.toJSON(),
};
}
public compareTo(other: Timeline): number {
const cmp = compareDurations(this.duration, other.duration);
if (0 !== cmp)
return cmp;
// Do cheaper checks before iterating through timeline entries
if (!!this.visibility !== !!other.visibility)
return this.visibility ? 1 : -1;
else if (!!this.color !== !!other.color)
return this.color ? 1 : -1;
else if (!!this.transform !== !!other.transform)
return this.transform ? 1 : -1;
else if (!!this.cuttingPlane !== !!other.cuttingPlane)
return this.cuttingPlane ? 1 : -1;
return comparePossiblyUndefined((x, y) => x.compareTo(y), this.visibility, other.visibility) || comparePossiblyUndefined((x, y) => x.compareTo(y), this.color, other.color)
|| comparePossiblyUndefined((x, y) => x.compareTo(y), this.transform, other.transform) || comparePossiblyUndefined((x, y) => x.compareTo(y), this.cuttingPlane, other.cuttingPlane);
}
public equals(other: Timeline): boolean {
return 0 === this.compareTo(other);
}
/** Get the visibility of the geometry at the specified time point. */
public getVisibility(time: number): number {
let interval;
if (!this.visibility || !(interval = this.visibility.findInterval(time, scratchInterval)))
return 100;
let visibility = this.visibility.getValue(interval.lowerIndex) ?? 100;
if (interval.fraction > 0)
visibility = interpolate(visibility, this.visibility.getValue(interval.upperIndex) ?? 100, interval.fraction);
return visibility;
}
/** Get the color of the geometry at the specified time point, or undefined if the color is not overridden at that time point. */
public getColor(time: number): RgbColor | undefined {
let interval;
if (!this.color || !(interval = this.color.findInterval(time, scratchInterval)))
return undefined;
const start = this.color.getValue(interval.lowerIndex);
if (start && interval.fraction > 0) {
const end = this.color.getValue(interval.upperIndex);
if (end)
return interpolateRgb(start, end, interval.fraction);
}
return start;
}
/** Get the transform applied to the geometry at the specified time point. */
public getAnimationTransform(time: number): Readonly<Transform> {
let interval;
if (!this.transform || !(interval = this.transform.findInterval(time, scratchInterval)))
return Transform.identity;
let transform = this.transform.getValue(interval.lowerIndex);
if (interval.fraction > 0) {
const comp0 = this.transform.getEntry(interval.lowerIndex)?.components;
const comp1 = this.transform.getEntry(interval.upperIndex)?.components;
if (comp0 && comp1) {
const sum = Point4d.interpolateQuaternions(comp0.orientation, interval.fraction, comp1.orientation);
const matrix = Matrix3d.createFromQuaternion(sum);
const pre = Transform.createTranslation(comp0.pivot);
const post = Transform.createTranslation(comp0.position.interpolate(interval.fraction, comp1.position));
const product = post.multiplyTransformMatrix3d(matrix);
product.multiplyTransformTransform(pre, product);
transform = product;
} else {
const end = this.transform.getValue(interval.upperIndex);
const q0 = transform.matrix.inverse()?.toQuaternion();
const q1 = end.matrix.inverse()?.toQuaternion();
if (q0 && q1) {
const sum = Point4d.interpolateQuaternions(q0, interval.fraction, q1);
const matrix = Matrix3d.createFromQuaternion(sum);
const origin0 = Vector3d.createFrom(transform.origin);
const origin1 = Vector3d.createFrom(end.origin);
transform = Transform.createRefs(origin0.interpolate(interval.fraction, origin1), matrix);
}
}
}
return transform;
}
/** Get the clipping plane applied to the geometry at the specified time point, or undefined if the geometry is unclipped at that time point. */
public getCuttingPlane(time: number): Plane3dByOriginAndUnitNormal | undefined {
let interval;
if (!this.cuttingPlane || !(interval = this.cuttingPlane.findInterval(time, scratchInterval)))
return undefined;
const start = this.cuttingPlane.getValue(interval.lowerIndex);
if (!start)
return undefined;
const position = Point3d.createFrom(start.position);
const direction = Vector3d.createFrom(start.direction);
const end = interval.fraction > 0 ? this.cuttingPlane.getValue(interval.upperIndex) : undefined;
if (end) {
position.interpolate(interval.fraction, end.position, position);
direction.interpolate(interval.fraction, end.direction, direction);
} else {
if (start.hidden || start.visible)
return undefined;
}
direction.negate(direction);
direction.normalizeInPlace();
return Plane3dByOriginAndUnitNormal.create(position, direction);
}
/** Create a ClipVector from the [[RenderSchedule.CuttingPlane]] applied to the geometry at the specified time point, if any. */
public getClipVector(time: number): ClipVector | undefined {
const plane = this.getCuttingPlane(time);
if (!plane)
return undefined;
const cp = ClipPlane.createPlane(plane);
const cps = UnionOfConvexClipPlaneSets.createConvexSets([ConvexClipPlaneSet.createPlanes([cp])]);
const prim = ClipPrimitive.createCapture(cps);
return ClipVector.createCapture([prim]);
}
/** @internal */
protected getFeatureAppearance(visibility: number, time: number): FeatureAppearance | undefined {
const transparency = visibility < 100 ? (1 - visibility / 100) : undefined;
const rgb = this.getColor(time);
return undefined !== rgb || undefined !== transparency ? FeatureAppearance.fromJSON({ rgb, transparency }) : undefined;
}
}
/** Specifies how to animate the geometry belonging to a set of [GeometricElement]($backend)s as part of a [[RenderSchedule.Script]]. */
export class ElementTimeline extends Timeline {
/** A positive integer that uniquely identififes this timeline among all ElementTimelines in the [[RenderSchedule.Script]]. */
public readonly batchId: number;
private readonly _elementIds: Id64String[] | CompressedId64Set;
private constructor(props: ElementTimelineProps) {
super(props);
this.batchId = props.batchId;
this._elementIds = props.elementIds;
}
public static fromJSON(props?: ElementTimelineProps): ElementTimeline {
return new ElementTimeline(props ?? { elementIds: [], batchId: 0 });
}
public override toJSON(): ElementTimelineProps {
return {
...super.toJSON(),
batchId: this.batchId,
elementIds: this._elementIds,
};
}
public get containsElementIds(): boolean {
return this._elementIds.length > 0;
}
private compareElementIds(other: ElementTimeline): number {
if (typeof this._elementIds === typeof other._elementIds) {
const cmp = compareNumbers(this._elementIds.length, other._elementIds.length);
if (0 !== cmp)
return cmp;
if (typeof this._elementIds === "string") {
assert(typeof other._elementIds === "string");
return compareStrings(this._elementIds, other._elementIds);
}
}
// One or both are stored as arrays, in which case they might contain the same Ids in different orders. We will consider them different in that case.
const mine = this.elementIds[Symbol.iterator]();
const theirs = other.elementIds[Symbol.iterator]();
while (true) {
const a = mine.next();
const b = theirs.next();
if (a.done !== b.done)
return compareBooleans(!!a.done, !!b.done);
else if (a.done)
return 0;
const cmp = compareStrings(a.value, b.value);
if (0 !== cmp)
return cmp;
}
}
public override compareTo(other: ElementTimeline): number {
assert(other instanceof ElementTimeline);
return compareNumbers(this.batchId, other.batchId) || this.compareElementIds(other) || super.compareTo(other);
}
/** @internal */
public static getElementIds(ids: Id64String[] | CompressedId64Set): Iterable<Id64String> {
if (typeof ids === "string")
return CompressedId64Set.iterable(ids);
else if (Array.isArray(ids)) {
return ids;
} else {
return [];
}
}
/** The Ids of the elements controlled by this timeline. */
public get elementIds(): Iterable<Id64String> {
return ElementTimeline.getElementIds(this._elementIds);
}
/** True if this timeline affects the color or transparency of the elements. */
public get containsFeatureOverrides(): boolean {
return undefined !== this.visibility || undefined !== this.color;
}
/** If true, applying this timeline requires special tiles to be generated in which groups of elements are batched into nodes.
* @internal
*/
public get requiresBatching(): boolean {
if (this.cuttingPlane)
return true;
return this.batchId !== 0 && (undefined !== this.color || undefined !== this.visibility);
}
/** True if this timeline affects the position, orientation, or scale of the elements. */
public get containsTransform(): boolean {
return undefined !== this.transform;
}
/** @internal */
public addSymbologyOverrides(overrides: FeatureOverrides, time: number): void {
assert(0 !== this.batchId);
const vis = this.getVisibility(time);
if (vis <= 0) {
overrides.setAnimationNodeNeverDrawn(this.batchId);
return;
}
const appearance = this.getFeatureAppearance(vis, time);
if (appearance)
overrides.overrideAnimationNode(this.batchId, appearance);
}
}
/** Specifies how to animate the geometry within a [GeometricModel]($backend) as part of a [[RenderSchedule.Script]]. */
export class ModelTimeline extends Timeline {
/** The Id of the [GeometricModel]($backend) to be animated. */
public readonly modelId: Id64String;
/** @internal */
public readonly realityModelUrl?: string;
/** Timelines specifying how to animate groups of [GeometricElement]($backend)s within the model. */
public readonly elementTimelines: ReadonlyArray<ElementTimeline>;
/** @internal */
public readonly transformBatchIds: ReadonlyArray<number>;
/** True if this timeline affects the color or transparency of the geometry. */
public readonly containsFeatureOverrides: boolean;
/** True if this timeline applies clipping to the model. */
public readonly containsModelClipping: boolean;
/** If true, applying this timeline requires special tiles to be generated in which groups of elements are batched into nodes.
* @internal
*/
public readonly requiresBatching: boolean;
/** True if this timeline affects the position, orientation, or scale of the geometry. */
public readonly containsTransform: boolean;
/** True if any [[RenderSchedule.ElementTimeline]]s exist and none of them contain any element Ids. This generally indicates that
* the backend was instructed to omit the Ids to save space when supplying the script.
*/
public readonly omitsElementIds: boolean;
private _maxBatchId?: number;
/** Tile tree suppliers perform **very** frequent ordered comparisons of ModelTimelines. They need to be fast. */
private readonly _cachedComparisons = new WeakMap<ModelTimeline, number>();
/** When loading tiles we need to quickly map element Ids to batch Ids. This map is initialized on first call to [[getTimelineForElement]] to facilitate that lookup. */
private _idPairToElementTimeline?: Id64.Uint32Map<ElementTimeline>;
private _discreteBatchIds?: Set<number>;
private constructor(props: ModelTimelineProps) {
super(props);
this.modelId = props.modelId;
this.realityModelUrl = props.realityModelUrl;
this.containsModelClipping = undefined !== this.cuttingPlane;
let containsFeatureOverrides = undefined !== this.visibility || undefined !== this.color;
let requiresBatching = false;
let containsTransform = false;
const transformBatchIds: number[] = [];
const elementTimelines: ElementTimeline[] = [];
let containsElementIds = false;
for (const elProps of props.elementTimelines) {
const el = ElementTimeline.fromJSON(elProps);
elementTimelines.push(el);
this.duration.extendRange(el.duration);
if (el.containsTransform) {
containsTransform = true;
if (el.batchId)
transformBatchIds.push(el.batchId);
}
containsFeatureOverrides ||= el.containsFeatureOverrides;
requiresBatching ||= el.requiresBatching;
containsElementIds = containsElementIds || el.containsElementIds;
}
this.elementTimelines = elementTimelines;
this.transformBatchIds = transformBatchIds;
this.omitsElementIds = elementTimelines.length > 0 && !containsElementIds;
this.containsFeatureOverrides = containsFeatureOverrides;
this.requiresBatching = requiresBatching;
this.containsTransform = containsTransform;
}
public static fromJSON(props?: ModelTimelineProps): ModelTimeline {
return new ModelTimeline(props ?? { elementTimelines: [], modelId: Id64.invalid });
}
public override toJSON(): ModelTimelineProps {
return {
...super.toJSON(),
modelId: this.modelId,
realityModelUrl: this.realityModelUrl,
elementTimelines: this.elementTimelines.map((x) => x.toJSON()),
};
}
public override compareTo(other: ModelTimeline): number {
if (this === other)
return 0;
const cached = this._cachedComparisons.get(other);
if (undefined !== cached)
return cached;
assert(other instanceof ModelTimeline);
let cmp = compareStrings(this.modelId, other.modelId) || compareStringsOrUndefined(this.realityModelUrl, other.realityModelUrl)
|| compareNumbers(this.elementTimelines.length, other.elementTimelines.length) || compareBooleans(this.containsFeatureOverrides, other.containsFeatureOverrides)
|| compareBooleans(this.containsModelClipping, other.containsModelClipping) || compareBooleans(this.containsTransform, other.containsTransform)
|| super.compareTo(other);
if (0 === cmp) {
for (let i = 0; i < this.elementTimelines.length; i++)
if (0 !== (cmp = this.elementTimelines[i].compareTo(other.elementTimelines[i])))
break;
}
this._cachedComparisons.set(other, cmp);
other._cachedComparisons.set(this, -cmp);
return cmp;
}
/** Look up the element timeline with the specified batch Id. */
public findByBatchId(batchId: number): ElementTimeline | undefined {
return this.elementTimelines.find((x) => x.batchId === batchId);
}
/** @internal */
public addSymbologyOverrides(overrides: FeatureOverrides, time: number): void {
const appearance = this.getFeatureAppearance(this.getVisibility(time), time);
if (appearance)
overrides.override({ modelId: this.modelId, appearance });
for (const timeline of this.elementTimelines)
timeline.addSymbologyOverrides(overrides, time);
}
/** Obtain the transform applied to the model at the specified time point, if any. */
public getTransform(batchId: number, time: number): Readonly<Transform> | undefined {
return this.findByBatchId(batchId)?.getAnimationTransform(time);
}
/** Get the highest batchId of any ElementTimeline in this timeline. */
public get maxBatchId(): number {
if (undefined === this._maxBatchId) {
this._maxBatchId = 0;
for (const elem of this.elementTimelines)
this._maxBatchId = Math.max(this._maxBatchId, elem.batchId);
}
return this._maxBatchId;
}
/** Given the two halves of an [Id64]($bentley) return the [[ElementTimeline]] containing the corresponding element.
* @note The first call to this method populates a mapping for fast lookup.
* @alpha
*/
public getTimelineForElement(idLo: number, idHi: number): ElementTimeline | undefined {
if (!this._idPairToElementTimeline) {
this._idPairToElementTimeline = new Id64.Uint32Map<ElementTimeline>();