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
//! A wrapper for a variable that hold additional flag that tells that initial value was changed in runtime.
//!
//! For more info see [`InheritableVariable`]

use crate::{
    reflect::{prelude::*, ReflectArray, ReflectInheritableVariable, ReflectList},
    visitor::prelude::*,
};
use bitflags::bitflags;
use std::{
    any::{Any, TypeId},
    cell::Cell,
    fmt::Debug,
    ops::{Deref, DerefMut},
};

#[derive(Reflect, Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
#[repr(transparent)]
pub struct VariableFlags(u8);

bitflags! {
    impl VariableFlags: u8 {
        /// Nothing.
        const NONE = 0;
        /// A variable was externally modified.
        const MODIFIED = 0b0000_0001;
        /// A variable must be synced with respective variable from data model.
        const NEED_SYNC = 0b0000_0010;
    }
}

/// An error that could occur during inheritance.
#[derive(Debug)]
pub enum InheritError {
    /// Types of properties mismatch.
    TypesMismatch {
        /// Type of left property.
        left_type: TypeId,
        /// Type of right property.
        right_type: TypeId,
    },
}

/// A wrapper for a variable that hold additional flag that tells that initial value was changed in runtime.
///
/// InheritableVariables are used for resource inheritance system. Resource inheritance may just sound weird,
/// but the idea behind it is very simple - take property values from parent resource if the value in current
/// hasn't changed in runtime.
///
/// To get better understanding, let's look at very simple example. Imagine you have a scene with a 3d model
/// instance. Now you realizes that the 3d model has a misplaced object and you need to fix it, you open a
/// 3D modelling software (Blender, 3Ds max, etc) and move the object to a correct spot and re-save the 3D model.
/// The question is: what should happen with the instance of the object in the scene? Logical answer would be:
/// if it hasn't been modified, then just take the new position from the 3D model. This is where inheritable
/// variable comes into play. If you've change the value of such variable, it will remember changes and the object
/// will stay on its new position instead of changed.
///
/// # Deref and DerefMut
///
/// Access via Deref provides access to inner variable. **DerefMut marks variable as modified** and returns a
/// mutable reference to inner variable.
#[derive(Debug)]
pub struct InheritableVariable<T> {
    value: T,
    flags: Cell<VariableFlags>,
}

impl<T: Clone> Clone for InheritableVariable<T> {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            flags: self.flags.clone(),
        }
    }
}

impl<T> From<T> for InheritableVariable<T> {
    fn from(v: T) -> Self {
        InheritableVariable::new_modified(v)
    }
}

impl<T: PartialEq> PartialEq for InheritableVariable<T> {
    fn eq(&self, other: &Self) -> bool {
        // `custom` flag intentionally ignored!
        self.value.eq(&other.value)
    }
}

impl<T: Eq> Eq for InheritableVariable<T> {}

impl<T: Default> Default for InheritableVariable<T> {
    fn default() -> Self {
        Self {
            value: T::default(),
            flags: Cell::new(VariableFlags::MODIFIED),
        }
    }
}

impl<T: Clone> InheritableVariable<T> {
    /// Clones wrapped value.
    pub fn clone_inner(&self) -> T {
        self.value.clone()
    }

    /// Tries to sync a value in a data model with a value in the inheritable variable. The value
    /// will be synced only if it was marked as needs sync.
    pub fn try_sync_model<S: FnOnce(T)>(&self, setter: S) -> bool {
        if self.need_sync() {
            // Drop flag first.
            let mut flags = self.flags.get();
            flags.remove(VariableFlags::NEED_SYNC);
            self.flags.set(flags);

            // Set new value in a data model.
            (setter)(self.value.clone());

            true
        } else {
            false
        }
    }
}

impl<T> InheritableVariable<T> {
    /// Creates new modified variable from given value. This method should always be used to create inheritable
    /// variables in the engine.
    pub fn new_modified(value: T) -> Self {
        Self {
            value,
            flags: Cell::new(VariableFlags::MODIFIED),
        }
    }

    /// Creates new variable without any flags set.
    pub fn new_non_modified(value: T) -> Self {
        Self {
            value,
            flags: Cell::new(VariableFlags::NONE),
        }
    }

    /// Creates new variable from a given value with custom flags.
    pub fn new_with_flags(value: T, flags: VariableFlags) -> Self {
        Self {
            value,
            flags: Cell::new(flags),
        }
    }

    /// Replaces value and also raises the [`VariableFlags::MODIFIED`] flag.
    pub fn set_value_and_mark_modified(&mut self, value: T) -> T {
        self.mark_modified_and_need_sync();
        std::mem::replace(&mut self.value, value)
    }

    /// Replaces value and flags.
    pub fn set_value_with_flags(&mut self, value: T, flags: VariableFlags) -> T {
        self.flags.set(flags);
        std::mem::replace(&mut self.value, value)
    }

    /// Replaces current value without marking the variable modified.
    pub fn set_value_silent(&mut self, value: T) -> T {
        std::mem::replace(&mut self.value, value)
    }

    /// Returns true if the respective data model's variable must be synced.
    pub fn need_sync(&self) -> bool {
        self.flags.get().contains(VariableFlags::NEED_SYNC)
    }

    /// Returns a reference to the wrapped value.
    pub fn get_value_ref(&self) -> &T {
        &self.value
    }

    /// Returns a mutable reference to the wrapped value.
    ///
    /// # Important notes.
    ///
    /// The method raises `modified` flag, no matter if actual modification was made!
    pub fn get_value_mut_and_mark_modified(&mut self) -> &mut T {
        self.mark_modified_and_need_sync();
        &mut self.value
    }

    /// Returns a mutable reference to the wrapped value.
    ///
    /// # Important notes.
    ///
    /// This method does not mark the value as modified!
    pub fn get_value_mut_silent(&mut self) -> &mut T {
        &mut self.value
    }

    /// Returns true if variable was modified and should not be overwritten during property inheritance.
    pub fn is_modified(&self) -> bool {
        self.flags.get().contains(VariableFlags::MODIFIED)
    }

    /// Marks value as modified, so its value won't be overwritten during property inheritance.
    pub fn mark_modified(&mut self) {
        self.flags
            .get_mut()
            .insert(VariableFlags::MODIFIED | VariableFlags::NEED_SYNC);
    }

    /// Deconstructs the variable and returns the wrapped value.
    pub fn take(self) -> T {
        self.value
    }

    fn mark_modified_and_need_sync(&mut self) {
        self.flags
            .get_mut()
            .insert(VariableFlags::MODIFIED | VariableFlags::NEED_SYNC);
    }
}

impl<T> Deref for InheritableVariable<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for InheritableVariable<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.mark_modified_and_need_sync();
        &mut self.value
    }
}

impl<T> Visit for InheritableVariable<T>
where
    T: Visit,
{
    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
        let mut visited = false;

        if visitor.is_reading() {
            // Try to visit inner value first, this is very useful if user decides to make their
            // variable inheritable, but still keep backward compatibility.
            visited = self.value.visit(name, visitor).is_ok();
            self.flags.get_mut().insert(VariableFlags::MODIFIED);
        }

        if !visited {
            if visitor.is_reading() {
                // The entire region could be missing if the variable wasn't modified.
                if let Ok(mut region) = visitor.enter_region(name) {
                    let _ = self.value.visit("Value", &mut region);
                    self.flags.get_mut().0.visit("Flags", &mut region)?;
                } else {
                    // Default flags contains `modified` flag, we need to remove it if there's no
                    // region at all.
                    self.flags.get_mut().remove(VariableFlags::MODIFIED);
                }
            } else if self.flags.get().contains(VariableFlags::MODIFIED) {
                let mut region = visitor.enter_region(name)?;
                self.value.visit("Value", &mut region)?;
                self.flags.get_mut().0.visit("Flags", &mut region)?;
            } else {
                // Non-modified variables do not write anything.
            }
        }

        Ok(())
    }
}

impl<T> Reflect for InheritableVariable<T>
where
    T: Reflect + Clone + PartialEq + Debug,
{
    fn type_name(&self) -> &'static str {
        self.value.type_name()
    }

    fn doc(&self) -> &'static str {
        self.value.doc()
    }

    fn fields_info(&self, func: &mut dyn FnMut(Vec<FieldInfo>)) {
        self.value.fields_info(func)
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        Box::new(self.value).into_any()
    }

    fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
        self.value.as_any(func)
    }

    fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
        self.value.as_any_mut(func)
    }

    fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
        self.value.as_reflect(func)
    }

    fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
        self.value.as_reflect_mut(func)
    }

    fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
        self.mark_modified_and_need_sync();
        self.value.set(value)
    }

    fn set_field(
        &mut self,
        field: &str,
        value: Box<dyn Reflect>,
        func: &mut dyn FnMut(Result<Box<dyn Reflect>, Box<dyn Reflect>>),
    ) {
        self.mark_modified_and_need_sync();
        self.value.set_field(field, value, func)
    }

    fn fields(&self, func: &mut dyn FnMut(Vec<&dyn Reflect>)) {
        self.value.fields(func)
    }

    fn fields_mut(&mut self, func: &mut dyn FnMut(Vec<&mut dyn Reflect>)) {
        self.value.fields_mut(func)
    }

    fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
        self.value.field(name, func)
    }

    fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
        // Any modifications inside of compound structs must mark the variable as modified.
        self.mark_modified_and_need_sync();
        self.value.field_mut(name, func)
    }

    fn as_array(&self, func: &mut dyn FnMut(Option<&dyn ReflectArray>)) {
        self.value.as_array(func)
    }

    fn as_array_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectArray>)) {
        // Any modifications inside of inheritable arrays must mark the variable as modified.
        self.mark_modified_and_need_sync();
        self.value.as_array_mut(func)
    }

    fn as_list(&self, func: &mut dyn FnMut(Option<&dyn ReflectList>)) {
        self.value.as_list(func)
    }

    fn as_list_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectList>)) {
        // Any modifications inside of inheritable lists must mark the variable as modified.
        self.mark_modified_and_need_sync();
        self.value.as_list_mut(func)
    }

    fn as_inheritable_variable(
        &self,
        func: &mut dyn FnMut(Option<&dyn ReflectInheritableVariable>),
    ) {
        func(Some(self))
    }

    fn as_inheritable_variable_mut(
        &mut self,
        func: &mut dyn FnMut(Option<&mut dyn ReflectInheritableVariable>),
    ) {
        func(Some(self))
    }
}

impl<T> ReflectInheritableVariable for InheritableVariable<T>
where
    T: Reflect + Clone + PartialEq + Debug,
{
    fn try_inherit(
        &mut self,
        parent: &dyn ReflectInheritableVariable,
    ) -> Result<Option<Box<dyn Reflect>>, InheritError> {
        let mut result: Result<Option<Box<dyn Reflect>>, InheritError> = Ok(None);

        // Cast directly to inner type, because any type that implements ReflectInheritableVariable,
        // has delegating methods for almost every method of Reflect trait implementation.
        parent.as_reflect(&mut |parent| {
            parent.downcast_ref::<T>(&mut |downcasted| match downcasted {
                Some(parent_value) => {
                    if !self.is_modified() {
                        let mut parent_value_clone = parent_value.clone();

                        mark_inheritable_properties_non_modified(&mut parent_value_clone);

                        result = Ok(Some(Box::new(std::mem::replace(
                            &mut self.value,
                            parent_value_clone,
                        ))));
                    }
                }
                None => {
                    result = Err(InheritError::TypesMismatch {
                        left_type: TypeId::of::<Self>(),
                        right_type: parent.type_id(),
                    });
                }
            });
        });

        result
    }

    fn reset_modified_flag(&mut self) {
        self.flags.get_mut().remove(VariableFlags::MODIFIED)
    }

    fn flags(&self) -> VariableFlags {
        self.flags.get()
    }

    fn set_flags(&mut self, flags: VariableFlags) {
        self.flags.set(flags)
    }

    fn is_modified(&self) -> bool {
        self.is_modified()
    }

    fn value_equals(&self, other: &dyn ReflectInheritableVariable) -> bool {
        let mut output_result = false;
        other.as_reflect(&mut |reflect| {
            reflect.downcast_ref::<T>(&mut |result| {
                output_result = match result {
                    Some(other) => &self.value == other,
                    None => false,
                };
            })
        });
        output_result
    }

    fn clone_value_box(&self) -> Box<dyn Reflect> {
        Box::new(self.value.clone())
    }

    fn mark_modified(&mut self) {
        self.mark_modified()
    }

    fn inner_value_mut(&mut self) -> &mut dyn Reflect {
        &mut self.value
    }

    fn inner_value_ref(&self) -> &dyn Reflect {
        &self.value
    }
}

/// Simultaneously walks over fields of given child and parent and tries to inherit values of properties
/// of child with parent's properties. It is done recursively for every fields in entities.
///
/// ## How it works
///
/// In general, it uses reflection to iterate over child and parent properties and trying to inherit values.
/// Child's field will take parent's field value only if child's field is **non-modified**. There are one
/// edge case in inheritance: collections.
///
/// Inheritance for collections itself works the same as described above, however the content of collections
/// can only be inherited if their sizes are equal. Also, since inheritance uses plain copy of inner data of
/// inheritable variables, it works in a special way.
///
/// ```text
/// Child                                       Parent (root)
///     InheritableVariableA            <-         InheritableVariableA*
///     InheritableCollection*          ->         InheritableCollection*
///         Item0                                       Item0
///             InheritableVariableB*   ->                  InheritableVariableB*
///             InheritableVariableC    <-                  InheritableVariableC*
///         Item1                                       Item1
///             ..                                          ..
///         ..                                          ..
///         ItemN                                       ItemN
///             ..                                          ..
///
/// * - means that the variable was modified
/// ```
///
/// At first, `InheritableVariableA` will be copied from the parent as usual. Next, the inheritable collection
/// won't be copied (because it is modified), however its items will be inherited separately.
/// `InheritableVariableB` won't be copied either (since it is modified too), but `InheritableVariableC` **will**
/// be copied from parent.
pub fn try_inherit_properties(
    child: &mut dyn Reflect,
    parent: &dyn Reflect,
    ignored_types: &[TypeId],
) -> Result<(), InheritError> {
    let child_type_id = (*child).type_id();
    let parent_type_id = (*parent).type_id();

    if ignored_types.contains(&child_type_id) || ignored_types.contains(&parent_type_id) {
        return Ok(());
    }

    if child_type_id != parent_type_id {
        return Err(InheritError::TypesMismatch {
            left_type: (*child).type_id(),
            right_type: (*parent).type_id(),
        });
    }

    let mut result = None;

    child.as_inheritable_variable_mut(&mut |inheritable_child| {
        if let Some(inheritable_child) = inheritable_child {
            parent.as_inheritable_variable(&mut |inheritable_parent| {
                if let Some(inheritable_parent) = inheritable_parent {
                    if let Err(e) = inheritable_child.try_inherit(inheritable_parent) {
                        result = Some(Err(e));
                    }

                    if !matches!(result, Some(Err(_))) {
                        result = Some(try_inherit_properties(
                            inheritable_child.inner_value_mut(),
                            inheritable_parent.inner_value_ref(),
                            ignored_types,
                        ));
                    }
                }
            })
        }
    });

    if result.is_none() {
        child.as_array_mut(&mut |child_collection| {
            if let Some(child_collection) = child_collection {
                parent.as_array(&mut |parent_collection| {
                    if let Some(parent_collection) = parent_collection {
                        if child_collection.reflect_len() == parent_collection.reflect_len() {
                            for i in 0..child_collection.reflect_len() {
                                // Sparse arrays (like Pool) could have empty entries.
                                if let (Some(child_item), Some(parent_item)) = (
                                    child_collection.reflect_index_mut(i),
                                    parent_collection.reflect_index(i),
                                ) {
                                    if let Err(e) = try_inherit_properties(
                                        child_item,
                                        parent_item,
                                        ignored_types,
                                    ) {
                                        result = Some(Err(e));

                                        break;
                                    }
                                }
                            }
                        }
                    }
                })
            }
        })
    }

    if result.is_none() {
        child.fields_mut(&mut |mut child_fields| {
            parent.fields(&mut |parent_fields| {
                for (child_field, parent_field) in child_fields.iter_mut().zip(parent_fields) {
                    // Look into inner properties recursively and try to inherit them. This is mandatory step, because inner
                    // fields may also be InheritableVariable<T>.
                    if let Err(e) =
                        try_inherit_properties(*child_field, parent_field, ignored_types)
                    {
                        result = Some(Err(e));
                    }

                    if matches!(result, Some(Err(_))) {
                        break;
                    }
                }
            })
        });
    }

    result.unwrap_or(Ok(()))
}

pub fn do_with_inheritable_variables<F>(root: &mut dyn Reflect, func: &mut F)
where
    F: FnMut(&mut dyn ReflectInheritableVariable),
{
    root.apply_recursively_mut(&mut |object| {
        object.as_inheritable_variable_mut(&mut |variable| {
            if let Some(variable) = variable {
                func(variable);
            }
        });
    })
}

pub fn mark_inheritable_properties_non_modified(object: &mut dyn Reflect) {
    do_with_inheritable_variables(object, &mut |variable| variable.reset_modified_flag());
}

pub fn mark_inheritable_properties_modified(object: &mut dyn Reflect) {
    do_with_inheritable_variables(object, &mut |variable| variable.mark_modified());
}

#[cfg(test)]
mod test {
    use std::{cell::Cell, ops::DerefMut};

    use crate::{
        reflect::{prelude::*, ReflectInheritableVariable},
        variable::{try_inherit_properties, InheritableVariable, VariableFlags},
        visitor::{Visit, Visitor},
    };

    #[derive(Reflect, Clone, Debug, PartialEq)]
    struct Foo {
        value: InheritableVariable<f32>,
    }

    #[derive(Reflect, Clone, Debug, PartialEq)]
    struct Bar {
        foo: Foo,

        other_value: InheritableVariable<String>,
    }

    #[test]
    fn test_property_inheritance_via_reflection() {
        let mut parent = Bar {
            foo: Foo {
                value: InheritableVariable::new_non_modified(1.23),
            },
            other_value: InheritableVariable::new_non_modified("Foobar".to_string()),
        };

        let mut child = parent.clone();

        // Try inherit non-modified, the result objects must be equal.
        try_inherit_properties(&mut child, &parent, &[]).unwrap();
        assert_eq!(parent, child);

        // Then modify parent's and child's values.
        parent
            .other_value
            .set_value_and_mark_modified("Baz".to_string());
        assert!(ReflectInheritableVariable::is_modified(&parent.other_value),);

        child.foo.value.set_value_and_mark_modified(3.21);
        assert!(ReflectInheritableVariable::is_modified(&child.foo.value));

        try_inherit_properties(&mut child, &parent, &[]).unwrap();

        // This property reflects parent's changes, because it is non-modified.
        assert_eq!(child.other_value.value, "Baz".to_string());
        // This property must remain unchanged, because it is modified.
        assert_eq!(child.foo.value.value, 3.21);
    }

    #[test]
    fn test_inheritable_variable_equality() {
        let va = InheritableVariable::new_non_modified(1.23);
        let vb = InheritableVariable::new_non_modified(1.23);

        assert!(va.value_equals(&vb))
    }

    #[derive(Reflect, Debug)]
    enum SomeEnum {
        Bar(InheritableVariable<f32>),
        Baz {
            foo: InheritableVariable<f32>,
            foobar: InheritableVariable<u32>,
        },
    }

    #[test]
    fn test_enum_inheritance_tuple() {
        let mut child = SomeEnum::Bar(InheritableVariable::new_non_modified(1.23));
        let parent = SomeEnum::Bar(InheritableVariable::new_non_modified(3.21));

        try_inherit_properties(&mut child, &parent, &[]).unwrap();

        if let SomeEnum::Bar(value) = child {
            assert_eq!(*value, 3.21);
        } else {
            unreachable!()
        }
    }

    #[test]
    fn test_enum_inheritance_struct() {
        let mut child = SomeEnum::Baz {
            foo: InheritableVariable::new_non_modified(1.23),
            foobar: InheritableVariable::new_non_modified(123),
        };
        let parent = SomeEnum::Baz {
            foo: InheritableVariable::new_non_modified(3.21),
            foobar: InheritableVariable::new_non_modified(321),
        };

        try_inherit_properties(&mut child, &parent, &[]).unwrap();

        if let SomeEnum::Baz { foo, foobar } = child {
            assert_eq!(*foo, 3.21);
            assert_eq!(*foobar, 321);
        } else {
            unreachable!()
        }
    }

    #[test]
    fn test_collection_inheritance() {
        #[derive(Reflect, Clone, Debug, PartialEq)]
        struct Foo {
            some_data: f32,
        }

        #[derive(Reflect, Clone, Debug, PartialEq)]
        struct CollectionItem {
            foo: InheritableVariable<Foo>,
            bar: InheritableVariable<u32>,
        }

        #[derive(Reflect, Clone, Debug, PartialEq)]
        struct MyEntity {
            collection: InheritableVariable<Vec<CollectionItem>>,
        }

        let parent = MyEntity {
            collection: InheritableVariable::new_modified(vec![CollectionItem {
                foo: InheritableVariable::new_modified(Foo { some_data: 123.321 }),
                bar: InheritableVariable::new_modified(321),
            }]),
        };

        let mut child = MyEntity {
            collection: InheritableVariable::new_modified(vec![CollectionItem {
                foo: InheritableVariable::new_modified(Foo { some_data: 321.123 }),
                bar: InheritableVariable::new_non_modified(321),
            }]),
        };

        try_inherit_properties(&mut child, &parent, &[]).unwrap();

        // Flags must be transferred correctly.
        let item = &child.collection[0];
        assert!(!item.bar.is_modified());
        assert_eq!(item.bar.value, 321);

        assert_eq!(item.foo.value, Foo { some_data: 321.123 });
        assert!(item.foo.is_modified());
    }

    #[test]
    fn test_compound_inheritance() {
        #[derive(Reflect, Clone, Debug, PartialEq, Eq)]
        struct SomeComplexData {
            foo: InheritableVariable<u32>,
        }

        #[derive(Reflect, Clone, Debug, PartialEq)]
        struct MyEntity {
            some_field: InheritableVariable<f32>,

            // This field won't be inherited correctly - at first it will take parent's value and then
            // will try to inherit inner fields, but its is useless step, because inner data is already
            // a full copy of parent's field value. This absolutely ok, it just indicates issues in user
            // code.
            incorrectly_inheritable_data: InheritableVariable<SomeComplexData>,

            // Subfields of this field will be correctly inherited, because the field itself is not inheritable.
            inheritable_data: SomeComplexData,
        }

        let mut child = MyEntity {
            some_field: InheritableVariable::new_non_modified(1.23),
            incorrectly_inheritable_data: InheritableVariable::new_non_modified(SomeComplexData {
                foo: InheritableVariable::new_modified(222),
            }),
            inheritable_data: SomeComplexData {
                foo: InheritableVariable::new_modified(222),
            },
        };

        let parent = MyEntity {
            some_field: InheritableVariable::new_non_modified(3.21),
            incorrectly_inheritable_data: InheritableVariable::new_non_modified(SomeComplexData {
                foo: InheritableVariable::new_non_modified(321),
            }),
            inheritable_data: SomeComplexData {
                foo: InheritableVariable::new_modified(321),
            },
        };

        assert!(try_inherit_properties(&mut child, &parent, &[]).is_ok());

        assert_eq!(child.some_field.value, 3.21);
        // These fields are equal, despite the fact that they're marked as modified.
        // This is due incorrect usage of inheritance.
        assert_eq!(
            child.incorrectly_inheritable_data.foo.value,
            parent.incorrectly_inheritable_data.foo.value
        );
        // These fields are not equal, as it should be.
        assert_ne!(
            child.inheritable_data.foo.value,
            parent.inheritable_data.foo.value
        );
    }

    #[test]
    fn inheritable_variable_from_t() {
        assert_eq!(
            InheritableVariable::from(42),
            InheritableVariable {
                value: 42,
                ..Default::default()
            }
        );
    }

    #[test]
    fn default_for_inheritable_variable() {
        assert_eq!(
            InheritableVariable::<i32>::default(),
            InheritableVariable {
                value: 0,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn inheritable_variable_clone_inner() {
        let v = InheritableVariable::from(42);

        assert_eq!(v.clone_inner(), 42);
    }

    #[test]
    fn inheritable_variable_try_sync_model() {
        let v = InheritableVariable::from(42);
        assert!(!v.try_sync_model(|s| println!("{}", s)));

        let v = InheritableVariable::new_with_flags(42, VariableFlags::NEED_SYNC);
        assert!(v.try_sync_model(|s| println!("{}", s)));
    }

    #[test]
    fn inheritable_variable_new_with_flags() {
        let v = InheritableVariable::new_with_flags(42, VariableFlags::MODIFIED);

        assert_eq!(
            v,
            InheritableVariable {
                value: 42,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn inheritable_variable_set_value_with_flags() {
        let mut v = InheritableVariable::from(42);
        let res = v.set_value_with_flags(15, VariableFlags::NEED_SYNC);

        assert_eq!(res, 42);
        assert_eq!(
            v,
            InheritableVariable {
                value: 15,
                flags: Cell::new(VariableFlags::NEED_SYNC),
            }
        );
    }

    #[test]
    fn inheritable_variable_set_value_silent() {
        let mut v = InheritableVariable::from(42);
        let res = v.set_value_silent(15);

        assert_eq!(res, 42);
        assert_eq!(
            v,
            InheritableVariable {
                value: 15,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn inheritable_variable_need_sync() {
        let v = InheritableVariable::from(42);
        assert!(!v.need_sync());

        let v = InheritableVariable::new_with_flags(42, VariableFlags::NEED_SYNC);
        assert!(v.need_sync());
    }

    #[test]
    fn inheritable_variable_get_value_ref() {
        let v = InheritableVariable::from(42);

        assert_eq!(v.get_value_ref(), &42);
    }

    #[test]
    fn inheritable_variable_get_value_mut_and_mark_modified() {
        let mut v = InheritableVariable::from(42);

        assert_eq!(v.get_value_mut_and_mark_modified(), &mut 42);
        assert_eq!(
            v,
            InheritableVariable {
                value: 42,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn inheritable_variable_get_value_mut_silent() {
        let mut v = InheritableVariable::from(42);

        assert_eq!(v.get_value_mut_silent(), &mut 42);
    }

    #[test]
    fn inheritable_variable_is_modified() {
        let v = InheritableVariable::new_with_flags(42, VariableFlags::NONE);
        assert!(!v.is_modified());

        let v = InheritableVariable::new_with_flags(42, VariableFlags::MODIFIED);
        assert!(v.is_modified());
    }

    #[test]
    fn inheritable_variable_mark_modified() {
        let mut v = InheritableVariable::new_with_flags(42, VariableFlags::NONE);
        v.mark_modified();

        assert_eq!(
            v,
            InheritableVariable {
                value: 42,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn inheritable_variable_take() {
        let v = InheritableVariable::from(42);

        assert_eq!(v.take(), 42);
    }

    #[test]
    fn deref_mut_for_inheritable_variable() {
        let mut v = InheritableVariable::new_with_flags(42, VariableFlags::NONE);
        let res = v.deref_mut();

        assert_eq!(res, &mut 42);
        assert_eq!(
            v,
            InheritableVariable {
                value: 42,
                flags: Cell::new(VariableFlags::MODIFIED),
            }
        );
    }

    #[test]
    fn visit_for_inheritable_variable() {
        let mut v = InheritableVariable::from(42);
        let mut visitor = Visitor::default();

        assert!(v.visit("name", &mut visitor).is_ok());
    }

    #[test]
    fn inheritable_variable_type_name() {
        let v = InheritableVariable::from(42);

        assert_eq!(v.type_name(), "i32");
    }

    #[test]
    fn inheritable_variable_doc() {
        let v = InheritableVariable::from(42);

        assert_eq!(v.doc(), "");
    }

    #[test]
    fn inheritable_variable_flags() {
        let v = InheritableVariable::new_with_flags(42, VariableFlags::NONE);

        assert_eq!(v.flags(), VariableFlags::NONE);
    }

    #[test]
    fn inheritable_variable_set_flags() {
        let mut v = InheritableVariable::new_with_flags(42, VariableFlags::NONE);
        v.set_flags(VariableFlags::NEED_SYNC);

        assert_eq!(v.flags(), VariableFlags::NEED_SYNC);
    }
}