]> git.bts.cx Git - jurassic-tween.git/blob - Scripts/Runtime/Internal/ComponentStateCaptor.cs
[FEATURE] Initial Release
[jurassic-tween.git] / Scripts / Runtime / Internal / ComponentStateCaptor.cs
1 //
2 // ComponentStateCaptor.cs
3 // JurassicTween
4 //
5 // Created by Benjamin Sherratt on 04/05/2021.
6 // Copyright © 2021 SKFX Ltd. All rights reserved.
7 //
8
9 using System;
10 using System.Collections.Generic;
11 using UnityEngine;
12
13 namespace JurassicTween.Internal {
14     public struct ComponentState {
15         public float[] values;
16
17         public ComponentState(float[] values) {
18             this.values = values;
19         }
20     }
21     public struct ComponentStateDelta {
22         public struct Range {
23             public float start;
24             public float end;
25
26             public Range(float start, float end) {
27                 this.start = start;
28                 this.end = end;
29             }
30         }
31
32         public Dictionary<string, Range> rangeByAnimationKey;
33
34         public ComponentStateDelta(Dictionary<string, Range> rangeByAnimationKey) {
35             this.rangeByAnimationKey = rangeByAnimationKey;
36         }
37     }
38
39     public interface IComponentStateGetter {
40         ComponentState GetComponentState(Component component);
41     }
42
43     public interface IComponentStateDeltaGenerator {
44         ComponentStateDelta GenerateComponentStateDelta(ComponentState startState, ComponentState endState);
45     }
46
47     public interface IComponentStateCaptor : IComponentStateGetter, IComponentStateDeltaGenerator {
48     }
49
50     public static class ComponentStateCaptor {
51         static Dictionary<Type, IComponentStateCaptor> stateCaptorByType;
52
53         public static IComponentStateCaptor GetStateCaptor(this Component component) {
54             Type componentType = component.GetType();
55
56             if (stateCaptorByType == null) {
57                 stateCaptorByType = new Dictionary<Type, IComponentStateCaptor>();
58                 CreateUnityInternalCaptors();
59             }
60
61             IComponentStateCaptor stateCaptor;
62             if (stateCaptorByType.ContainsKey(componentType)) {
63                 stateCaptor = stateCaptorByType[componentType];
64             } else {
65                 stateCaptor = new GenericComponentStateCaptor(componentType);
66                 stateCaptorByType[componentType] = stateCaptor;
67             }
68
69             return stateCaptor;
70         }
71
72         static void CreateUnityInternalCaptors() {
73             // Add the custom captors for Unity internals...
74             stateCaptorByType[typeof(Transform)] = new TransformComponentStateCaptor();
75         }
76     }
77 }