Repository navigation
Export native map patches and M2O resource manifests #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Segfaultd
wants to merge
9
commits into
main
Choose a base branch
from
feat/sds-patch-export
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f0896c2
feat: write .sds.patch files
Segfaultd 5293e03
feat: remove world objects and emit the patch that does it
Segfaultd 062791e
feat: export edits as a patch, leaving the game's archives alone
Segfaultd 49fae5d
feat: export a patch for both season variants
Segfaultd 415abb4
fix: stop guessing which collision belongs to a removed frame
Segfaultd f2112fd
fix: export no longer saves the working copy behind the user's back
Segfaultd 5c527a6
Editor: Export M2O maps with packaged resource manifests
Segfaultd 3637914
Editor: Handle unchanged exports and reject output collisions
Segfaultd 3ca5c78
Patches: Validate input lengths and protect source archives
Segfaultd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| using System.Text.Json; | ||
|
|
||
| namespace Illusion.Assets.Sds; | ||
|
|
||
| /// <summary>Publishes native patches and their manifest together in a new M2O map folder.</summary> | ||
| public static class M2oMapExporter | ||
| { | ||
| /// <summary>The native target path relative to the game's pc directory.</summary> | ||
| public static string TargetOf(FileInfo archive) | ||
| { | ||
| string relative = Path.GetRelativePath(MafiaEnvironment.PcFolder, archive.FullName).Replace('\\', '/'); | ||
| if (!relative.StartsWith("sds/", StringComparison.OrdinalIgnoreCase) || relative.Split('/').Any(part => part is ".." or ".") || !relative.EndsWith(".sds", StringComparison.OrdinalIgnoreCase)) | ||
| throw new InvalidOperationException($"{archive.Name} is not an SDS archive inside the selected game's pc/sds folder."); | ||
| return "/" + relative.ToLowerInvariant(); | ||
| } | ||
|
|
||
| /// <summary>Exports only the supplied edited archives; season variants must be edited separately.</summary> | ||
| public static IReadOnlyList<PatchExportResult> Export(IReadOnlyList<FileInfo> archives, string destination, IProgress<string>? progress = null) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(archives); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(destination); | ||
| if (archives.Count == 0) throw new InvalidOperationException("No edited archives to export."); | ||
| string fullDestination = Path.GetFullPath(destination); | ||
| if (Directory.Exists(fullDestination) || File.Exists(fullDestination)) throw new IOException("That export folder already exists. Choose a new name to keep the previous export intact."); | ||
| string[] targets = archives.Select(TargetOf).ToArray(); | ||
| if (targets.Distinct(StringComparer.OrdinalIgnoreCase).Count() != targets.Length) throw new InvalidOperationException("The export contains duplicate SDS targets."); | ||
| string stage = fullDestination + ".tmp-" + Guid.NewGuid().ToString("N"); | ||
| Directory.CreateDirectory(stage); | ||
| try | ||
| { | ||
| var results = new List<PatchExportResult>(); | ||
| var entries = new List<object>(); | ||
| for (int i = 0; i < archives.Count; i++) | ||
| { | ||
| progress?.Report($"Exporting {i + 1} of {archives.Count}: {archives[i].Name}"); | ||
| string patch = targets[i].TrimStart('/') + ".patch"; | ||
| PatchExportResult? exported; | ||
| try { exported = PatchExporter.TryExport(archives[i], Path.Combine(stage, patch)); } | ||
| catch (Exception ex) { throw new InvalidOperationException($"Could not export {archives[i].Name}: {ex.Message}", ex); } | ||
| if (exported is not { } result) continue; | ||
| results.Add(result with { PatchPath = Path.Combine(fullDestination, patch) }); | ||
| entries.Add(new { sds = targets[i], patch }); | ||
| } | ||
| if (results.Count == 0) return results; | ||
| File.WriteAllText(Path.Combine(stage, "map_patches.json"), JsonSerializer.Serialize(new { patches = entries }, new JsonSerializerOptions { WriteIndented = true })); | ||
| Directory.Move(stage, fullDestination); | ||
| return results; | ||
| } | ||
| finally | ||
| { | ||
| if (Directory.Exists(stage)) Directory.Delete(stage, true); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| using Illusion.Formats; | ||
| using Illusion.Formats.Archive; | ||
|
|
||
| namespace Illusion.Assets.Sds; | ||
|
|
||
| /// <summary>One archive's export: where the patch went, and what it carries.</summary> | ||
| /// <param name="Archive">The game archive the patch applies to.</param> | ||
| /// <param name="PatchPath">The file written.</param> | ||
| /// <param name="Result">What the diff found.</param> | ||
| public readonly record struct PatchExportResult(string Archive, string PatchPath, PatchDiffResult Result); | ||
|
|
||
| /// <summary>Diffs saved working copies against read-only game archives and exports native patches.</summary> | ||
| public static class PatchExporter | ||
| { | ||
| /// <summary>The extension every exported patch carries, matching the game's own convention.</summary> | ||
| public const string PatchExtension = ".sds.patch"; | ||
|
|
||
| /// <summary> | ||
| /// The other season's copy of a district, or null when there is none. | ||
| /// </summary> | ||
| public static FileInfo? SeasonVariantOf(FileInfo sds) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
|
|
||
| string stem = Path.GetFileNameWithoutExtension(sds.Name); | ||
| string twin = stem.EndsWith("_z", StringComparison.OrdinalIgnoreCase) | ||
| ? stem[..^2] | ||
| : stem + "_z"; | ||
|
|
||
| var candidate = new FileInfo(Path.Combine(sds.DirectoryName ?? string.Empty, twin + ".sds")); | ||
| return candidate.Exists ? candidate : null; | ||
| } | ||
|
|
||
| /// <summary>The name a patch for <paramref name="sds"/> should be given.</summary> | ||
| public static string SuggestFileName(FileInfo sds) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
| return Path.GetFileNameWithoutExtension(sds.Name) + PatchExtension; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes a patch for <paramref name="sds"/> to <paramref name="outputPath"/>, expressing every | ||
| /// edit made to it this session. | ||
| /// </summary> | ||
| /// <exception cref="FileNotFoundException">The archive was never extracted, so there is nothing to diff.</exception> | ||
| /// <exception cref="InvalidOperationException">Nothing changed, so there is no patch to write.</exception> | ||
| public static PatchExportResult Export(FileInfo sds, string outputPath) | ||
| => TryExport(sds, outputPath) ?? throw new InvalidOperationException($"{sds.Name} is unchanged; no patch is needed."); | ||
|
|
||
| /// <summary>Exports a changed archive, or returns null without writing a file when unchanged.</summary> | ||
| public static PatchExportResult? TryExport(FileInfo sds, string outputPath) | ||
| => TryExport(sds, outputPath, out _, out _); | ||
|
|
||
| private static PatchExportResult? TryExport(FileInfo sds, string outputPath, out SdsArchive original, out SdsArchive edited) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); | ||
|
|
||
| if (string.Equals(sds.FullName, Path.GetFullPath(outputPath), StringComparison.OrdinalIgnoreCase)) | ||
| throw new InvalidOperationException("The output patch cannot overwrite its base archive."); | ||
| string extracted = MafiaEnvironment.ExtractedDir(sds); | ||
| if (!File.Exists(Path.Combine(extracted, "SDSContent.xml"))) | ||
| { | ||
| throw new FileNotFoundException( | ||
| $"Extracted content not found for {sds.Name} — nothing to diff.", | ||
| Path.Combine(extracted, "SDSContent.xml")); | ||
| } | ||
|
|
||
| edited = SdsArchive.Pack(extracted, GameProfile.MafiaII); | ||
| original = SdsArchive.Open(sds.FullName); | ||
|
|
||
| if (SdsPatchDiff.TryBetween(original, edited) is not { } diff) return null; | ||
| (SdsPatchFile patch, PatchDiffResult result) = diff; | ||
|
|
||
| string? directory = Path.GetDirectoryName(outputPath); | ||
| if (!string.IsNullOrEmpty(directory)) | ||
| { | ||
| Directory.CreateDirectory(directory); | ||
| } | ||
|
|
||
| using (FileStream output = File.Create(outputPath)) | ||
| { | ||
| patch.Save(output); | ||
| } | ||
|
|
||
| return new PatchExportResult(sds.FullName, outputPath, result); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Exports the patch for <paramref name="sds"/> and, when the district ships a season twin, a | ||
| /// second patch that applies the same removals to it. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Only matching frame removals carry across; resource ordinals and other edits are season-specific. | ||
| /// </remarks> | ||
| public static IReadOnlyList<PatchExportResult> ExportWithSeasonVariant(FileInfo sds, string outputPath) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); | ||
|
|
||
| FileInfo? twin = SeasonVariantOf(sds); | ||
| string? twinPath = twin is null ? null : Path.Combine(Path.GetDirectoryName(outputPath) ?? string.Empty, SuggestFileName(twin)); | ||
| if (twinPath is not null && string.Equals(Path.GetFullPath(outputPath), Path.GetFullPath(twinPath), StringComparison.OrdinalIgnoreCase)) | ||
| throw new IOException("The chosen filename conflicts with the seasonal patch filename."); | ||
| PatchExportResult result = TryExport(sds, outputPath, out SdsArchive original, out SdsArchive edited) | ||
| ?? throw new InvalidOperationException($"{sds.Name} is unchanged; no patch is needed."); | ||
| var exported = new List<PatchExportResult> { result }; | ||
| if (twin is null) | ||
| { | ||
| return exported; | ||
| } | ||
|
|
||
| var removedNames = ScenePatchAuthor | ||
| .FrameNamesOf(FrameResourceOf(original)) | ||
| .Except(ScenePatchAuthor.FrameNamesOf(FrameResourceOf(edited)), StringComparer.Ordinal) | ||
| .ToList(); | ||
|
|
||
| if (removedNames.Count == 0) | ||
| { | ||
| return exported; | ||
| } | ||
|
|
||
| var author = new ScenePatchAuthor(SdsArchive.Open(twin.FullName)); | ||
| RemovalResult removal = author.RemoveFrames(removedNames); | ||
| if (removal.DeletedFrames == 0 && removal.DeletedCollisionInstances == 0) return exported; | ||
|
|
||
| SdsPatchFile twinPatch = author.Build(); | ||
| using (FileStream output = File.Create(twinPath!)) | ||
| { | ||
| twinPatch.Save(output); | ||
| } | ||
|
|
||
| exported.Add(new PatchExportResult( | ||
| twin.FullName, | ||
| twinPath!, | ||
| new PatchDiffResult(Changed: twinPatch.Entries.Count, Removed: 0, Added: 0))); | ||
|
|
||
| return exported; | ||
| } | ||
|
|
||
| private static byte[]? FrameResourceOf(SdsArchive archive) | ||
| { | ||
| for (int i = 0; i < archive.Entries.Count; i++) | ||
| { | ||
| int typeId = archive.Entries[i].TypeId; | ||
| if (typeId >= 0 && typeId < archive.ResourceTypes.Count && | ||
| string.Equals(archive.ResourceTypes[typeId].Name, "FrameResource", StringComparison.Ordinal)) | ||
| { | ||
| return archive.Entries[i].Data; | ||
| } | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Exports one patch per archive into <paramref name="targetFolder"/>, naming each after its | ||
| /// archive. Archives that turn out to be unchanged are skipped rather than failing the export. | ||
| /// </summary> | ||
| public static IReadOnlyList<PatchExportResult> ExportAll(IEnumerable<FileInfo> archives, string targetFolder) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(archives); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(targetFolder); | ||
|
|
||
| FileInfo[] sources = archives.ToArray(); | ||
| if (sources.Select(SuggestFileName).Distinct(StringComparer.OrdinalIgnoreCase).Count() != sources.Length) | ||
| throw new IOException("Several archives would export to the same filename. Export them separately."); | ||
| var exported = new List<PatchExportResult>(); | ||
| foreach (FileInfo sds in sources) | ||
| { | ||
| if (TryExport(sds, Path.Combine(targetFolder, SuggestFileName(sds))) is { } result) | ||
| { | ||
| exported.Add(result); | ||
| } | ||
| } | ||
|
|
||
| return exported; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Reject existing generated patch paths before writing.
The dialog confirms only its selected path. A seasonal export can silently replace an existing automatically named twin patch. A batch export can silently replace any generated patch after the first archive. Check all generated paths before writing the primary patch so a failure cannot leave a partial export.
src/Illusion.Assets/Sds/PatchExporter.cs#L128-L128: reject an existingtwinPathbeforeTryExportwrites the primary patch.src/Illusion.Assets/Sds/PatchExporter.cs#L171-L171: precompute all batch output paths and reject existing paths before the loop.Proposed fix
if (twinPath is not null && string.Equals(Path.GetFullPath(outputPath), Path.GetFullPath(twinPath), StringComparison.OrdinalIgnoreCase)) throw new IOException("The chosen filename conflicts with the seasonal patch filename."); + if (twinPath is not null && File.Exists(twinPath)) + throw new IOException("The seasonal patch already exists. Choose a different output name."); PatchExportResult result = TryExport(sds, outputPath, out SdsArchive original, out SdsArchive edited) ?? throw new InvalidOperationException($"{sds.Name} is unchanged; no patch is needed.");FileInfo[] sources = archives.ToArray(); if (sources.Select(SuggestFileName).Distinct(StringComparer.OrdinalIgnoreCase).Count() != sources.Length) throw new IOException("Several archives would export to the same filename. Export them separately."); + string[] outputPaths = sources.Select(sds => Path.Combine(targetFolder, SuggestFileName(sds))).ToArray(); + if (outputPaths.Any(File.Exists)) + throw new IOException("An output patch already exists. Choose a different folder."); var exported = new List<PatchExportResult>(); - foreach (FileInfo sds in sources) + for (int i = 0; i < sources.Length; i++) { - if (TryExport(sds, Path.Combine(targetFolder, SuggestFileName(sds))) is { } result) + if (TryExport(sources[i], outputPaths[i]) is { } result) { exported.Add(result); } }📝 Committable suggestion
📍 Affects 1 file
src/Illusion.Assets/Sds/PatchExporter.cs#L128-L128(this comment)src/Illusion.Assets/Sds/PatchExporter.cs#L171-L171🤖 Prompt for AI Agents