Add core functionality for loading and processing game assets

- Implemented palette loading from binary files in `palette.cpp`.
- Added runtime utilities for reading text and JSON files in `runtime.cpp`.
- Created shape archive handling in `shape_archive.cpp`, including frame parsing and pixel decoding.
- Introduced type flag loading functionality in `type_flags.cpp`.
- Developed tests for combat tactics, entity dispatch entries, file system operations, fixed maps, flex archives, glob archives, map rendering, palette loading, shape archives, and type flags.
- Added a Python script for importing Ghidra-exported function slices with reporting capabilities.
This commit is contained in:
MaddoScientisto 2026-04-27 21:15:01 +02:00
commit 8907604b84
41 changed files with 2889 additions and 0 deletions

View file

@ -0,0 +1,150 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import dataclasses
import pathlib
import re
import shutil
from collections.abc import Iterable
CALLING_CONVENTION_REPLACEMENTS = {
"__cdecl16far": "CR_FARCALL",
"__cdecl16near": "CR_CDECL",
"__stdcall16far": "CR_FARCALL",
"__stdcall16near": "CR_STDCALL",
"__cdecl": "CR_CDECL",
"__stdcall": "CR_STDCALL",
"__regcall": "CR_CDECL",
}
EXPORT_HEADER_INCLUDE_RE = re.compile(r'#include\s+"(?:\.\./)*CRUSADER\.EXE\.h"')
@dataclasses.dataclass(frozen=True)
class ImportStats:
files_read: int = 0
files_written: int = 0
callconv_replacements: int = 0
namespace_qualified_functions: int = 0
unresolved_tokens: tuple[str, ...] = ()
def normalize_text(text: str) -> tuple[str, int]:
replacement_count = 0
text = EXPORT_HEADER_INCLUDE_RE.sub('#include "remorse/export_prelude.h"', text)
for source, target in CALLING_CONVENTION_REPLACEMENTS.items():
text, count = re.subn(rf"\b{re.escape(source)}\b", target, text)
replacement_count += count
return text, replacement_count
def find_unresolved_tokens(text: str) -> tuple[str, ...]:
tokens = []
for token in ("unaff_SS", "unaff_CS", "__return_storage_ptr__", "CONCAT22", "BADSPACEBASE"):
if token in text:
tokens.append(token)
return tuple(tokens)
def iter_source_files(source_root: pathlib.Path) -> Iterable[pathlib.Path]:
for path in sorted(source_root.rglob("*")):
if path.is_file() and path.suffix.lower() in {".c", ".h"}:
yield path
def import_slice(export_root: pathlib.Path, slice_path: pathlib.Path, output_root: pathlib.Path) -> ImportStats:
source_root = export_root / "functions" / slice_path
if not source_root.is_dir():
raise FileNotFoundError(f"export slice does not exist: {source_root}")
destination_root = output_root / slice_path
if destination_root.exists():
shutil.rmtree(destination_root)
destination_root.mkdir(parents=True, exist_ok=True)
files_read = 0
files_written = 0
callconv_replacements = 0
namespace_qualified_functions = 0
unresolved_tokens: set[str] = set()
for source_file in iter_source_files(source_root):
files_read += 1
relative_path = source_file.relative_to(source_root)
destination_name = relative_path.with_suffix(".cpp") if source_file.suffix.lower() == ".c" else relative_path
destination_file = destination_root / destination_name
destination_file.parent.mkdir(parents=True, exist_ok=True)
original = source_file.read_text(encoding="utf-8", errors="replace")
normalized, replacement_count = normalize_text(original)
callconv_replacements += replacement_count
namespace_qualified_functions += normalized.count("Remorse::")
unresolved_tokens.update(find_unresolved_tokens(normalized))
destination_file.write_text(normalized, encoding="utf-8", newline="\n")
files_written += 1
return ImportStats(
files_read=files_read,
files_written=files_written,
callconv_replacements=callconv_replacements,
namespace_qualified_functions=namespace_qualified_functions,
unresolved_tokens=tuple(sorted(unresolved_tokens)),
)
def write_report(path: pathlib.Path, slice_path: pathlib.Path, stats: ImportStats) -> None:
lines = [
"# Export Slice Import Report",
"",
f"Slice: `{slice_path.as_posix()}`",
f"Files read: {stats.files_read}",
f"Files written: {stats.files_written}",
f"Calling-convention replacements: {stats.callconv_replacements}",
f"Namespace-qualified references: {stats.namespace_qualified_functions}",
"",
"## Remaining Cleanup Signals",
"",
]
if stats.unresolved_tokens:
lines.extend(f"- `{token}`" for token in stats.unresolved_tokens)
else:
lines.append("- No tracked unresolved tokens found by this importer.")
lines.extend(
[
"",
"This is a staging import only. Do not link the generated files into the host rebuild until their types, globals, and segmented-pointer behavior are reviewed.",
"",
]
)
path.write_text("\n".join(lines), encoding="utf-8", newline="\n")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Stage one Ghidra-exported function slice for manual Remorse rebuild cleanup.")
parser.add_argument("slice", help="Path under exports/src_remorse/functions, such as classes/Remorse/EntityDispatchEntry")
parser.add_argument("--export-root", type=pathlib.Path, default=pathlib.Path("exports/src_remorse"))
parser.add_argument("--output-root", type=pathlib.Path, default=pathlib.Path("rebuild/remorse/imported"))
parser.add_argument("--report", type=pathlib.Path, default=pathlib.Path("rebuild/remorse/imported/import_report.md"))
return parser.parse_args()
def main() -> int:
args = parse_args()
slice_path = pathlib.Path(args.slice)
stats = import_slice(args.export_root, slice_path, args.output_root)
args.report.parent.mkdir(parents=True, exist_ok=True)
write_report(args.report, slice_path, stats)
print(f"Imported {stats.files_written} files from {slice_path.as_posix()} into {args.output_root / slice_path}")
print(f"Report: {args.report}")
return 0
if __name__ == "__main__":
raise SystemExit(main())