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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
use crate::animation::{AnimationState, Interpolator};
use crate::prelude::*;
use hashbrown::HashMap;
use vizia_storage::{SparseSet, SparseSetGeneric, SparseSetIndex};
const INDEX_MASK: u32 = u32::MAX / 4;
const INLINE_MASK: u32 = 1 << 31;
const INHERITED_MASK: u32 = 1 << 30;
/// Represents an index that can either be used to retrieve inline or shared data
///
/// Since inline data will override shared data, this allows the same index to be used
/// with a flag to indicate which data the index refers to.
/// The first bit of the u32 internal value is used to signify if the data index
/// refers to shared (default) or inline data:
/// - 0 - shared
/// - 1 - inline
#[derive(Clone, Copy, PartialEq)]
struct DataIndex(u32);
impl DataIndex {
/// Create a new data index with the first bit set to 1, indicating that
/// the index refers to inline data.
pub fn inline(index: usize) -> Self {
assert!((index as u32) < INDEX_MASK);
let value = (index as u32) | INLINE_MASK;
Self(value)
}
pub fn inherited(self) -> Self {
let value = self.0;
Self(value | INHERITED_MASK)
}
/// Create a new data index with the first bit set to 0, indicating that
/// the index refers to shared data.
pub fn shared(index: usize) -> Self {
assert!((index as u32) < INDEX_MASK);
Self(index as u32)
}
/// Retrieve the inline or shared data index.
pub fn index(&self) -> usize {
(self.0 & INDEX_MASK) as usize
}
/// Returns true if the data index refers to inline data.
pub fn is_inline(&self) -> bool {
(self.0 & INLINE_MASK).rotate_left(1) != 0
}
/// Returns true if the data index refers to an inherited value
pub fn is_inherited(&self) -> bool {
(self.0 & INHERITED_MASK).rotate_left(2) != 0
}
/// Create a null data index.
///
/// A null data index is used to signify that the index refers to no data.
pub fn null() -> Self {
Self(u32::MAX >> 1)
}
}
impl std::fmt::Debug for DataIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_inline() {
write!(f, "Inline: {}", self.index())
} else {
write!(f, "Shared: {}", self.index())
}
}
}
/// An Index is used by the AnimatableSet and contains a data index and an animation index.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct InlineIndex {
data_index: DataIndex,
anim_index: u32,
}
impl Default for InlineIndex {
fn default() -> Self {
InlineIndex { data_index: DataIndex::null(), anim_index: u32::MAX }
}
}
impl SparseSetIndex for InlineIndex {
fn new(index: usize) -> Self {
InlineIndex { data_index: DataIndex::inline(index), anim_index: u32::MAX }
}
fn null() -> Self {
Self::default()
}
fn index(&self) -> usize {
self.data_index.index()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct SharedIndex {
data_index: u32,
animation: Animation,
}
impl Default for SharedIndex {
fn default() -> Self {
SharedIndex { data_index: u32::MAX, animation: Animation::null() }
}
}
impl SparseSetIndex for SharedIndex {
fn new(index: usize) -> Self {
SharedIndex { data_index: index as u32, animation: Animation::null() }
}
fn null() -> Self {
Self::default()
}
fn index(&self) -> usize {
self.data_index as usize
}
}
#[derive(Debug)]
pub(crate) struct SharedData<T> {
pub variable_name_hash: u64,
pub fallback: Option<T>,
pub value: T,
}
/// Animatable set is used for storing inline and shared data for entities as well as definitions for
/// animations, which can be played for entities, and transitions, which play when an entity matches a new shared style
/// rule which defines a trnasition.
///
/// Animations are moved from animations to active_animations when played. This allows the active
/// animations to be quickly iterated to update the value.
#[derive(Default, Debug)]
pub(crate) struct AnimatableVarSet<T: Interpolator> {
/// Shared data determined by style rules
pub(crate) shared_data: SparseSetGeneric<SharedIndex, SharedData<T>>,
/// Inline data defined on specific entities
pub(crate) inline_data: SparseSetGeneric<InlineIndex, T>,
/// Animation descriptions
animations: SparseSet<AnimationState<T>>,
/// Animations which are currently playing
active_animations: Vec<AnimationState<T>>,
}
impl<T> AnimatableVarSet<T>
where
T: 'static + Default + Clone + Interpolator + PartialEq + std::fmt::Debug,
{
/// Insert an inline value for an entity.
pub fn insert(&mut self, entity: Entity, value: T) {
self.inline_data.insert(entity, value);
}
/// Remove an entity and any inline data.
pub fn remove(&mut self, entity: Entity) -> Option<T> {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
let active_anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if active_anim_index < self.active_animations.len() {
let anim_state = &mut self.active_animations[active_anim_index];
anim_state.t = 1.0;
self.remove_innactive_animations();
}
let data_index = self.inline_data.sparse[entity_index].data_index;
if data_index.is_inline() && !data_index.is_inherited() {
self.inline_data.remove(entity)
} else {
self.inline_data.sparse[entity_index] = InlineIndex::null();
None
}
} else {
None
}
}
/// Inherit inline data from a parent entity.
pub fn inherit_inline(&mut self, entity: Entity, parent: Entity) -> bool {
let entity_index = entity.index();
let parent_index = parent.index();
if parent_index < self.inline_data.sparse.len() {
let parent_sparse_index = self.inline_data.sparse[parent_index];
if parent_sparse_index.data_index.is_inline()
&& parent_sparse_index.data_index.index() < self.inline_data.dense.len()
{
if entity_index >= self.inline_data.sparse.len() {
self.inline_data.sparse.resize(entity_index + 1, InlineIndex::null());
}
let entity_sparse_index = self.inline_data.sparse[entity_index];
if self.inline_data.sparse[entity_index].data_index.index()
!= parent_sparse_index.data_index.index()
{
if entity_sparse_index.data_index.index() < self.inline_data.dense.len() {
if entity_sparse_index.data_index.is_inherited()
&& entity_sparse_index.data_index.is_inline()
{
self.inline_data.sparse[entity_index] = InlineIndex {
data_index: DataIndex::inline(
parent_sparse_index.data_index.index(),
)
.inherited(),
anim_index: u32::MAX,
};
return true;
}
} else {
self.inline_data.sparse[entity_index] = InlineIndex {
data_index: DataIndex::inline(parent_sparse_index.data_index.index())
.inherited(),
anim_index: u32::MAX,
};
return true;
}
}
}
}
false
}
/// Inherit shared data from a parent entity.
pub fn inherit_shared(&mut self, entity: Entity, parent: Entity) -> bool {
let entity_index = entity.index();
let parent_index = parent.index();
if parent_index < self.inline_data.sparse.len() {
let parent_sparse_index = self.inline_data.sparse[parent_index];
if !parent_sparse_index.data_index.is_inline()
&& parent_sparse_index.data_index.index() < self.shared_data.dense.len()
{
if entity_index >= self.inline_data.sparse.len() {
self.inline_data.sparse.resize(entity_index + 1, InlineIndex::null());
}
let entity_sparse_index = self.inline_data.sparse[entity_index];
if !entity_sparse_index.data_index.is_inline()
&& self.inline_data.sparse[entity_index].data_index.index()
!= parent_sparse_index.data_index.index()
{
if entity_sparse_index.data_index.index() < self.shared_data.dense.len() {
if entity_sparse_index.data_index.is_inherited() {
self.inline_data.sparse[entity_index] = InlineIndex {
data_index: DataIndex::shared(
parent_sparse_index.data_index.index(),
)
.inherited(),
// Preserve any active animation (e.g. a reverse transition
// that was just started before inheritance runs).
anim_index: entity_sparse_index.anim_index,
};
return true;
}
} else {
if !entity_sparse_index.data_index.is_inline() {
self.inline_data.sparse[entity_index] = InlineIndex {
data_index: DataIndex::shared(
parent_sparse_index.data_index.index(),
)
.inherited(),
// Preserve any active animation.
anim_index: entity_sparse_index.anim_index,
};
}
return true;
}
}
}
}
false
}
/// Inserts an animation
///
/// Animations exist separately to inline (entity) data and shared (rule) data.
/// Playing an aimation for a particular entity will clone the animation state to the
/// active animations and then link the entity to it.
pub(crate) fn insert_animation(
&mut self,
animation: Animation,
animation_description: AnimationState<T>,
) {
self.animations.insert(animation, animation_description);
}
pub(crate) fn insert_rule(&mut self, rule: Rule, value: T) {
self.shared_data
.insert(rule, SharedData { variable_name_hash: u64::MAX, fallback: None, value });
}
pub(crate) fn insert_variable_rule(
&mut self,
rule: Rule,
variable_name_hash: u64,
fallback: Option<T>,
) {
self.shared_data
.insert(rule, SharedData { variable_name_hash, fallback, value: T::default() });
}
// pub(crate) fn remove_rule(&mut self, rule: Rule) -> Option<T> {
// self.shared_data.remove(rule)
// }
/// Inserts a transition for a given rule
///
/// Transitions are animations which are defined for a particular rule. When an entity is linked to
/// a rule any transition associated with that rule will play for that entity.
///
pub(crate) fn insert_transition(&mut self, rule: Rule, animation: Animation) {
// Check if the rule exists
if self.shared_data.contains(rule) && self.animations.contains(animation) {
self.shared_data.sparse[rule.index()].animation = animation;
}
}
/// Play an animation for a given entity.
pub(crate) fn play_animation(
&mut self,
entity: Entity,
animation: Animation,
start_time: Instant,
duration: Duration,
delay: Duration,
) {
let entity_index = entity.index();
if !self.animations.contains(animation) {
return;
}
// If there is no inline or shared data for the entity then add the entity as animation only
if entity_index >= self.inline_data.sparse.len() {
self.inline_data.sparse.resize(entity_index + 1, InlineIndex::null());
}
if entity_index < self.inline_data.sparse.len() {
let active_anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if active_anim_index < self.active_animations.len() {
let anim_state = &mut self.active_animations[active_anim_index];
if anim_state.id == animation {
anim_state.active = true;
anim_state.t = 0.0;
anim_state.start_time = start_time;
anim_state.output = Some(
self.animations
.get(animation)
.cloned()
.unwrap()
.keyframes
.first()
.unwrap()
.value
.clone(),
);
} else {
anim_state.output = Some(
self.animations
.get(animation)
.cloned()
.unwrap()
.keyframes
.first()
.unwrap()
.value
.clone(),
);
anim_state.entities.remove(&entity);
}
}
// Safe to unwrap because already checked that the animation exists
let mut anim_state = self.animations.get(animation).cloned().unwrap();
anim_state.duration = duration;
anim_state.id = animation;
anim_state.delay = delay;
anim_state.dt = delay.as_secs_f32() / duration.as_secs_f32();
anim_state.output = Some(
self.animations
.get(animation)
.cloned()
.unwrap()
.keyframes
.first()
.unwrap()
.value
.clone(),
);
anim_state.play(entity);
self.inline_data.sparse[entity_index].anim_index = self.active_animations.len() as u32;
self.active_animations.push(anim_state);
}
}
/// Tick the animation for the given time and return a list of entities which have been animated.
pub fn tick(&mut self, time: Instant) -> Vec<Entity> {
self.remove_innactive_animations();
if self.has_animations() {
for state in self.active_animations.iter_mut() {
// If the animation is already finished then skip
if state.t == 1.0 {
continue;
}
if state.keyframes.len() == 1 {
state.output = Some(state.keyframes[0].value.clone());
continue;
}
let elapsed_time = time.duration_since(state.start_time);
let mut normalised_time =
(elapsed_time.as_secs_f32() / state.duration.as_secs_f32()) - state.dt;
normalised_time = normalised_time.clamp(0.0, 1.0);
let mut i = 0;
while i < state.keyframes.len() - 1 && state.keyframes[i + 1].time < normalised_time
{
i += 1;
}
let start = &state.keyframes[i];
let end = &state.keyframes[i + 1];
let normalised_elapsed_time =
(normalised_time - start.time) / (end.time - start.time);
state.t = normalised_time;
let timing_t = start.timing_function.value(normalised_elapsed_time);
state.output = Some(T::interpolate(&start.value, &end.value, timing_t));
}
self.active_animations
.iter()
.flat_map(|state| state.entities.clone())
.collect::<Vec<Entity>>()
} else {
Vec::new()
}
}
// Returns true if the given entity is linked to an active animation
// pub fn is_animating(&self, entity: Entity) -> bool {
// let entity_index = entity.index();
// if entity_index < self.inline_data.sparse.len() {
// let anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
// if anim_index < self.active_animations.len() {
// return true;
// }
// }
// false
// }
/// Returns a reference to the active animations.
pub(crate) fn get_active_animations(&mut self) -> Option<&Vec<AnimationState<T>>> {
Some(&self.active_animations)
}
/// Stop an active animation for the given entity.
pub(crate) fn stop_animation(&mut self, entity: Entity, animation: Animation) {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
let active_anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if active_anim_index < self.active_animations.len() {
let anim_state = &mut self.active_animations[active_anim_index];
if anim_state.id == animation {
anim_state.entities.remove(&entity);
}
}
self.inline_data.sparse[entity_index].anim_index = u32::MAX;
}
}
/// Remove any inactive animations from the active animations list.
pub fn remove_innactive_animations(&mut self) {
// Create a list of finished animations
let inactive: Vec<AnimationState<T>> = self
.active_animations
.iter()
.filter(|e| e.t == 1.0 && !e.persistent)
.cloned()
.collect();
// Remove inactive animation states from active animations list
// Retains persistent animations
self.active_animations.retain(|e| e.t < 1.0 || e.persistent);
for state in inactive.into_iter() {
for entity in state.entities.iter() {
self.inline_data.sparse[entity.index()].anim_index = u32::MAX;
}
}
for (index, state) in self.active_animations.iter().enumerate() {
for entity in state.entities.iter() {
self.inline_data.sparse[entity.index()].anim_index = index as u32;
}
}
}
/// Returns true if there are any active animations.
pub fn has_animations(&self) -> bool {
for state in self.active_animations.iter() {
if state.t < 1.0 {
return true;
}
}
false
}
/// Returns true if the given entity is linked to an active animation.
pub fn has_active_animation(&self, entity: Entity, animation: Animation) -> bool {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
let anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if anim_index < self.active_animations.len()
&& self.active_animations[anim_index].id == animation
{
return true;
}
}
false
}
// Returns a reference to any inline data on the entity if it exists.
// pub fn get_inline(&self, entity: Entity) -> Option<&T> {
// let entity_index = entity.index();
// if entity_index < self.inline_data.sparse.len() {
// let data_index = self.inline_data.sparse[entity_index].data_index;
// if data_index.is_inline() {
// return self.inline_data.get(entity);
// }
// }
// None
// }
/// Returns a mutable reference to any inline data on the entity if it exists.
pub fn get_inline_mut(&mut self, entity: Entity) -> Option<&mut T> {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
if data_index.is_inline() {
return self.inline_data.get_mut(entity);
}
}
None
}
pub(crate) fn get_animation_mut(
&mut self,
animation: Animation,
) -> Option<&mut AnimationState<T>> {
self.animations.get_mut(animation)
}
/// Get the animated, inline, or shared data value from the storage.
pub fn get(&self, entity: Entity) -> Option<&T> {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
// Animations override inline and shared styling
let animation_index = self.inline_data.sparse[entity_index].anim_index as usize;
if animation_index < self.active_animations.len() {
return self.active_animations[animation_index].get_output();
}
let data_index = self.inline_data.sparse[entity_index].data_index;
if data_index.is_inline() {
if data_index.index() < self.inline_data.dense.len() {
return Some(&self.inline_data.dense[data_index.index()].value);
}
} else if data_index.index() < self.shared_data.dense.len() {
return Some(&self.shared_data.dense[data_index.index()].value.value);
}
}
None
}
pub(crate) fn get_with_variables(
&self,
entity: Entity,
variables: &HashMap<u64, AnimatableVarSet<T>>,
) -> Option<T> {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
let idx = data_index.index();
if !data_index.is_inline() && idx < self.shared_data.dense.len() {
if self.shared_data.dense[data_index.index()].value.variable_name_hash != u64::MAX {
let shared = &self.shared_data.dense[data_index.index()].value;
if let Some(prop) = variables.get(&shared.variable_name_hash) {
return prop
.get_with_variables(entity, variables)
.or_else(|| shared.fallback.clone());
}
return shared.fallback.clone();
} else {
return Some(self.shared_data.dense[data_index.index()].value.value.clone());
}
}
}
None
}
/// Get the current value for an entity, dynamically resolving any variable reference.
///
/// Unlike `get()`, this follows the stored variable hash at draw time so that an
/// animating custom property (e.g. `--my-color`) is visible to any property that
/// references it via `var(--my-color)`.
pub fn get_resolved(
&self,
entity: Entity,
variables: &HashMap<u64, AnimatableVarSet<T>>,
) -> Option<T> {
let entity_index = entity.index();
if entity_index < self.inline_data.sparse.len() {
// An active animation on this property itself takes priority.
let animation_index = self.inline_data.sparse[entity_index].anim_index as usize;
if animation_index < self.active_animations.len() {
return self.active_animations[animation_index].get_output().cloned();
}
let data_index = self.inline_data.sparse[entity_index].data_index;
if data_index.is_inline() {
if data_index.index() < self.inline_data.dense.len() {
return Some(self.inline_data.dense[data_index.index()].value.clone());
}
} else if data_index.index() < self.shared_data.dense.len() {
let shared = &self.shared_data.dense[data_index.index()].value;
if shared.variable_name_hash != u64::MAX {
// Property references a CSS variable — resolve dynamically so that
// an in-progress animation on the variable is picked up every frame.
if let Some(var_store) = variables.get(&shared.variable_name_hash) {
return var_store
.get_resolved(entity, variables)
.or_else(|| shared.fallback.clone());
}
return shared.fallback.clone();
} else {
return Some(shared.value.clone());
}
}
}
None
}
/// Link an entity to some shared data.
pub(crate) fn link(
&mut self,
entity: Entity,
rules: &[(Rule, u32)],
variables: &HashMap<u64, AnimatableVarSet<T>>,
) -> bool {
let entity_index = entity.index();
// Check if the entity already has some data
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
// If the data is inline then skip linking as inline data overrides shared data
if data_index.is_inline() && !data_index.is_inherited() {
return false;
}
}
// Loop through matched rules and link to the first valid rule
for (rule, _) in rules {
if let Some(shared_data) = self.shared_data.get_mut(*rule) {
if shared_data.variable_name_hash != u64::MAX {
if let Some(prop) = variables.get(&shared_data.variable_name_hash) {
if let Some(data) = prop.get_with_variables(entity, variables) {
shared_data.value = data;
}
}
}
}
if let Some(shared_data_index) = self.shared_data.dense_idx(*rule) {
// If the entity doesn't have any previous shared data then create space for it
if entity_index >= self.inline_data.sparse.len() {
self.inline_data.sparse.resize(entity_index + 1, InlineIndex::null());
}
// Get the animation state index of any animations (transitions) defined for the rule
let rule_animation = shared_data_index.animation;
//if let Some(transition_state) = self.animations.get_mut(rule_animation) {
let entity_anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if entity_anim_index < self.active_animations.len() {
// Already animating
let current_value = self.get(entity).cloned().unwrap_or_default();
let current_anim_state = &mut self.active_animations[entity_anim_index];
let rule_data_index = shared_data_index.data_index as usize;
if current_anim_state.is_transition() {
// Skip if the transition hasn't changed
if current_anim_state.to_rule != rule_data_index {
if rule_data_index == current_anim_state.from_rule {
// Transitioning back to previous rule
current_anim_state.from_rule = current_anim_state.to_rule;
current_anim_state.to_rule = rule_data_index;
current_anim_state.keyframes.first_mut().unwrap().value =
self.shared_data.dense[current_anim_state.from_rule]
.value
.value
.clone();
current_anim_state.keyframes.last_mut().unwrap().value =
self.shared_data.dense[current_anim_state.to_rule]
.value
.value
.clone();
current_anim_state.dt = current_anim_state.t - 1.0;
current_anim_state.start_time = Instant::now();
} else {
// Transitioning to new rule
current_anim_state.to_rule = rule_data_index;
current_anim_state.keyframes.first_mut().unwrap().value =
current_value;
current_anim_state.keyframes.last_mut().unwrap().value =
self.shared_data.dense[current_anim_state.to_rule]
.value
.value
.clone();
current_anim_state.t = 0.0;
current_anim_state.start_time = Instant::now();
}
}
}
} else if let Some(transition_state) = self.animations.get_mut(rule_animation) {
// Safe to unwrap because already checked that the rule exists
let end = self.shared_data.get(*rule).unwrap();
let entity_data_index = self.inline_data.sparse[entity_index].data_index;
if !entity_data_index.is_inline()
&& entity_data_index.index() < self.shared_data.dense.len()
{
// Resolve the start value dynamically so that a stale baked value
// is not used when only a CSS variable changed since the last link.
let start_data = {
let shared = &self.shared_data.dense[entity_data_index.index()].value;
if shared.variable_name_hash != u64::MAX {
if let Some(var_store) = variables.get(&shared.variable_name_hash) {
var_store
.get_resolved(entity, variables)
.unwrap_or_else(|| shared.value.clone())
} else {
shared.fallback.clone().unwrap_or_else(|| shared.value.clone())
}
} else {
shared.value.clone()
}
};
transition_state.keyframes.first_mut().unwrap().value = start_data;
} else {
transition_state.keyframes.first_mut().unwrap().value = end.value.clone();
}
transition_state.keyframes.last_mut().unwrap().value = end.value.clone();
transition_state.from_rule =
self.inline_data.sparse[entity_index].data_index.index();
transition_state.to_rule = shared_data_index.index();
let duration = transition_state.duration;
let delay = transition_state.delay;
if transition_state.from_rule != DataIndex::null().index()
&& transition_state.from_rule != transition_state.to_rule
{
self.play_animation(
entity,
rule_animation,
Instant::now(),
duration,
delay,
);
}
} else {
// No transition on the arriving rule — nothing to animate forward.
}
//}
// if let Some(shared_data) = self.shared_data.get_mut(*rule) {
// if shared_data.variable_name_hash != u64::MAX {
// if let Some(prop) = variables.get(&shared_data.variable_name_hash) {
// if let Some(data) = prop.get_with_variables(entity, variables) {
// shared_data.value = data;
// }
// }
// }
// }
let data_index = self.inline_data.sparse[entity_index].data_index;
// Already linked
if !data_index.is_inline() && data_index.index() == shared_data_index.index() {
return false;
}
self.inline_data.sparse[entity_index].data_index =
DataIndex::shared(shared_data_index.index());
return true;
}
}
// No matching rules — entity is leaving whatever rule it was linked to.
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
if !data_index.is_inline()
&& !data_index.is_inherited()
&& data_index != DataIndex::null()
{
let current_dense_idx = data_index.index();
if current_dense_idx < self.shared_data.dense.len() {
let entity_anim_index =
self.inline_data.sparse[entity_index].anim_index as usize;
if entity_anim_index < self.active_animations.len() {
// Mid-animation: reverse the active state in-place so the
// transition picks up from the current visual position.
let current_value = self.get(entity).cloned().unwrap_or_default();
let current_anim = &mut self.active_animations[entity_anim_index];
if current_anim.is_transition() {
let reverse_to = current_anim.from_rule;
if reverse_to < self.shared_data.dense.len() {
current_anim.from_rule = current_anim.to_rule;
current_anim.to_rule = reverse_to;
current_anim.keyframes.first_mut().unwrap().value = current_value;
current_anim.keyframes.last_mut().unwrap().value =
self.shared_data.dense[reverse_to].value.value.clone();
current_anim.dt = current_anim.t - 1.0;
current_anim.start_time = Instant::now();
}
}
} else {
// Animation completed — start a fresh reverse transition using the
// template animation stored on the departing (hover) rule, but only
// if that rule actually defined a transition for this property.
if let Some(departing_anim) = self
.shared_data
.sparse
.iter()
.find(|si| si.index() == current_dense_idx && !si.animation.is_null())
.map(|si| si.animation)
{
if let Some(transition_state) = self.animations.get_mut(departing_anim)
{
let prev_rule = transition_state.from_rule;
if prev_rule < self.shared_data.dense.len() {
let start_value = self.shared_data.dense[current_dense_idx]
.value
.value
.clone();
let end_value =
self.shared_data.dense[prev_rule].value.value.clone();
transition_state.keyframes.first_mut().unwrap().value =
start_value;
transition_state.keyframes.last_mut().unwrap().value =
end_value;
transition_state.from_rule = current_dense_idx;
transition_state.to_rule = prev_rule;
let duration = transition_state.duration;
let delay = transition_state.delay;
if transition_state.from_rule != transition_state.to_rule {
self.play_animation(
entity,
departing_anim,
Instant::now(),
duration,
delay,
);
}
}
}
}
}
}
self.inline_data.sparse[entity_index].data_index = DataIndex::null();
return true;
}
}
false
}
/// Link an entity to some shared data, using a pre-resolved variable snapshot.
///
/// This is identical to [`link`] except that, instead of accepting the live
/// `HashMap<u64, AnimatableVarSet<T>>` (which would require removing `self`
/// from the map to avoid a conflicting borrow), the caller pre-computes a
/// `HashMap<u64, T>` snapshot via [`get_with_variables`] and passes that here.
/// The variable-baking step then simply clones out of the snapshot.
///
/// This removes the per-entity `Vec`-of-keys allocation and the
/// remove / re-insert hashmap churn that the old pattern required.
pub(crate) fn link_with_resolved(
&mut self,
entity: Entity,
rules: &[(Rule, u32)],
resolved_vars: &HashMap<u64, T>,
) -> bool {
let entity_index = entity.index();
// Check if the entity already has some data
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
// If the data is inline then skip linking as inline data overrides shared data
if data_index.is_inline() && !data_index.is_inherited() {
return false;
}
}
// Loop through matched rules and link to the first valid rule
for (rule, _) in rules {
// Bake the resolved variable value into the shared slot, using the
// pre-computed snapshot instead of a live map lookup.
if let Some(shared_data) = self.shared_data.get_mut(*rule) {
if shared_data.variable_name_hash != u64::MAX {
if let Some(data) = resolved_vars.get(&shared_data.variable_name_hash) {
shared_data.value = data.clone();
}
}
}
if let Some(shared_data_index) = self.shared_data.dense_idx(*rule) {
// If the entity doesn't have any previous shared data then create space for it
if entity_index >= self.inline_data.sparse.len() {
self.inline_data.sparse.resize(entity_index + 1, InlineIndex::null());
}
// Get the animation state index of any animations (transitions) defined for the rule
let rule_animation = shared_data_index.animation;
let entity_anim_index = self.inline_data.sparse[entity_index].anim_index as usize;
if entity_anim_index < self.active_animations.len() {
// Already animating
let current_value = self.get(entity).cloned().unwrap_or_default();
let current_anim_state = &mut self.active_animations[entity_anim_index];
let rule_data_index = shared_data_index.data_index as usize;
if current_anim_state.is_transition() {
// Skip if the transition hasn't changed
if current_anim_state.to_rule != rule_data_index {
if rule_data_index == current_anim_state.from_rule {
// Transitioning back to previous rule
current_anim_state.from_rule = current_anim_state.to_rule;
current_anim_state.to_rule = rule_data_index;
current_anim_state.keyframes.first_mut().unwrap().value =
self.shared_data.dense[current_anim_state.from_rule]
.value
.value
.clone();
current_anim_state.keyframes.last_mut().unwrap().value =
self.shared_data.dense[current_anim_state.to_rule]
.value
.value
.clone();
current_anim_state.dt = current_anim_state.t - 1.0;
current_anim_state.start_time = Instant::now();
} else {
// Transitioning to new rule
current_anim_state.to_rule = rule_data_index;
current_anim_state.keyframes.first_mut().unwrap().value =
current_value;
current_anim_state.keyframes.last_mut().unwrap().value =
self.shared_data.dense[current_anim_state.to_rule]
.value
.value
.clone();
current_anim_state.t = 0.0;
current_anim_state.start_time = Instant::now();
}
}
}
} else if let Some(transition_state) = self.animations.get_mut(rule_animation) {
// Safe to unwrap because already checked that the rule exists
let end = self.shared_data.get(*rule).unwrap();
let entity_data_index = self.inline_data.sparse[entity_index].data_index;
if !entity_data_index.is_inline()
&& entity_data_index.index() < self.shared_data.dense.len()
{
// Resolve the start value dynamically so that a stale baked value
// is not used when only a CSS variable changed since the last link.
let start_data = {
let shared = &self.shared_data.dense[entity_data_index.index()].value;
if shared.variable_name_hash != u64::MAX {
resolved_vars
.get(&shared.variable_name_hash)
.cloned()
.or_else(|| shared.fallback.clone())
.unwrap_or_else(|| shared.value.clone())
} else {
shared.value.clone()
}
};
transition_state.keyframes.first_mut().unwrap().value = start_data;
} else {
transition_state.keyframes.first_mut().unwrap().value = end.value.clone();
}
transition_state.keyframes.last_mut().unwrap().value = end.value.clone();
transition_state.from_rule =
self.inline_data.sparse[entity_index].data_index.index();
transition_state.to_rule = shared_data_index.index();
let duration = transition_state.duration;
let delay = transition_state.delay;
if transition_state.from_rule != DataIndex::null().index()
&& transition_state.from_rule != transition_state.to_rule
{
self.play_animation(
entity,
rule_animation,
Instant::now(),
duration,
delay,
);
}
} else {
// No transition on the arriving rule — nothing to animate forward.
}
let data_index = self.inline_data.sparse[entity_index].data_index;
// Already linked
if !data_index.is_inline() && data_index.index() == shared_data_index.index() {
return false;
}
self.inline_data.sparse[entity_index].data_index =
DataIndex::shared(shared_data_index.index());
return true;
}
}
// No matching rules — entity is leaving whatever rule it was linked to.
if entity_index < self.inline_data.sparse.len() {
let data_index = self.inline_data.sparse[entity_index].data_index;
if !data_index.is_inline()
&& !data_index.is_inherited()
&& data_index != DataIndex::null()
{
let current_dense_idx = data_index.index();
if current_dense_idx < self.shared_data.dense.len() {
let entity_anim_index =
self.inline_data.sparse[entity_index].anim_index as usize;
if entity_anim_index < self.active_animations.len() {
// Mid-animation: reverse the active state in-place so the
// transition picks up from the current visual position.
let current_value = self.get(entity).cloned().unwrap_or_default();
let current_anim = &mut self.active_animations[entity_anim_index];
if current_anim.is_transition() {
let reverse_to = current_anim.from_rule;
if reverse_to < self.shared_data.dense.len() {
current_anim.from_rule = current_anim.to_rule;
current_anim.to_rule = reverse_to;
current_anim.keyframes.first_mut().unwrap().value = current_value;
current_anim.keyframes.last_mut().unwrap().value =
self.shared_data.dense[reverse_to].value.value.clone();
current_anim.dt = current_anim.t - 1.0;
current_anim.start_time = Instant::now();
}
}
} else {
// Animation completed — start a fresh reverse transition using the
// template animation stored on the departing (hover) rule, but only
// if that rule actually defined a transition for this property.
if let Some(departing_anim) = self
.shared_data
.sparse
.iter()
.find(|si| si.index() == current_dense_idx && !si.animation.is_null())
.map(|si| si.animation)
{
if let Some(transition_state) = self.animations.get_mut(departing_anim)
{
let prev_rule = transition_state.from_rule;
if prev_rule < self.shared_data.dense.len() {
let start_value = self.shared_data.dense[current_dense_idx]
.value
.value
.clone();
let end_value =
self.shared_data.dense[prev_rule].value.value.clone();
transition_state.keyframes.first_mut().unwrap().value =
start_value;
transition_state.keyframes.last_mut().unwrap().value =
end_value;
transition_state.from_rule = current_dense_idx;
transition_state.to_rule = prev_rule;
let duration = transition_state.duration;
let delay = transition_state.delay;
if transition_state.from_rule != transition_state.to_rule {
self.play_animation(
entity,
departing_anim,
Instant::now(),
duration,
delay,
);
}
}
}
}
}
}
self.inline_data.sparse[entity_index].data_index = DataIndex::null();
return true;
}
}
false
}
/// Clear all rules and animations from the storage.
pub fn clear_rules(&mut self) {
// Remove transitions
for index in self.shared_data.sparse.iter() {
let animation = index.animation;
self.animations.remove(animation);
}
self.shared_data.clear();
for index in self.inline_data.sparse.iter_mut() {
if !index.data_index.is_inline() {
index.data_index = DataIndex::null();
}
}
}
}