-
Notifications
You must be signed in to change notification settings - Fork 22
/
BContext.cs
386 lines (343 loc) · 16.3 KB
/
BContext.cs
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
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using UnityEngine;
using UnityEngine.Serialization;
namespace Binject {
/// <summary>
/// A container for dependencies. You can use contexts to group dependencies.
/// </summary>
[ExecuteAlways]
[DisallowMultipleComponent]
[DefaultExecutionOrder( -10 )]
[AddComponentMenu( "Binject/Binject Context" )]
public sealed class BContext : MonoBehaviour {
[Tooltip( "used for when you want to use a specific context but don't have access to it directly; you can find " +
"it using it's Group number." )]
[SerializeField] internal ushort Group;
[FormerlySerializedAs( "ObjectDependencies" )]
[Tooltip( "List of injectable Unity Objects as dependency." )]
[SerializeField] internal List<UnityEngine.Object> UnityObjectDependencies = new( 8 );
[Tooltip( "List of injectable non Unity Object classes as dependency." )]
[SerializeReference] internal List<object> ClassDependencies = new( 8 );
[Tooltip( "List of injectable value types (struct) as dependency.\n" +
"Elements added from inspector will be boxed." )]
[SerializeReference] internal List<BoxedValueHolder> StructDependencies_Serialized = new( 8 );
[NonSerialized] readonly List<IValueHolder> _structDependencies = new( 8 );
[NonSerialized] readonly HashSet<Type> _dependencyTypes = new( 16, new TypeComparer() );
[NonSerialized] bool _inited;
[NonSerialized] bool _addedToManager;
SceneHandle _lastSceneHandle;
Transform _lastParent;
int _lastSiblingIndex;
#if UNITY_EDITOR
/// <summary>
/// When true, <see cref="StructDependencies_Serialized"/> will be updated.
/// </summary>
[NonSerialized] internal bool IsEditorInspecting_EditorOnly;
#endif
#if UNITY_EDITOR
void OnValidate() {
if (Application.isPlaying) return;
// fix broken lists
StringBuilder sb = new( 128 );
for (int i = 0; i < ClassDependencies.Count; i++)
if (ClassDependencies[i] == null) {
sb.AppendLine( $" - class at {i}: was null" );
ClassDependencies.RemoveAt( i-- );
}
for (int i = 0; i < StructDependencies_Serialized.Count; i++) {
if (StructDependencies_Serialized[i] == null || StructDependencies_Serialized[i].BoxAndGetValue() == null) {
StructDependencies_Serialized.RemoveAt( i-- );
}
}
// delete duplicates
for (int i = 0; i < UnityObjectDependencies.Count - 1; i++)
for (int j = i + 1; j < UnityObjectDependencies.Count; j++)
if ((UnityObjectDependencies[i] == null && UnityObjectDependencies[j] == null) ||
(UnityObjectDependencies[i].GetType() == UnityObjectDependencies[j].GetType()))
{
sb.AppendLine( $" - Unity Object at [{j}]: duplicate of [{i}]" );
UnityObjectDependencies.RemoveAt( j-- );
}
for (int i = 0; i < ClassDependencies.Count - 1; i++)
for (int j = i + 1; j < ClassDependencies.Count; j++)
if (ClassDependencies[i].GetType() == ClassDependencies[j].GetType()) {
sb.AppendLine( $" - class at [{j}]: duplicate of [{i}]" );
ClassDependencies.RemoveAt( j-- );
}
for (int i = 0; i < StructDependencies_Serialized.Count - 1; i++)
for (int j = i + 1; j < StructDependencies_Serialized.Count; j++)
if (StructDependencies_Serialized[i].GetValueType() == StructDependencies_Serialized[j].GetValueType()) {
sb.AppendLine( $" - struct at [{j}]: duplicate of [{i}]" );
StructDependencies_Serialized.RemoveAt( j-- );
}
if (sb.Length > 0)
Debug.LogWarning( $"Binject Context of {name} removed some dependencies:\n{sb}" );
// support in-editor injection
InitializeIfHaveNot();
AddToManagerIfNotAddedTo();
ReportSceneChangeOrRemoveFromManagerIfPossible();
ReportTransformHierarchyChangeIfPossible();
}
#endif
void Awake() {
_structDependencies.Clear();
ApplyAllSerializedStructs();
InitializeIfHaveNot();
SaveLastScene();
SaveLastHierarchyState();
AddToManagerIfNotAddedTo();
}
void OnEnable() => AddToManagerIfNotAddedTo();
void OnDisable() => RemoveFromManagerIfAddedTo();
void OnDestroy() => RemoveFromManagerIfAddedTo();
void LateUpdate() {
// TODO: come up with a better way of handling scene-change
ReportSceneChangeOrRemoveFromManagerIfPossible();
ReportTransformHierarchyChangeIfPossible();
}
/// <summary>
/// Binds a dependency to this context. If one with the same type already exists, the new one will override
/// the old one.
/// </summary>
public void Bind<T>(T dependency) {
if (_dependencyTypes.Add( typeof(T) )) {
// new type
if (typeof(T).IsValueType) {
_structDependencies.Add( new RealValueHolder<T>( dependency ) );
#if UNITY_EDITOR
if (IsEditorInspecting_EditorOnly)
StructDependencies_Serialized.Add( new BoxedValueHolder( dependency ) );
#endif
}
else if (IsUnityObjectType( dependency.GetType() ))
UnityObjectDependencies.Add( dependency as UnityEngine.Object );
else
ClassDependencies.Add( dependency );
} else {
// override previous of same type
if (typeof(T).IsValueType) {
for (int i = 0; i < _structDependencies.Count; i++) {
if (_structDependencies[i] is RealValueHolder<T> sd) {
sd.Value = dependency;
#if UNITY_EDITOR
if (IsEditorInspecting_EditorOnly)
StructDependencies_Serialized[i].BoxAndSetValue( dependency );
#endif
break;
}
if (_structDependencies[i].GetValueType() == typeof(T)) {
_structDependencies[i].BoxAndSetValue( dependency );
#if UNITY_EDITOR
if (IsEditorInspecting_EditorOnly)
StructDependencies_Serialized[i].BoxAndSetValue( dependency );
#endif
break;
}
}
}
else if (IsUnityObjectType( dependency.GetType() )) {
for (int i = 0; i < UnityObjectDependencies.Count; i++) {
if (UnityObjectDependencies[i].GetType() == dependency.GetType()) {
UnityObjectDependencies[i] = dependency as UnityEngine.Object;
break;
}
}
} else {
for (int i = 0; i < ClassDependencies.Count; i++) {
if (ClassDependencies[i].GetType() == dependency.GetType()) {
ClassDependencies[i] = dependency;
break;
}
}
}
}
}
/// <summary>
/// Unbinds a dependency from this context.
/// </summary>
public void Unbind<T>() {
if (_dependencyTypes.Remove( typeof(T) )) {
if (typeof(T).IsValueType) {
for (int i = 0; i < _structDependencies.Count; i++) {
if (_structDependencies[i].GetValueType() == typeof(T)) {
_structDependencies.RemoveAt( i );
#if UNITY_EDITOR
if (IsEditorInspecting_EditorOnly)
StructDependencies_Serialized.RemoveAt( i );
#endif
return;
}
}
}
if (IsUnityObjectType( typeof(T) )) {
for (int i = 0; i < UnityObjectDependencies.Count; i++) {
if (UnityObjectDependencies[i].GetType() == typeof(T)) {
UnityObjectDependencies.RemoveAt( i );
return;
}
}
} else {
for (int i = 0; i < ClassDependencies.Count; i++) {
if (ClassDependencies[i].GetType() == typeof(T)) {
ClassDependencies.RemoveAt( i );
return;
}
}
}
}
}
/// <summary>
/// Checks if this context has a dependency of type <see cref="T"/>
/// </summary>
public bool HasDependency<T>() => _dependencyTypes.Contains( typeof(T) );
/// <summary>
/// Returns the dependency of type <see cref="T"/> if it exists, otherwise returns <c>default</c>.
/// </summary>
public T GetDependency<T>() {
if (HasDependency<T>())
if (TryFindDependency( out T result ))
return result;
Debug.LogWarning( $"No dependency of type {typeof(T).FullName} found. returning default/null." );
return default;
}
/// <summary>
/// Without checking if it exists, returns the dependency of type <see cref="T"/>. If not found, returns default.
/// Slightly faster than <see cref="GetDependency{T}"/> if you already know that the dependency exists, but
/// using <see cref="HasDependency{T}"/> and this method together is slightly slower than a single
/// <see cref="GetDependency{T}"/> call.
/// </summary>
public T GetDependencyNoCheck<T>() {
if (TryFindDependency<T>( out var result ))
return result;
Debug.LogWarning( $"No dependency of type {typeof(T).FullName} found. returning default/null." );
return default;
}
internal void PopulateSerializedStructs() {
StructDependencies_Serialized.Clear();
for (int i = 0; i < _structDependencies.Count; i++)
StructDependencies_Serialized.Add( new BoxedValueHolder( _structDependencies[i].BoxAndGetValue() ) );
}
/// <summary>
/// updates manager to adapt for the new transform hierarchy change
/// </summary>
void ReportTransformHierarchyChangeIfPossible() {
if (transform.GetSiblingIndex() != _lastSiblingIndex || !ReferenceEquals( _lastParent, transform.parent )) {
BinjectManager.UpdateAllRootContextsAndTopmostScene();
SaveLastHierarchyState();
}
}
void SaveLastHierarchyState() {
_lastParent = transform.parent;
_lastSiblingIndex = transform.GetSiblingIndex();
}
/// <summary>
/// Reports scene change to <see cref="BinjectManager"/> if it happened, or removes this from it if it has
/// moved to an invalid scene.
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void ReportSceneChangeOrRemoveFromManagerIfPossible() {
var sceneHandle = new SceneHandle( gameObject.scene );
if (_lastSceneHandle.Value != sceneHandle.Value) { // scene changed
if (sceneHandle.Value == 0 || !gameObject.scene.isLoaded) { // invalid scene
BinjectManager.RemoveContext( this, sceneHandle );
_addedToManager = false;
} else {
BinjectManager.UpdateContextScene( this, _lastSceneHandle );
}
SaveLastScene();
SaveLastHierarchyState();
}
}
/// <summary>
/// Adds this to <see cref="BinjectManager"/> if it wasn't added to it already and if it has a valid scene.
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void AddToManagerIfNotAddedTo() {
if (_lastSceneHandle.Value != 0 && gameObject.scene.isLoaded && !_addedToManager) {
BinjectManager.AddContext( this, _lastSceneHandle );
_addedToManager = true;
}
}
/// <summary>
/// Removes this from <see cref="BinjectManager"/> if it was added to it.
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void RemoveFromManagerIfAddedTo() {
if (_addedToManager) {
BinjectManager.RemoveContext( this, _lastSceneHandle );
_addedToManager = false;
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void InitializeIfHaveNot() {
if (!_inited) {
SyncAllDependencyTypes( true );
SaveLastHierarchyState();
SaveLastScene();
_inited = true;
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void SaveLastScene() => _lastSceneHandle = new( gameObject.scene );
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void ApplyAllSerializedStructs() {
for (int i = 0; i < StructDependencies_Serialized.Count; i++)
_structDependencies.Add( StructDependencies_Serialized[i] );
}
/// <summary>
/// Stores types of all dependencies to <see cref="_dependencyTypes"/>.
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void SyncAllDependencyTypes(bool clear) {
if (clear) _dependencyTypes.Clear();
for (int i = 0; i < ClassDependencies.Count; i++)
_dependencyTypes.Add( ClassDependencies[i].GetType() );
for (int i = 0; i < UnityObjectDependencies.Count; i++)
_dependencyTypes.Add( UnityObjectDependencies[i].GetType() );
for (int i = 0; i < _structDependencies.Count; i++)
_dependencyTypes.Add( _structDependencies[i].GetValueType() );
}
/// <summary>
/// Tries to find the dependency from the given type, from fields <see cref="_structDependencies"/>,
/// <see cref="UnityObjectDependencies"/> and <see cref="ClassDependencies"/> respectively. <para/>
/// (It won't allocate garbage if <see cref="T"/> is a value type.)
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
bool TryFindDependency<T>(out T result) {
if (typeof(T).IsValueType) {
for (int i = 0; i < _structDependencies.Count; i++)
if (_structDependencies[i] is RealValueHolder<T> sd) {
result = sd.Value;
return true;
} else if (_structDependencies[i].GetValueType() == typeof(T)) {
result = (T)_structDependencies[i].BoxAndGetValue();
return true;
}
}
if (IsUnityObjectType( typeof(T) )) {
for (int i = 0; i < UnityObjectDependencies.Count; i++)
if (UnityObjectDependencies[i] is T obj) {
result = obj;
return true;
}
} else {
for (int i = 0; i < ClassDependencies.Count; i++)
if (ClassDependencies[i] is T dat) {
result = dat;
return true;
}
}
result = default;
return false;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
static bool IsUnityObjectType(Type type) => type.IsSubclassOf( typeof(UnityEngine.Object) );
}
class TypeComparer : IEqualityComparer<Type> {
public bool Equals(Type x, Type y) => ReferenceEquals( x, y );
public int GetHashCode(Type obj) => obj.GetHashCode();
}
}