Client LuaCsForBarotrauma
GenericPrefabFile.cs
1 using System.Linq;
2 using System.Xml.Linq;
3 
4 namespace Barotrauma
5 {
6  abstract class GenericPrefabFile<T> : ContentFile where T : Prefab
7  {
8  protected GenericPrefabFile(ContentPackage contentPackage, ContentPath path) : base(contentPackage, path) { }
9 
10  protected abstract bool MatchesSingular(Identifier identifier);
11  protected abstract bool MatchesPlural(Identifier identifier);
12  protected abstract PrefabCollection<T> Prefabs { get; }
13  protected abstract T CreatePrefab(ContentXElement element);
14 
15  private void LoadFromXElement(ContentXElement parentElement, bool overriding)
16  {
17  Identifier elemName = parentElement.NameAsIdentifier();
18  var childElements = parentElement.Elements()
19 #if DEBUG
20  .OrderBy(e => Rand.Int(int.MaxValue, Rand.RandSync.Unsynced)).ToArray()
21 #endif
22  ;
23  if (parentElement.IsOverride())
24  {
25  foreach (var element in childElements)
26  {
27  LoadFromXElement(element, true);
28  }
29  }
30  else if (elemName == "clear")
31  {
32  Prefabs.AddOverrideFile(this);
33  }
34  else if (MatchesSingular(elemName))
35  {
36  T prefab = CreatePrefab(parentElement);
37  try
38  {
39  Prefabs.Add(prefab, overriding);
40  }
41  catch
42  {
43  //clean up before rethrowing, since some prefab types might lock resources
44  prefab.Dispose();
45  Prefabs.Remove(prefab);
46  throw;
47  }
48  }
49  else if (MatchesPlural(elemName))
50  {
51  foreach (var element in childElements)
52  {
53  LoadFromXElement(element, overriding);
54  }
55  }
56  else
57  {
58  DebugConsole.ThrowError($"GenericPrefabFile: Invalid {GetType().Name} element: {parentElement.Name} in {Path}", contentPackage: ContentPackage);
59  }
60  }
61 
62  public override sealed void LoadFile()
63  {
64  XDocument doc = XMLExtensions.TryLoadXml(Path);
65  if (doc == null) { return; }
66 
67  var rootElement = doc.Root.FromPackage(ContentPackage);
68  LoadFromXElement(rootElement, false);
69  }
70 
71  public override sealed void UnloadFile()
72  {
73  Prefabs.RemoveByFile(this);
74  }
75 
76  public sealed override void Sort()
77  {
78  Prefabs.SortAll();
79  }
80  }
81 }
Base class for content file types, which are loaded from filelist.xml via reflection....
Definition: ContentFile.cs:23
readonly ContentPackage ContentPackage
Definition: ContentFile.cs:136
Identifier NameAsIdentifier()
IEnumerable< ContentXElement > Elements()
sealed override void Sort()
override sealed void LoadFile()
override sealed void UnloadFile()
GenericPrefabFile(ContentPackage contentPackage, ContentPath path)
abstract bool MatchesSingular(Identifier identifier)
abstract bool MatchesPlural(Identifier identifier)
abstract PrefabCollection< T > Prefabs
abstract T CreatePrefab(ContentXElement element)