-
Notifications
You must be signed in to change notification settings - Fork 45
/
ContentManager.cs
251 lines (202 loc) · 8.81 KB
/
ContentManager.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml.Linq;
using Nito.AsyncEx;
using Windows.Storage;
namespace DirectX12GameEngine.Core.Assets
{
public partial class ContentManager : IContentManager
{
private readonly AsyncLock asyncLock = new AsyncLock();
private readonly Dictionary<string, Reference> loadedAssetPaths = new Dictionary<string, Reference>();
private readonly Dictionary<object, Reference> loadedAssetReferences = new Dictionary<object, Reference>();
static ContentManager()
{
AddTypeConverters(typeof(Vector3Converter), typeof(Vector4Converter), typeof(QuaternionConverter), typeof(Matrix4x4Converter));
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
AddAssembly(assembly);
}
AppDomain.CurrentDomain.AssemblyLoad += (s, e) => AddAssembly(e.LoadedAssembly);
}
private static void AddAssembly(Assembly assembly)
{
foreach (ContractNamespaceAttribute attribute in assembly.GetCustomAttributes<ContractNamespaceAttribute>())
{
if (!XmlnsDefinitions.TryGetValue(attribute.ContractNamespace, out var namespaces))
{
namespaces = new List<(string, Assembly)>();
XmlnsDefinitions.Add(attribute.ContractNamespace, namespaces);
}
namespaces.Add((attribute.ClrNamespace, assembly));
}
}
public ContentManager(IServiceProvider services)
{
Services = services;
}
public ContentManager(IServiceProvider services, IStorageFolder rootFolder)
{
Services = services;
RootFolder = rootFolder;
}
public static Dictionary<string, List<(string ClrNamespace, Assembly Assembly)>> XmlnsDefinitions { get; } = new Dictionary<string, List<(string, Assembly)>>();
public IServiceProvider Services { get; }
public string FileExtension { get; set; } = ".xaml";
public IStorageFolder? RootFolder { get; set; }
public string? RootPath => RootFolder?.Path;
public async Task<bool> ExistsAsync(string path)
{
if (RootFolder is null || !(RootFolder is IStorageFolder2 folder)) throw new InvalidOperationException("The root folder cannot be null.");
return await folder.TryGetItemAsync(path + FileExtension) != null;
}
public T Get<T>(string path) where T : class?
{
object? asset = Get(typeof(T), path);
if (asset != null)
{
return (T)asset;
}
return null!;
}
public object? Get(Type type, string path)
{
return FindDeserializedObject(path, type)?.Object;
}
public async Task<T> LoadAsync<T>(string path) where T : class
{
return (T)await LoadAsync(typeof(T), path);
}
public async Task<object> LoadAsync(Type type, string path)
{
using (await asyncLock.LockAsync())
{
return await DeserializeAsync(path, type, null, null);
}
}
public async Task<bool> ReloadAsync(object asset, string? newPath = null)
{
using (await asyncLock.LockAsync())
{
if (!loadedAssetReferences.TryGetValue(asset, out Reference reference))
{
return false;
}
string path = newPath ?? reference.Path;
await DeserializeExistingObjectAsync(reference.Path, path, asset);
if (path != reference.Path)
{
loadedAssetPaths.Remove(reference.Path);
}
return true;
}
}
public async Task SaveAsync(string path, object asset, Type? storageType = null)
{
using (await asyncLock.LockAsync())
{
await SerializeAsync(path, asset, storageType);
}
}
public void Unload(object asset)
{
using (asyncLock.Lock())
{
if (!loadedAssetReferences.TryGetValue(asset, out Reference reference))
{
throw new InvalidOperationException("Content is not loaded.");
}
DecrementReference(reference, true);
}
}
public void Unload(string path)
{
using (asyncLock.Lock())
{
if (!loadedAssetPaths.TryGetValue(path, out Reference reference))
{
throw new InvalidOperationException("Content is not loaded.");
}
DecrementReference(reference, true);
}
}
public static void AddTypeConverters(params Type[] typeConverters)
{
foreach (Type typeConverter in typeConverters)
{
GlobalTypeConverterAttribute converterAttribute = typeConverter.GetCustomAttribute<GlobalTypeConverterAttribute>();
TypeDescriptor.AddAttributes(converterAttribute.Type, new TypeConverterAttribute(typeConverter));
}
}
public static IEnumerable<PropertyInfo> GetDataContractProperties(Type type, object obj)
{
bool isDataContractPresent = type.IsDefined(typeof(DataContractAttribute));
var properties = !isDataContractPresent
? type.GetProperties(BindingFlags.Public | BindingFlags.Instance).AsEnumerable()
: type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.IsDefined(typeof(DataMemberAttribute))).OrderBy(p => p.GetCustomAttribute<DataMemberAttribute>().Order);
properties = properties.Where(p => !p.IsDefined(typeof(IgnoreDataMemberAttribute)) && !p.IsSpecialName && !(p.GetIndexParameters().Length > 0));
return properties.Where(p => p.CanRead).Where(p => p.CanWrite || p.GetValue(obj) is IList);
}
public static void GetNamespaceAndTypeName(string xmlName, XElement element, out string namespaceName, out string typeName)
{
string[] namespaceAndType = xmlName.Split(new[] { ':' }, 2);
if (namespaceAndType.Length == 2)
{
string namespacePrefix = namespaceAndType[0];
namespaceName = element.GetNamespaceOfPrefix(namespacePrefix).NamespaceName;
typeName = namespaceAndType[1];
}
else
{
namespaceName = element.GetDefaultNamespace().NamespaceName;
typeName = xmlName;
}
}
public static Type GetTypeFromXmlName(string xmlNamespace, string typeName)
{
const string clrNamespaceString = "clr-namespace:";
const string assemblyString = "assembly=";
const string extensionString = "Extension";
int indexOfSemicolon = xmlNamespace.IndexOf(';');
if (xmlNamespace.StartsWith(clrNamespaceString))
{
string namespaceName = indexOfSemicolon >= 0
? xmlNamespace.Substring(clrNamespaceString.Length, indexOfSemicolon - clrNamespaceString.Length)
: xmlNamespace.Substring(clrNamespaceString.Length);
Assembly assembly;
if (indexOfSemicolon >= 0)
{
string assemblyName = xmlNamespace.Substring(indexOfSemicolon + assemblyString.Length + 1);
assembly = Assembly.Load(assemblyName);
}
else
{
assembly = Assembly.GetExecutingAssembly();
}
Type? type = assembly.GetType(namespaceName + Type.Delimiter + typeName, false);
return type ?? assembly.GetType(namespaceName + Type.Delimiter + typeName + extensionString, true);
}
else
{
var namespaces = XmlnsDefinitions[xmlNamespace];
foreach ((string clrNamespace, Assembly assembly) in namespaces)
{
Type? type = assembly.GetType(clrNamespace + Type.Delimiter + typeName, false);
type ??= assembly.GetType(clrNamespace + Type.Delimiter + typeName + extensionString, false);
if (type != null)
{
return type;
}
}
throw new InvalidOperationException();
}
}
}
}