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.
+2,208
−0
Open
Changes from 7 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
Some comments aren't visible on the classic Files Changed page.
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,52 @@ | ||
| 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 result; | ||
| try { result = PatchExporter.Export(archives[i], Path.Combine(stage, patch)); } | ||
| catch (Exception ex) { throw new InvalidOperationException($"Could not export {archives[i].Name}: {ex.Message}", ex); } | ||
| results.Add(result with { PatchPath = Path.Combine(fullDestination, patch) }); | ||
| entries.Add(new { sds = targets[i], patch }); | ||
| } | ||
| 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,189 @@ | ||
| 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> | ||
| /// Exports this session's edits as <c>.sds.patch</c> files instead of repacking the game's archives. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The game's <c>.sds</c> files are opened read-only and never written, moved or backed up — the | ||
| /// edited archive is packed in memory from the extracted folder and diffed against the original. | ||
| /// This is the difference between exporting and <see cref="SdsWriter.PackSds(System.IO.FileInfo, bool)"/>, | ||
| /// which replaces the archive in place. | ||
| /// </remarks> | ||
| 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> | ||
| /// <remarks> | ||
| /// Districts ship twice: <c>sandisland.sds</c> for summer and <c>sandisland_z.sds</c> for winter. | ||
| /// The two hold different geometry at different resource ordinals, so a patch built against one | ||
| /// is silently inert in a session running the other — the engine never even asks for it. | ||
| /// </remarks> | ||
| 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) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); | ||
|
|
||
| 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")); | ||
| } | ||
|
|
||
| // The edited archive is built in memory. Nothing is written next to the game file, and the | ||
| // original is only ever read. | ||
| SdsArchive edited = SdsArchive.Pack(extracted, GameProfile.MafiaII); | ||
| SdsArchive original = SdsArchive.Open(sds.FullName); | ||
|
|
||
| (SdsPatchFile patch, PatchDiffResult result) = SdsPatchDiff.Between(original, edited); | ||
|
|
||
| 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 removals carry across: they are expressed by frame name, and names are all but identical | ||
| /// between the two copies of a district — 3,387 of 3,399 on sandisland, the rest being the | ||
| /// seasonal geometry itself, which lives in disjoint name ranges. Ordinals and resource bytes are | ||
| /// not portable, which is exactly why the twin is rebuilt rather than copied. | ||
| /// </remarks> | ||
| public static IReadOnlyList<PatchExportResult> ExportWithSeasonVariant(FileInfo sds, string outputPath) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sds); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); | ||
|
|
||
| var exported = new List<PatchExportResult> { Export(sds, outputPath) }; | ||
|
|
||
| FileInfo? twin = SeasonVariantOf(sds); | ||
| if (twin is null) | ||
| { | ||
| return exported; | ||
| } | ||
|
|
||
| // What the edit removed, by name — the only part of a diff that means anything in the twin. | ||
| SdsArchive original = SdsArchive.Open(sds.FullName); | ||
| SdsArchive edited = SdsArchive.Pack(MafiaEnvironment.ExtractedDir(sds), GameProfile.MafiaII); | ||
| 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)); | ||
| author.RemoveFrames(removedNames); | ||
|
|
||
| string twinPath = Path.Combine( | ||
| Path.GetDirectoryName(outputPath) ?? string.Empty, | ||
| SuggestFileName(twin)); | ||
|
|
||
| using (FileStream output = File.Create(twinPath)) | ||
| { | ||
| author.Build().Save(output); | ||
| } | ||
|
|
||
| exported.Add(new PatchExportResult( | ||
| twin.FullName, | ||
| twinPath, | ||
| new PatchDiffResult(Changed: 1, 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); | ||
|
|
||
| var exported = new List<PatchExportResult>(); | ||
| foreach (FileInfo sds in archives) | ||
| { | ||
| try | ||
| { | ||
| exported.Add(Export(sds, Path.Combine(targetFolder, SuggestFileName(sds)))); | ||
| } | ||
| catch (InvalidOperationException) | ||
| { | ||
| // Identical to the original — nothing to ship for this one. | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| 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.
Uh oh!
There was an error while loading. Please reload this page.