Skip to content

Commit e68d10c

Browse files
committed
Loading patches from addressables
1 parent 3990848 commit e68d10c

File tree

5 files changed

+100
-28
lines changed

5 files changed

+100
-28
lines changed

Editor/PatchImporter.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System.IO;
2+
using UnityEditor.AssetImporters;
3+
using UnityEngine;
4+
5+
namespace PatchManager.Editor
6+
{
7+
[ScriptedImporter(1, "patch")]
8+
public class PatchImporter: ScriptedImporter
9+
{
10+
public override void OnImportAsset(AssetImportContext ctx)
11+
{
12+
var asset = new TextAsset(File.ReadAllText(ctx.assetPath));
13+
ctx.AddObjectToAsset(ctx.assetPath, asset);
14+
ctx.SetMainObject(asset);
15+
}
16+
}
17+
}

Editor/PatchImporter.cs.meta

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Runtime/Core/Assets/PatchingManager.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ internal static class PatchingManager
3131

3232
internal static int TotalPatchCount;
3333
internal static int TotalErrorCount;
34-
34+
3535
public static void GenerateUniverse(HashSet<string> singleFileModIds)
3636
{
3737
var loadedPlugins = PluginList.AllEnabledAndActivePlugins.Select(x => x.Guid).ToList();
@@ -139,6 +139,12 @@ public static void ImportSinglePatch(FileInfo fileInfo)
139139
CurrentPatchHashes.Patches.Add(fileInfo.FullName, Hash.FromFile(fileInfo.FullName));
140140
}
141141

142+
public static void ImportAssetPatch(TextAsset asset, string modId)
143+
{
144+
Universe.LoadPatchAsset(asset, modId);
145+
CurrentPatchHashes.Patches.Add(asset.name, Hash.FromString(asset.text));
146+
}
147+
142148
public static void RegisterPatches()
143149
{
144150
Logging.LogInfo($"Registering all patches!");
@@ -299,7 +305,7 @@ public static void CreateNewAssets(Action resolve, Action<string> reject)
299305
}
300306

301307
internal static bool InjectPatchManagerTips = false;
302-
308+
303309
public static void RebuildAllCache(Action resolve, Action<string> reject)
304310
{
305311
var distinctKeys = Universe.LoadedLabels.Concat(_createdAssets.Keys).Distinct().ToList();

Runtime/Core/CoreModule.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections.Generic;
33
using System.IO;
44
using JetBrains.Annotations;
5+
using KSP.Game;
56
using Newtonsoft.Json;
67
using PatchManager.Core.Assets;
78
using PatchManager.Core.Cache;
@@ -12,6 +13,7 @@
1213
using SpaceWarp.API.Mods.JSON;
1314
using UniLinq;
1415
using Unity.VisualScripting;
16+
using UnityEngine;
1517
using UnityEngine.AddressableAssets;
1618
using UnityEngine.UIElements;
1719
using FlowAction = PatchManager.Core.Flow.FlowAction;
@@ -24,6 +26,9 @@ namespace PatchManager.Core
2426
[UsedImplicitly]
2527
public class CoreModule : BaseModule
2628
{
29+
private const string PATCH_LABEL = "redux_patches";
30+
private const string REDUX_MOD_ID = "Redux";
31+
2732
private ConfigValue<bool> _shouldAlwaysInvalidate;
2833

2934
private bool _wasCacheInvalidated;
@@ -88,11 +93,10 @@ public override void Init()
8893
/// <inheritdoc />
8994
public override void PreLoad()
9095
{
91-
9296
// Go here instead so that the static constructor recognizes everything
9397
var disabledPlugins = File.ReadAllText(SpaceWarp.API.CommonPaths.DisabledPlugins)
9498
.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
95-
99+
96100
var modFolders = Directory.GetDirectories(SpaceWarp.API.CommonPaths.ModsFolder, "*", SearchOption.AllDirectories)
97101
.Where(dir => ShouldLoad(disabledPlugins, Path.Combine(dir, "swinfo.json")))
98102
.Select(x => (
@@ -112,13 +116,23 @@ public override void PreLoad()
112116
.Select(x => new FileInfo(x))
113117
.ToList();
114118

115-
119+
116120
PatchingManager.GenerateUniverse(standalonePatches.Select(x =>
117121
x.Directory!.FullName
118122
.MakeRelativePathTo(gameRoot.FullName)
119123
.Replace("\\", "-")
120124
).ToHashSet());
121125

126+
var handle = GameManager.Instance.Assets.LoadAssetsAsync<TextAsset>(PATCH_LABEL, asset =>
127+
{
128+
PatchingManager.ImportAssetPatch(asset, REDUX_MOD_ID);
129+
});
130+
handle.Completed += _ =>
131+
{
132+
Addressables.Release(handle);
133+
};
134+
handle.WaitForCompletion();
135+
122136
foreach (var modFolder in modFolders)
123137
{
124138
Logging.LogInfo($"Loading patchers from {modFolder.Folder}");

Runtime/SassyPatching/Execution/Universe.cs

Lines changed: 55 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using PatchManager.Shared;
1515
using UniLinq;
1616
using Unity.VisualScripting;
17+
using UnityEngine;
1718

1819
namespace PatchManager.SassyPatching.Execution
1920
{
@@ -34,10 +35,10 @@ public class Universe
3435

3536

3637
/// <summary>
37-
/// This contains all the constant text based libraries that have been registered
38+
/// This contains all the constant text based libraries that have been registered
3839
/// </summary>
3940
public static readonly Dictionary<string, string> AllRawLibraries = new();
40-
41+
4142
private static List<string> _preloadedLabels;
4243

4344
static Universe()
@@ -235,7 +236,7 @@ private void LoadAllRawPatches()
235236
}
236237
}
237238
}
238-
239+
239240
/// <summary>
240241
/// Loads all patches from a directory
241242
/// </summary>
@@ -247,12 +248,12 @@ public void LoadPatchesInDirectory(DirectoryInfo directory, string modId)
247248
var tokenTransformer = new Transformer(msg => throw new LoadException(msg));
248249
foreach (var library in directory.EnumerateFiles("_*.patch", SearchOption.AllDirectories))
249250
{
250-
LoadSingleLibrary(modId, library, tokenTransformer);
251+
LoadSingleLibrary(modId, library.Name, CharStreams.fromPath(library.FullName), tokenTransformer);
251252
}
252253

253254
foreach (var patch in directory.EnumerateFiles("*.patch", SearchOption.AllDirectories))
254255
{
255-
LoadSinglePatch(modId, patch, tokenTransformer);
256+
LoadSinglePatch(modId, patch.Name, CharStreams.fromPath(patch.FullName), tokenTransformer);
256257
}
257258
}
258259

@@ -262,40 +263,66 @@ public void LoadPatchesInDirectory(DirectoryInfo directory, string modId)
262263
/// <param name="patch">The file info of the patch file</param>
263264
/// <param name="cwd">The working directory to generate the patch mod id against</param>
264265
public void LoadSinglePatchFile(FileInfo patch, DirectoryInfo cwd)
265-
{
266+
{
266267
var tokenTransformer = new Transformer(msg => throw new LoadException(msg));
267268
var name = Path.GetFileNameWithoutExtension(patch.FullName);
268269
var id = patch.Directory!.FullName.MakeRelativePathTo(cwd.FullName).Replace("\\", "-");
269270
if (name.StartsWith("_"))
270271
{
271-
LoadSingleLibrary(id, patch, tokenTransformer);
272+
LoadSingleLibrary(id, name, CharStreams.fromPath(patch.FullName), tokenTransformer);
273+
}
274+
else
275+
{
276+
LoadSinglePatch(id, name, CharStreams.fromPath(patch.FullName), tokenTransformer);
277+
}
278+
}
279+
280+
/// <summary>
281+
/// Loads a single patch
282+
/// </summary>
283+
/// <param name="asset">The text asset to load</param>
284+
/// <param name="modId">Mod ID</param>
285+
public void LoadPatchAsset(TextAsset asset, string modId)
286+
{
287+
var tokenTransformer = new Transformer(msg => throw new LoadException(msg));
288+
if (asset.name.StartsWith("_"))
289+
{
290+
LoadSingleLibrary(modId, asset.name, CharStreams.fromString(asset.text), tokenTransformer);
272291
}
273292
else
274293
{
275-
LoadSinglePatch(id, patch, tokenTransformer);
294+
LoadSinglePatch(modId, asset.name, CharStreams.fromString(asset.text), tokenTransformer);
276295
}
277296
}
278297

279-
private void LoadSinglePatch(string modId, FileInfo patch, Transformer tokenTransformer)
298+
private void LoadSinglePatch(string modId, string name, ICharStream charStream, Transformer tokenTransformer)
280299
{
281-
if (patch.Name.StartsWith("_"))
300+
if (name.StartsWith("_"))
301+
{
282302
return;
303+
}
304+
283305
try
284306
{
285-
MessageLogger.Invoke($"Loading patch {modId}:{patch.Name}");
286-
var charStream = CharStreams.fromPath(patch.FullName);
307+
MessageLogger.Invoke($"Loading patch {modId}:{name}");
287308
var lexer = new sassy_lexer(charStream);
288-
var lexerErrorGenerator = new LexerListener($"{modId}:{patch.Name}", ErrorLogger);
309+
var lexerErrorGenerator = new LexerListener($"{modId}:{name}", ErrorLogger);
289310
lexer.AddErrorListener(lexerErrorGenerator);
290311
if (lexerErrorGenerator.Errored)
312+
{
291313
throw new LoadException("lexer errors detected");
314+
}
315+
292316
var tokenStream = new CommonTokenStream(lexer);
293317
var parser = new sassy_parser(tokenStream);
294-
var parserErrorGenerator = new ParserListener($"{modId}:{patch.Name}", ErrorLogger);
318+
var parserErrorGenerator = new ParserListener($"{modId}:{name}", ErrorLogger);
295319
parser.AddErrorListener(parserErrorGenerator);
296320
var patchContext = parser.patch();
297321
if (parserErrorGenerator.Errored)
322+
{
298323
throw new LoadException("parser errors detected");
324+
}
325+
299326
tokenTransformer.Errored = false;
300327
// var gEnv = new GlobalEnvironment(this, modId);
301328
// var env = new Environment(gEnv);
@@ -305,37 +332,42 @@ private void LoadSinglePatch(string modId, FileInfo patch, Transformer tokenTran
305332
}
306333
catch (Exception e)
307334
{
308-
ErrorLogger($"Could not run patch: {modId}:{patch.Name} due to: {e}");
335+
ErrorLogger($"Could not run patch: {modId}:{name} due to: {e}");
309336
}
310337
}
311338

312-
private void LoadSingleLibrary(string modId, FileInfo library, Transformer tokenTransformer)
339+
private void LoadSingleLibrary(string modId, string name, ICharStream charStream, Transformer tokenTransformer)
313340
{
314-
string name = modId + ":" + library.Name.Replace(".patch", "").TrimFirst();
341+
string libName = modId + ":" + name.Replace(".patch", "").TrimFirst();
315342
try
316343
{
317-
MessageLogger.Invoke($"Loading library {name}");
318-
var charStream = CharStreams.fromPath(library.FullName);
319-
var lexerErrorGenerator = new LexerListener(name, ErrorLogger);
344+
MessageLogger.Invoke($"Loading library {libName}");
345+
var lexerErrorGenerator = new LexerListener(libName, ErrorLogger);
320346
var lexer = new sassy_lexer(charStream);
321347
lexer.AddErrorListener(lexerErrorGenerator);
322348
if (lexerErrorGenerator.Errored)
349+
{
323350
throw new LoadException("lexer errors detected");
351+
}
352+
324353
var tokenStream = new CommonTokenStream(lexer);
325354
var parser = new sassy_parser(tokenStream);
326-
var parserErrorGenerator = new ParserListener(name, ErrorLogger);
355+
var parserErrorGenerator = new ParserListener(libName, ErrorLogger);
327356
parser.AddErrorListener(parserErrorGenerator);
328357
if (parserErrorGenerator.Errored)
358+
{
329359
throw new LoadException("parser errors detected");
360+
}
361+
330362
var patchContext = parser.patch();
331363
tokenTransformer.Errored = false;
332364
var patch = tokenTransformer.Visit(patchContext) as SassyPatch;
333365
var lib = new SassyPatchLibrary(patch);
334-
AllLibraries[name] = lib;
366+
AllLibraries[libName] = lib;
335367
}
336368
catch (Exception e)
337369
{
338-
ErrorLogger($"Could not load library: {name} due to: {e.Message}");
370+
ErrorLogger($"Could not load library: {libName} due to: {e.Message}");
339371
}
340372
}
341373

0 commit comments

Comments
 (0)