Files
mandy/tools/rpf9dump/Util.cs
NWX10 65d927b61a rpf9dump: write every output under a temporary name and rename it into place
make_game.py takes ttpf manifest.json and audio_manifest.json as proof that
a step finished, and every exporter skips a file that already exists. Both
were written in place, so a stopped run or a full disk could leave:

- a truncated manifest, after which make_game.py skips that texture pool
  or the audio banks on every later run, or
- a truncated .dds / .obj / .xma.wav under its final name, kept forever
  because the next run sees it exists.

All outputs (ttpf DDS + manifest, audio_manifest.json, XMA2 .xma.wav,
model .obj, embedded and dictionary .dds) now go through Util.WriteAtomic:
written to <path>.partial, then File.Move'd over the final name; the
temporary is removed on failure, and a stale one from a stopped run is
deleted first (WriteXmaWave opens its target with FileMode.CreateNew).
The models manifest already worked this way.

Util moves to its own file so tests/Rpf9DumpDiagnostics can link it; the
diagnostics program gains four checks for WriteAtomic.

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:22:35 +03:00

35 lines
1.9 KiB
C#

// Helpers shared by rpf9dump's exporters (linked into tests/Rpf9DumpDiagnostics too).
using RpfPreview.Core;
public static class Util
{
// Every output is written to <path>.partial and renamed into place. The exporters skip any file that already
// exists, and make_game.py takes manifest.json / audio_manifest.json as proof a step finished, so a file cut
// short by a stopped run or a full disk must never appear under its final name.
public static void WriteAtomic(string path, Action<string> write)
{
string tmp = path + ".partial";
if (File.Exists(tmp)) File.Delete(tmp); // left by a stopped run; some writers open with CreateNew
try { write(tmp); File.Move(tmp, path, true); }
finally { if (File.Exists(tmp)) File.Delete(tmp); }
}
public static void WriteAllBytes(string path, byte[] data) => WriteAtomic(path, t => File.WriteAllBytes(t, data));
public static void WriteAllText(string path, string text) => WriteAtomic(path, t => File.WriteAllText(t, text));
public static string Safe(string s)
{
var bad = Path.GetInvalidFileNameChars();
var c = s.Select(ch => bad.Contains(ch) || char.IsControl(ch) ? '_' : ch).ToArray();
var v = new string(c).Trim(' ', '.'); return v.Length == 0 ? "x" : v[..Math.Min(120, v.Length)];
}
// Uncompressed 32-bit BGRA DDS (legacy header, A8R8G8B8 masks).
public static byte[] BgraDds(RageTexturePixels px)
{
var o = new byte[128 + px.Bgra32.Length];
void U(int at, uint v) => BitConverter.TryWriteBytes(o.AsSpan(at), v);
U(0, 0x20534444); U(4, 124); U(8, 0x100F); U(12, (uint)px.Height); U(16, (uint)px.Width); U(20, (uint)(px.Width * 4));
U(76, 32); U(80, 0x41); U(88, 32); U(92, 0x00FF0000); U(96, 0x0000FF00); U(100, 0x000000FF); U(104, 0xFF000000); U(108, 0x1000);
px.Bgra32.CopyTo(o, 128); return o;
}
}