-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathModBase.cs
304 lines (248 loc) · 10.2 KB
/
ModBase.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
using Planetbase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Harmony;
using ICSharpCode.SharpZipLib.Zip;
using PlanetbaseFramework.Patches.Planetbase.GameStateCredits;
using PlanetbaseFramework.Patches.Planetbase.GameStateTitle;
using PlanetbaseFramework.Patches.Planetbase.Util;
using UnityEngine;
namespace PlanetbaseFramework
{
public abstract class ModBase
{
public List<Texture2D> ModTextures { get; protected set; }
public List<GameObject> ModObjects { get; protected set; }
public Assembly ModAssembly { get; protected set; } // This is set by the mod loader and should generally not be set elsewhere except possibly by second stage mod loaders
public virtual Version ModVersion => new Version(0, 0, 0, 0);
private HarmonyInstance Harmony { get; set; }
private static FastZip ZipInstance { get; } = new FastZip();
protected ModBase()
{
ExtractAssemblyResources();
LoadResourcesSafe();
UpdateCredits();
}
protected virtual void ExtractAssemblyResources()
{
//Extract embedded assets
ZipConstants.DefaultCodePage = 0; //This is a workaround to get files to extract properly
var manifestResources = ModAssembly.GetManifestResourceNames();
PreProcessEmbeddedResources(manifestResources);
foreach (var file in manifestResources)
{
if (!PreProcessEmbeddedResource(file))
continue;
Debug.Log($"Processing embedded file \"{file}\"");
using (var resourceStream = ModAssembly.GetManifestResourceStream(file))
{
switch (Path.GetExtension(file))
{
case ".zip":
Debug.Log("zip " + GetResourceRelativeFilePath(file));
ZipInstance.ExtractZip(
resourceStream,
ModPath,
FastZip.Overwrite.Always,
null,
null,
null,
false,
false
);
break;
default: //Copy the file to a directory matching the name under the mod's folder
var filePath = Path.Combine(ModPath, GetResourceRelativeFilePath(file));
Debug.Log($"Loading \"{file}\" to \"{filePath}\"");
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
using (var fileStream = File.Create(filePath))
{
resourceStream.CopyTo(fileStream);
}
break;
}
}
}
}
protected virtual void LoadResourcesSafe()
{
LoadStringsSafe();
LoadPngsSafe();
LoadObjsSafe();
}
protected virtual void LoadStringsSafe()
{
try
{
LoadAllStrings("strings");
}
catch (Exception e)
{
Debug.Log("Failed to load strings files due to exception:");
Utils.LogException(e);
}
}
protected virtual void LoadPngsSafe()
{
try
{
ModTextures = LoadAllPngs("png");
if (ModTextures.Count > 0)
{
Debug.Log($"Successfully loaded {ModTextures.Count} texture(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load PNG files due to exception:");
Utils.LogException(e);
}
}
protected virtual void LoadObjsSafe()
{
try
{
ModObjects = LoadAllObjs("obj");
if (ModObjects.Count > 0)
{
Debug.Log($"Successfully loaded {ModObjects.Count} object(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load OBJ files due to exception:");
Utils.LogException(e);
}
}
protected virtual void UpdateCredits()
{
var credits = GetCredits()?.Trim();
if (!string.IsNullOrEmpty(credits))
ConstructorPatch.Credits[this] = credits;
}
public abstract string ModName { get; }
public static string BasePath { get; } = Path.Combine(FilesFolderPatch.FilesFolderPath, "Mods");
public virtual string ModPath => Path.Combine(BasePath, ModName);
public virtual string AssetsPath => Path.Combine(ModPath, "assets");
public virtual void Init() //This is virtual instead of abstract so mods aren't required to implement it. Same with Update below
{
}
public virtual void Update()
{
}
public int LoadAllStrings(string subfolder = null)
{
var files = GetAssetsMatchingFileType("xml", subfolder);
Debug.Log($"Found {files.Length} strings files");
foreach (var file in files)
{
Utils.LoadStringsFromFile(file);
}
return files.Length;
}
public List<Texture2D> LoadAllPngs(string subfolder = null)
{
var files = GetAssetsMatchingFileType("png", subfolder);
Debug.Log($"Found {files.Length} PNG files");
var loadedFiles = new List<Texture2D>(files.Length);
foreach (var file in files)
{
loadedFiles.Add(Utils.LoadPngFromFile(file));
}
return loadedFiles;
}
public List<GameObject> LoadAllObjs(string subfolder = null)
{
var files = GetAssetsMatchingFileType("obj", subfolder);
Debug.Log($"Found {files.Length} OBJ files");
var loadedFiles = new List<GameObject>(files.Length);
foreach (var file in files)
{
var loadedObject = ObjLoader.LoadOBJFile(file, ModTextures);
loadedObject.setVisibleRecursive(false);
loadedObject.name = Path.GetFileName(file);
loadedObject.tag = "Untagged";
loadedFiles.Add(loadedObject);
}
return loadedFiles;
}
private string[] GetAssetsMatchingFileType(string fileType, string subfolder = null)
{
if (subfolder == null)
subfolder = string.Empty;
var searchPath = Path.Combine(AssetsPath, subfolder);
return Directory.Exists(searchPath) ? Directory.GetFiles(searchPath, "*." + fileType) : new string[0];
}
public HarmonyInstance GetHarmonyInstance() => Harmony ?? (Harmony = HarmonyInstance.Create(ModName));
public void InjectPatches()
{
GetHarmonyInstance().PatchAll(Assembly.GetCallingAssembly());
}
public void InjectPatches(Assembly containingPatches)
{
GetHarmonyInstance().PatchAll(containingPatches);
}
public void RegisterTitleButton(TitleButton button)
{
TitleButtonPatch.RegisteredTitleButtons.Add(button);
}
/// <summary>
/// Do any pre-load actions before embedded resources are loaded, such as removing existing folders/items.
/// Warning: this call will be made in the constructor before child initialization.
/// </summary>
/// <param name="resourceNames">The name of all the resources to be loaded</param>
protected virtual void PreProcessEmbeddedResources(string[] resourceNames)
{
}
/// <summary>
/// Do any pre-load actions before an embedded resource is loaded, such as removing existing folders/items.
/// Warning: this call will be made in the constructor before child initialization.
/// </summary>
/// <param name="resourceName">The name of the resources being loaded</param>
/// <returns>True if the resource should be loaded, false otherwise</returns>
protected virtual bool PreProcessEmbeddedResource(string resourceName)
{
return true;
}
// Resource names will be of the format:
// <ProjectName>.some.directory.path.fileName.extension
// For example:
// * PlanetbaseFramework.assets.png.error.png
// * PlanetbaseFramework.LICENSE.txt
// This code does not currently support files without an extension.
private static string GetResourceRelativeFilePath(string resourceName)
{
//Remove the project name from the path, including the preceding '.'
var convertedFilePath = resourceName.Substring(resourceName.IndexOf('.') + 1);
//Replace the '.' characters for directories with the path separation character
convertedFilePath = convertedFilePath.Substring(0, convertedFilePath.LastIndexOf('.'))
.Replace('.', Path.DirectorySeparatorChar) + Path.GetExtension(convertedFilePath);
return convertedFilePath;
}
/// <summary>
/// This function updates the "Credits" screen with the return value.
/// </summary>
public virtual string GetCredits()
{
var authors = GetContributors();
if (authors == null)
return null;
if (authors.Count == 0)
return null;
var headerString = $"(h){ModName}(/h)";
var authorsString = string.Join("\n", authors.ToArray());
return headerString + "\n" + authorsString;
}
/// <summary>
/// Called by the default implementation of GetCredits to add the returned
/// authors to the credit screen.
/// </summary>
public virtual ICollection<string> GetContributors()
{
return new string[] { };
}
}
}