Initial
Rust validation / Windows x64 build and tests (push) Waiting to run
Rust validation / Formatting (push) Failing after 26s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s

This commit is contained in:
EonaCat committed 2026-12-04 21:27:30 +01:00
1 parent 2cff35f215
commit 53e6e612c9
360 files changed
+253990 -74

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "eonacat-xsbox-game"
description = "Everything specific to the title: its containers, build identities, patches."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
eonacat-xsbox-gpu = { path = "../graphics" }
memchr.workspace = true
zlib-rs.workspace = true
thiserror.workspace = true
tracing.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi"] }
[lints]
workspace = true
+115
View File
@@ -0,0 +1,115 @@
pub mod prompts;
pub mod sgd5;
#[derive(Debug, Clone, Copy)]
pub struct KnownBuild {
pub label: &'static str,
pub blake3: &'static str,
pub patches: &'static [CodePatch],
pub startup_archive: &'static str,
pub archives: &'static [&'static str],
pub required_files: &'static [RequiredFile],
pub key_prompts: prompts::HookOffsets,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RequiredFile {
pub path: &'static str,
pub size: u64,
pub without: &'static str,
}
#[derive(Debug, Clone, Copy)]
pub struct CodePatch {
pub name: &'static str,
pub rva: u32,
pub expect: &'static [u8],
pub write: &'static [u8],
}
const UPSCALER_6: &[u8] = &[0xb8, 0x06, 0x00, 0x00, 0x00, 0xc3];
pub const KNOWN_BUILDS: &[KnownBuild] = &[KnownBuild {
label: "Xbox Series master",
blake3: "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93",
patches: &[
CodePatch {
name: "upscaler choice",
rva: 0x7e_93f0,
expect: &[0x48, 0x83, 0xec, 0x28, 0x80, 0x3d],
write: UPSCALER_6,
},
CodePatch {
name: "upscaler choice (the per-frame copy)",
rva: 0x540_0190,
expect: &[0x48, 0x83, 0xec, 0x28, 0x48, 0x8b],
write: UPSCALER_6,
},
],
startup_archive: "appdata0.rpf",
archives: &[
"anim.rpf",
"appdata0.rpf",
"audio.rpf",
"common.rpf",
"data.rpf",
"levels.rpf",
"movies.rpf",
"navmeshes.rpf",
"packs.rpf",
"script.rpf",
"shaders.rpf",
"textures.rpf",
],
required_files: &[RequiredFile {
path: "data/ttdb/graphics/ttdb_graphics.ttpf",
size: 34_411_776,
without: "the title stops while loading, at its own breakpoint +0x3e42541 (#421)",
}],
key_prompts: prompts::HookOffsets {
movie_address_builder: prompts::PointerOffset(0x62f_3388),
string_assign: prompts::CodeOffset(0xeb_ba60),
},
}];
#[derive(Debug, Default, PartialEq, Eq)]
pub struct PackageCheck {
pub missing: Vec<&'static RequiredFile>,
pub other_size: Vec<(&'static RequiredFile, u64)>,
}
pub fn check_package(build: &'static KnownBuild, dir: &std::path::Path) -> PackageCheck {
let mut check = PackageCheck::default();
for file in build.required_files {
let path = file
.path
.split('/')
.fold(dir.to_path_buf(), |p, part| p.join(part));
match std::fs::metadata(&path) {
Ok(m) if m.is_file() && m.len() == file.size => {}
Ok(m) if m.is_file() => check.other_size.push((file, m.len())),
_ => check.missing.push(file),
}
}
check
}
pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> {
KNOWN_BUILDS
.iter()
.find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex))
}
+420
View File
@@ -0,0 +1,420 @@
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use eonacat_xsbox_gpu::core::pad::{
PadControl, VK_BACK, VK_DOWN, VK_ESCAPE, VK_LEFT, VK_RETURN, VK_RIGHT, VK_TAB, VK_UP,
fallback_key,
};
use eonacat_xsbox_gpu::formats::gfx::{
self, Change, Contour, Depth, Edge, Movie, Placement, Point, ShapeBody, Sprite,
};
#[cfg(windows)]
mod font;
#[cfg(windows)]
pub mod hook;
#[derive(Debug, Clone, Copy)]
pub struct PointerOffset(pub u32);
#[derive(Debug, Clone, Copy)]
pub struct CodeOffset(pub u32);
#[derive(Debug, Clone, Copy)]
pub struct HookOffsets {
pub movie_address_builder: PointerOffset,
pub string_assign: CodeOffset,
}
const ICONS: &[(u32, &[PadControl])] = {
use PadControl as C;
const LEFT: &[PadControl] = &[
C::LeftStickUp,
C::LeftStickLeft,
C::LeftStickDown,
C::LeftStickRight,
];
const RIGHT: &[PadControl] = &[
C::RightStickUp,
C::RightStickLeft,
C::RightStickDown,
C::RightStickRight,
];
const PAD: &[PadControl] = &[C::Up, C::Down, C::Left, C::Right];
&[
(4, &[C::Up]),
(5, &[C::Down]),
(6, &[C::Left]),
(7, &[C::Right]),
(8, PAD),
(9, PAD),
(10, &[C::Up, C::Down]),
(11, &[C::Left, C::Right]),
(12, &[C::LeftStickUp]),
(13, &[C::LeftStickDown]),
(14, &[C::LeftStickLeft]),
(15, &[C::LeftStickRight]),
(16, &[C::LeftStick]),
(17, LEFT),
(18, &[C::LeftStickUp, C::LeftStickDown]),
(19, &[C::LeftStickLeft, C::LeftStickRight]),
(20, LEFT),
(21, &[C::RightStickUp]),
(22, &[C::RightStickDown]),
(23, &[C::RightStickLeft]),
(24, &[C::RightStickRight]),
(25, &[C::RightStick]),
(26, RIGHT),
(27, &[C::RightStickUp, C::RightStickDown]),
(28, &[C::RightStickLeft, C::RightStickRight]),
(29, RIGHT),
(30, &[C::A]),
(31, &[C::B]),
(32, &[C::X]),
(33, &[C::Y]),
(34, &[C::LeftShoulder]),
(35, &[C::LeftTrigger]),
(36, &[C::RightShoulder]),
(37, &[C::RightTrigger]),
(38, &[C::Menu]),
(39, &[C::View]),
(58, LEFT),
(59, RIGHT),
]
};
const FEWEST_ICONS: usize = 20;
const FACE_BUTTONS: [PadControl; 4] = [PadControl::A, PadControl::B, PadControl::X, PadControl::Y];
const CELL_TWIPS: i32 = 1280;
const CAP_MARGIN_TWIPS: i32 = 50;
const CAP_RADIUS_TWIPS: i32 = 220;
const LABEL_MARGIN_TWIPS: i32 = 250;
const TALLEST_ROW_TWIPS: f64 = 640.0;
const ROW_EMS: f64 = 1.05;
const WHITE: [u8; 4] = [0xFF; 4];
const BLACK: [u8; 4] = [0, 0, 0, 0xFF];
pub(crate) type EmPoint = [f64; 2];
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Glyph {
pub(crate) contours: Vec<Contour<EmPoint>>,
pub(crate) advance_ems: f64,
}
fn key_label(virtual_key: u8) -> Option<&'static str> {
const LETTERS: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS: &str = "0123456789";
Some(match virtual_key {
0x01 => "LMB",
0x02 => "RMB",
0x04 => "MMB",
0x05 => "M4",
0x06 => "M5",
VK_BACK => "\u{232B}",
VK_TAB => "Tab",
VK_RETURN => "\u{21B5}",
0x10 | 0xA0 | 0xA1 => "Shift",
0x11 | 0xA2 | 0xA3 => "Ctrl",
0x12 | 0xA4 | 0xA5 => "Alt",
VK_ESCAPE => "Esc",
0x20 => "Space",
VK_LEFT => "\u{2190}",
VK_UP => "\u{2191}",
VK_RIGHT => "\u{2192}",
VK_DOWN => "\u{2193}",
b'0'..=b'9' => {
let at = usize::from(virtual_key - b'0');
DIGITS.get(at..=at)?
}
b'A'..=b'Z' => {
let at = usize::from(virtual_key - b'A');
LETTERS.get(at..=at)?
}
_ => return None,
})
}
static BOUND_KEYS: OnceLock<Vec<(PadControl, Vec<u8>)>> = OnceLock::new();
pub fn use_bound_keys(keys: Vec<(PadControl, Vec<u8>)>) -> bool {
BOUND_KEYS.set(keys).is_ok()
}
fn input_labels(controls: &[PadControl]) -> Option<Vec<&'static str>> {
labels_for(BOUND_KEYS.get().map(Vec::as_slice), controls)
}
fn labels_for(
bound: Option<&[(PadControl, Vec<u8>)]>,
controls: &[PadControl],
) -> Option<Vec<&'static str>> {
controls
.iter()
.map(|&control| match bound {
Some(bound) => bound
.iter()
.filter(|(bound_to, _)| *bound_to == control)
.flat_map(|(_, keys)| keys)
.find_map(|&key| key_label(key)),
None => key_label(fallback_key(control)),
})
.collect()
}
fn cap() -> Contour {
let (low, high) = (CAP_MARGIN_TWIPS, CELL_TWIPS - CAP_MARGIN_TWIPS);
let (near, far) = (low + CAP_RADIUS_TWIPS, high - CAP_RADIUS_TWIPS);
let point = |x, y| Point { x, y };
let corner = |cx, cy, x, y| Edge::Curve {
control: point(cx, cy),
to: point(x, y),
};
Contour {
start: point(near, low),
edges: vec![
Edge::Line(point(far, low)),
corner(high, low, high, near),
Edge::Line(point(high, far)),
corner(high, high, far, high),
Edge::Line(point(near, high)),
corner(low, high, low, far),
Edge::Line(point(low, near)),
corner(low, low, near, low),
],
}
}
fn label(keys: &[&str], glyphs: &HashMap<char, Glyph>) -> Option<Vec<Contour>> {
let rows: Vec<String> = if keys.len() == 4 {
keys.chunks(2).map(<[&str]>::concat).collect()
} else {
vec![keys.concat()]
};
let mut placed: Vec<Vec<Contour<EmPoint>>> = Vec::new();
let mut down = 0.0;
for row in rows {
let mut contours = Vec::new();
let mut pen = 0.0;
for character in row.chars() {
let glyph = glyphs.get(&character)?;
let place = |[x, y]: EmPoint| [x + pen, down - y];
contours.extend(glyph.contours.iter().map(|contour| contour.map(place)));
pen += glyph.advance_ems;
}
placed.push(contours);
down += ROW_EMS;
}
let extent = |contours: &[Contour<EmPoint>], axis: usize| {
contours
.iter()
.flat_map(Contour::points)
.fold((f64::MAX, f64::MIN), |(low, high), point| {
(low.min(point[axis]), high.max(point[axis]))
})
};
let widths: Vec<(f64, f64)> = placed.iter().map(|row| extent(row, 0)).collect();
let heights: Vec<(f64, f64)> = placed.iter().map(|row| extent(row, 1)).collect();
let widest = widths
.iter()
.map(|(low, high)| high - low)
.fold(0.0, f64::max);
let tallest_row = heights
.iter()
.map(|(low, high)| high - low)
.fold(0.0, f64::max);
let (top, bottom) = heights
.iter()
.fold((f64::MAX, f64::MIN), |(low, high), &(a, b)| {
(low.min(a), high.max(b))
});
if !(widest > 0.0 && tallest_row > 0.0) {
return None;
}
let room = f64::from(CELL_TWIPS - 2 * LABEL_MARGIN_TWIPS);
let scale = (room / widest)
.min(room / (bottom - top))
.min(TALLEST_ROW_TWIPS / tallest_row);
let middle = f64::from(CELL_TWIPS) / 2.0;
let mut contours = Vec::new();
for (row, (low, high)) in placed.iter().zip(&widths) {
#[expect(
clippy::cast_possible_truncation,
reason = "a position inside one icon cell"
)]
let twips = |[x, y]: EmPoint| Point {
x: (middle + (x - (low + high) / 2.0) * scale).round() as i32,
y: (middle + (y - (top + bottom) / 2.0) * scale).round() as i32,
};
contours.extend(row.iter().map(|contour| contour.map(twips)));
}
Some(contours)
}
fn icon_number(name: &[u8]) -> Option<u32> {
let digits = name.get(name.iter().rposition(|&byte| byte == b'_')? + 1..)?;
if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
return None;
}
std::str::from_utf8(digits).ok()?.parse().ok()
}
fn still_shapes(sprite: &Sprite) -> Option<Vec<u16>> {
let mut placed: Vec<(Depth, u16)> = sprite
.placements
.iter()
.map(|placement| match placement.change {
Change::Place(character) if placement.frame == 0 => Some((placement.depth, character)),
Change::Place(_)
| Change::Mask(_)
| Change::Replace(_)
| Change::Modify
| Change::Remove
| Change::Unread => None,
})
.collect::<Option<_>>()?;
placed.sort_unstable();
if placed.windows(2).any(|pair| pair[0].0 == pair[1].0) {
return None;
}
Some(placed.into_iter().map(|(_, shape)| shape).collect())
}
fn controls(number: u32) -> Option<&'static [PadControl]> {
ICONS
.iter()
.find(|(known, _)| *known == number)
.map(|(_, controls)| *controls)
}
fn uses(sprites: &[Sprite], timeline: &[Placement]) -> Option<HashMap<u16, u32>> {
let mut uses = HashMap::new();
let placements = sprites
.iter()
.flat_map(|sprite| &sprite.placements)
.chain(timeline);
for placement in placements {
match placement.change {
Change::Place(character) | Change::Mask(character) | Change::Replace(character) => {
*uses.entry(character).or_insert(0) += 1;
}
Change::Modify | Change::Remove => {}
Change::Unread => return None,
}
}
Some(uses)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Refusal {
NotIconMovie,
Unreadable,
NothingDrawn,
}
#[cfg_attr(
not(windows),
expect(dead_code, reason = "only the Windows hook draws key caps")
)]
pub(crate) fn key_caps(
movie: &[u8],
glyph: &dyn Fn(char) -> Option<Glyph>,
) -> Result<Vec<u8>, Refusal> {
let movie = Movie::parse(movie).ok_or(Refusal::NotIconMovie)?;
let mut numbers = HashSet::new();
let mut wanted: HashMap<u16, &'static [PadControl]> = HashMap::new();
for (sprite, name) in movie.classes().ok_or(Refusal::NotIconMovie)? {
let Some((number, controls)) = icon_number(name).and_then(|n| Some((n, controls(n)?)))
else {
continue;
};
if numbers.insert(number) {
wanted.entry(sprite).or_insert(controls);
}
}
let has_icon = |button: PadControl| {
ICONS
.iter()
.any(|&(number, controls)| controls == [button] && numbers.contains(&number))
};
if numbers.len() < FEWEST_ICONS || !FACE_BUTTONS.into_iter().all(has_icon) {
return Err(Refusal::NotIconMovie);
}
if movie.defines_buttons() {
return Err(Refusal::Unreadable);
}
let sprites = movie.sprites().ok_or(Refusal::Unreadable)?;
let timeline = movie.timeline().ok_or(Refusal::Unreadable)?;
let uses = uses(&sprites, &timeline).ok_or(Refusal::Unreadable)?;
let icons: Vec<(&[PadControl], Vec<u16>)> = sprites
.iter()
.filter_map(|sprite| Some((wanted.remove(&sprite.id)?, still_shapes(sprite)?)))
.collect();
if icons.iter().filter(|(_, shapes)| shapes.len() >= 2).count() < FEWEST_ICONS {
return Err(Refusal::NotIconMovie);
}
let definitions = movie.shape_counts();
let mut asked = HashSet::new();
let mut glyphs: HashMap<char, Glyph> = HashMap::new();
for character in icons
.iter()
.filter_map(|(controls, _)| input_labels(controls))
.flatten()
.flat_map(str::chars)
{
if asked.insert(character)
&& let Some(found) = glyph(character)
{
glyphs.insert(character, found);
}
}
let mut bodies: Vec<ShapeBody> = Vec::new();
for (controls, shapes) in &icons {
let [back, front, rest @ ..] = shapes.as_slice() else {
continue;
};
if shapes
.iter()
.any(|shape| uses.get(shape) != Some(&1) || definitions.get(shape) != Some(&1))
{
continue;
}
let Some(keys) = input_labels(controls) else {
continue;
};
let Some(label) = label(&keys, &glyphs).and_then(|label| gfx::shape(*front, BLACK, &label))
else {
continue;
};
bodies.push(gfx::shape(*back, WHITE, &[cap()]).ok_or(Refusal::Unreadable)?);
bodies.push(label);
for &shape in rest {
bodies.push(gfx::shape(shape, BLACK, &[]).ok_or(Refusal::Unreadable)?);
}
}
if bodies.is_empty() {
return Err(Refusal::NothingDrawn);
}
movie.replace_shapes(&bodies).ok_or(Refusal::Unreadable)
}
+227
View File
@@ -0,0 +1,227 @@
use std::ptr;
use windows_sys::Win32::Graphics::Gdi::{
CreateCompatibleDC, CreateFontW, DEFAULT_CHARSET, DeleteDC, DeleteObject, FIXED, FW_BOLD,
GGI_MARK_NONEXISTING_GLYPHS, GGO_NATIVE, GGO_UNHINTED, GLYPHMETRICS, GetGlyphIndicesW,
GetGlyphOutlineW, HDC, HFONT, MAT2, SelectObject, TT_PRIM_LINE, TT_PRIM_QSPLINE,
};
use eonacat_xsbox_gpu::formats::gfx::{Contour, Edge};
use super::{EmPoint, Glyph};
#[derive(Clone, Copy, Debug)]
enum Face {
Letters,
Signs,
}
impl Face {
fn name(self) -> &'static str {
match self {
Self::Letters => "Segoe UI",
Self::Signs => "Segoe UI Symbol",
}
}
}
pub(super) struct Fonts {
letters: Option<Font>,
signs: Option<Font>,
}
impl Fonts {
pub(super) fn open() -> Self {
Self {
letters: Font::open(Face::Letters),
signs: Font::open(Face::Signs),
}
}
pub(super) fn glyph(&self, character: char) -> Option<Glyph> {
let from = |font: &Option<Font>| font.as_ref()?.glyph(character);
from(&self.letters).or_else(|| from(&self.signs))
}
}
const EM_PIXELS: i32 = 1024;
const LARGEST_OUTLINE_BYTES: u32 = 1 << 20;
const MISSING_GLYPH: u16 = 0xFFFF;
const OUTLINE_FAILED: u32 = u32::MAX;
struct Font {
dc: HDC,
font: HFONT,
}
impl Font {
fn open(face: Face) -> Option<Self> {
let face: Vec<u16> = face.name().encode_utf16().chain([0]).collect();
unsafe {
let dc = CreateCompatibleDC(ptr::null_mut());
if dc.is_null() {
return None;
}
let font = CreateFontW(
-EM_PIXELS,
0,
0,
0,
FW_BOLD.cast_signed(),
0,
0,
0,
u32::from(DEFAULT_CHARSET),
0,
0,
0,
0,
face.as_ptr(),
);
if font.is_null() {
DeleteDC(dc);
return None;
}
SelectObject(dc, font);
Some(Self { dc, font })
}
}
fn glyph(&self, character: char) -> Option<Glyph> {
let mut units = [0u16; 2];
let [unit] = *character.encode_utf16(&mut units) else {
return None;
};
let one = FIXED { fract: 0, value: 1 };
let zero = FIXED { fract: 0, value: 0 };
let identity = MAT2 {
eM11: one,
eM12: zero,
eM21: zero,
eM22: one,
};
let format = GGO_NATIVE | GGO_UNHINTED;
let mut index = MISSING_GLYPH;
let mut metrics = GLYPHMETRICS::default();
let size = unsafe {
GetGlyphIndicesW(
self.dc,
&raw const unit,
1,
&raw mut index,
GGI_MARK_NONEXISTING_GLYPHS,
);
if index == MISSING_GLYPH {
return None;
}
GetGlyphOutlineW(
self.dc,
u32::from(unit),
format,
&raw mut metrics,
0,
ptr::null_mut(),
&raw const identity,
)
};
if size == OUTLINE_FAILED || size > LARGEST_OUTLINE_BYTES {
return None;
}
let mut bytes = vec![0u8; usize::try_from(size).ok()?];
let written = unsafe {
GetGlyphOutlineW(
self.dc,
u32::from(unit),
format,
&raw mut metrics,
size,
bytes.as_mut_ptr().cast(),
&raw const identity,
)
};
if written != size {
return None;
}
Some(Glyph {
contours: contours(&bytes)?,
advance_ems: f64::from(metrics.gmCellIncX) / f64::from(EM_PIXELS),
})
}
}
impl Drop for Font {
fn drop(&mut self) {
unsafe {
DeleteDC(self.dc);
DeleteObject(self.font);
}
}
}
fn contours(bytes: &[u8]) -> Option<Vec<Contour<EmPoint>>> {
let word = |at: usize| Some(u16::from_le_bytes(*bytes.get(at..)?.first_chunk()?));
let long = |at: usize| Some(u32::from_le_bytes(*bytes.get(at..)?.first_chunk()?));
let point = |at: usize| -> Option<EmPoint> {
let fixed =
|at: usize| Some(f64::from(long(at)?.cast_signed()) / 65536.0 / f64::from(EM_PIXELS));
Some([fixed(at)?, fixed(at.checked_add(4)?)?])
};
let mut found = Vec::new();
let mut at = 0usize;
while at < bytes.len() {
let size = usize::try_from(long(at)?).ok()?;
let end = at
.checked_add(size)
.filter(|&end| size >= 16 && end <= bytes.len())?;
let start = point(at + 8)?;
let mut edges = Vec::new();
let mut from = start;
let mut record = at + 16;
while record < end {
let (kind, count) = (u32::from(word(record)?), usize::from(word(record + 2)?));
let next = record + 4 + count * 8;
if next > end {
return None;
}
let points = (0..count)
.map(|i| point(record + 4 + i * 8))
.collect::<Option<Vec<_>>>()?;
match kind {
TT_PRIM_LINE => edges.extend(points.iter().map(|&to| Edge::Line(to))),
TT_PRIM_QSPLINE => edges.extend(points.windows(2).enumerate().map(|(i, pair)| {
let (control, next) = (pair[0], pair[1]);
let to = if i + 2 == points.len() {
next
} else {
[(control[0] + next[0]) / 2.0, (control[1] + next[1]) / 2.0]
};
Edge::Curve { control, to }
})),
_ => return None,
}
from = edges
.last()
.map_or(from, |edge: &Edge<EmPoint>| edge.points()[1]);
record = next;
}
if from != start {
edges.push(Edge::Line(start));
}
found.push(Contour { start, edges });
at = end;
}
Some(found)
}
+363
View File
@@ -0,0 +1,363 @@
use std::cell::OnceCell;
use std::ffi::{CString, c_char, c_void};
use std::mem::offset_of;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use eonacat_xsbox_gpu::formats::gfx;
use eonacat_xsbox_gpu::loader::{LoadedImage, SlotError};
use super::{HookOffsets, Refusal, font::Fonts, key_caps};
const TEXT_BUFFER_BYTES: usize = 512;
const LARGEST_MOVIE_BYTES: usize = 256 << 10;
const MOST_DRAWN: usize = 8;
const MOST_STORED: usize = 64;
const STRING_FLAG_MASK: usize = 3;
const STRING_TEXT_OFFSET_BYTES: usize = 12;
#[repr(transparent)]
#[derive(Clone, Copy, Debug)]
struct UiString(usize);
#[repr(C)]
struct Location {
kind: u32,
name: UiString,
}
const _: () = assert!(offset_of!(Location, kind) == 0 && offset_of!(Location, name) == 8);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Request {
HandedOver,
LoadedByAMovie,
}
impl TryFrom<u32> for Request {
type Error = u32;
fn try_from(kind: u32) -> Result<Self, u32> {
match kind {
0 => Ok(Self::HandedOver),
3 => Ok(Self::LoadedByAMovie),
other => Err(other),
}
}
}
type BuildAddress = unsafe extern "system" fn(*mut c_void, *mut UiString, *const Location);
type AssignString = unsafe extern "system" fn(*mut UiString, *const c_char);
struct Title {
build_address: BuildAddress,
assign_string: AssignString,
}
static TITLE: OnceLock<Title> = OnceLock::new();
static SERVED: AtomicBool = AtomicBool::new(false);
#[derive(Clone, Copy, Debug)]
enum Warning {
Unreadable,
NothingDrawn,
TooManyMovies,
}
static WARNED: AtomicU8 = AtomicU8::new(0);
fn warn_once(warning: Warning) {
let bit = 1 << warning as u8;
if WARNED.fetch_or(bit, Ordering::Relaxed) & bit == 0 {
tracing::warn!(
?warning,
"prompts: the icon movie keeps its gamepad pictures"
);
}
}
struct Drawn {
original: Box<[u8]>,
redrawn: &'static [u8],
}
struct Stored {
tag: String,
address: usize,
len: usize,
redrawn: &'static [u8],
}
struct Kept {
drawn: Vec<Drawn>,
refused: Vec<Box<[u8]>>,
stored: Vec<Stored>,
}
static KEPT: Mutex<Kept> = Mutex::new(Kept {
drawn: Vec::new(),
refused: Vec::new(),
stored: Vec::new(),
});
fn kept() -> MutexGuard<'static, Kept> {
KEPT.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Debug, thiserror::Error)]
pub enum Refused {
#[error("the pointer does not lead to code of the image")]
NotATitlePointer,
#[error("the hook is already placed")]
AlreadyPlaced,
#[error(transparent)]
Slot(#[from] SlotError),
}
pub unsafe fn install(image: &LoadedImage, offsets: HookOffsets) -> Result<(), Refused> {
let assign_string = image.code_address(offsets.string_assign.0)?;
let slot = offsets.movie_address_builder.0;
let build_address = unsafe { image.read_pointer(slot) }?;
let builder_offset = build_address
.checked_sub(image.base())
.and_then(|offset| u32::try_from(offset).ok())
.ok_or(Refused::NotATitlePointer)?;
if image.code_address(builder_offset).is_err() {
return Err(Refused::NotATitlePointer);
}
let title = unsafe {
Title {
build_address: std::mem::transmute::<usize, BuildAddress>(build_address),
assign_string: std::mem::transmute::<usize, AssignString>(assign_string),
}
};
TITLE.set(title).map_err(|_| Refused::AlreadyPlaced)?;
let hook: BuildAddress = movie_address;
unsafe { image.write_pointer(slot, hook as usize) }?;
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
struct InMemory<'a> {
address: usize,
len: usize,
tag: &'a str,
}
impl<'a> InMemory<'a> {
fn parse(text: &'a str) -> Option<Self> {
let (fields, tag) = text.strip_prefix("memory:$")?.split_once(':')?;
let mut fields = fields.split(',');
let address = usize::from_str_radix(fields.next()?, 16).ok()?;
let len: usize = fields.next()?.parse().ok()?;
(address != 0 && (gfx::HEADER_BYTES..=LARGEST_MOVIE_BYTES).contains(&len)).then_some(Self {
address,
len,
tag,
})
}
}
fn address_text(movie: &[u8], name: &str) -> Option<CString> {
CString::new(format!(
"memory:${:016X},{},0:eonacat-xs:{name}",
movie.as_ptr().addr(),
movie.len()
))
.ok()
}
struct UiText {
bytes: [u8; TEXT_BUFFER_BYTES],
len: usize,
}
impl UiText {
fn as_str(&self) -> &str {
self.bytes
.get(..self.len)
.and_then(|text| std::str::from_utf8(text).ok())
.unwrap_or_default()
}
unsafe fn read(string: UiString) -> Option<Self> {
let block = string.0 & !STRING_FLAG_MASK;
if block == 0 {
return None;
}
let from = block.checked_add(STRING_TEXT_OFFSET_BYTES)? as *const u8;
let mut text = Self {
bytes: [0; TEXT_BUFFER_BYTES],
len: 0,
};
for at in 0..TEXT_BUFFER_BYTES {
let byte = unsafe { from.add(at).read() };
if byte == 0 {
text.len = at;
let valid = std::str::from_utf8(text.bytes.get(..at)?).is_ok();
return (valid && at > 0).then_some(text);
}
*text.bytes.get_mut(at)? = byte;
}
None
}
}
unsafe fn copy_of(memory: &InMemory) -> Option<Box<[u8]>> {
let from = memory.address as *const u8;
let header = unsafe { from.cast::<[u8; gfx::HEADER_BYTES]>().read_unaligned() };
if !gfx::names_movie(&header, memory.len) {
return None;
}
let mut copy = Vec::with_capacity(memory.len);
unsafe {
from.copy_to_nonoverlapping(copy.as_mut_ptr(), memory.len);
copy.set_len(memory.len);
}
Some(copy.into_boxed_slice())
}
fn redrawn(original: Box<[u8]>) -> Option<&'static [u8]> {
let drawn_before = |kept: &Kept| {
kept.drawn
.iter()
.find(|drawn| drawn.original == original)
.map(|drawn| drawn.redrawn)
};
{
let kept = kept();
if let Some(redrawn) = drawn_before(&kept) {
return Some(redrawn);
}
if kept.refused.contains(&original) {
return None;
}
if kept.drawn.len() >= MOST_DRAWN {
drop(kept);
warn_once(Warning::TooManyMovies);
return None;
}
}
let fonts = OnceCell::new();
let glyph = |character| fonts.get_or_init(Fonts::open).glyph(character);
let warning = match key_caps(&original, &glyph) {
Ok(drawn) => {
let drawn = drawn.into_boxed_slice();
let mut kept = kept();
if let Some(redrawn) = drawn_before(&kept) {
return Some(redrawn);
}
let redrawn: &'static [u8] = Box::leak(drawn);
kept.drawn.push(Drawn { original, redrawn });
drop(kept);
tracing::info!(
bytes = redrawn.len(),
"prompts: key caps drawn into the icon movie"
);
return Some(redrawn);
}
Err(Refusal::NotIconMovie) => return None,
Err(Refusal::Unreadable) => Warning::Unreadable,
Err(Refusal::NothingDrawn) => Warning::NothingDrawn,
};
let mut kept = kept();
if kept.refused.len() < MOST_DRAWN && !kept.refused.contains(&original) {
kept.refused.push(original);
}
drop(kept);
warn_once(warning);
None
}
unsafe fn keep(memory: &InMemory) {
let redrawn = unsafe { copy_of(memory) }.and_then(redrawn);
let mut kept = kept();
kept.stored.retain(|stored| stored.tag != memory.tag);
let Some(redrawn) = redrawn else {
return;
};
if kept.stored.len() >= MOST_STORED {
kept.stored.remove(0);
}
kept.stored.push(Stored {
tag: memory.tag.to_owned(),
address: memory.address,
len: memory.len,
redrawn,
});
}
fn served(memory: &InMemory) -> Option<&'static [u8]> {
kept()
.stored
.iter()
.find(|stored| {
stored.tag == memory.tag && stored.address == memory.address && stored.len == memory.len
})
.map(|stored| stored.redrawn)
}
fn serve(title: &Title, out: *mut UiString, name: UiString, memory: &InMemory) {
let Some(movie) = served(memory) else {
return;
};
let Some(text) =
unsafe { UiText::read(name) }.and_then(|name| address_text(movie, name.as_str()))
else {
return;
};
unsafe { (title.assign_string)(out, text.as_ptr()) };
if !SERVED.swap(true, Ordering::Relaxed) {
tracing::info!("prompts: the title loads the icon movie with key caps");
}
}
extern "system" fn movie_address(this: *mut c_void, out: *mut UiString, location: *const Location) {
let Some(title) = TITLE.get() else {
return;
};
unsafe { (title.build_address)(this, out, location) };
if out.is_null() || location.is_null() {
return;
}
let (Location { kind, name }, answer) =
unsafe { (location.read_unaligned(), out.read_unaligned()) };
let Ok(request) = Request::try_from(kind) else {
return;
};
let Some(answer) = (unsafe { UiText::read(answer) }) else {
return;
};
let Some(memory) = InMemory::parse(answer.as_str()) else {
return;
};
match request {
Request::HandedOver => unsafe { keep(&memory) },
Request::LoadedByAMovie => serve(title, out, name, &memory),
}
}
+111
View File
@@ -0,0 +1,111 @@
pub const MAGIC: &[u8; 4] = b"SGD5";
const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes();
const MAX_UNPACKED: usize = 64 << 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Record<'a> {
pub offset: usize,
pub name: Option<&'a str>,
pub kind: u8,
packed: &'a [u8],
unpacked_size: usize,
}
impl Record<'_> {
pub fn unpack(&self) -> Option<Vec<u8>> {
let mut state = zlib_rs::Inflate::new(false, 15);
let mut out = Vec::new();
let (mut in_pos, mut out_pos) = (0usize, 0usize);
loop {
if out_pos == self.unpacked_size {
let mut extra = [0u8; 1];
let status = state
.decompress(
&self.packed[in_pos..],
&mut extra,
zlib_rs::InflateFlush::NoFlush,
)
.ok()?;
return (status == zlib_rs::Status::StreamEnd
&& state.total_out() as usize == self.unpacked_size)
.then_some(out);
}
if out_pos == out.len() {
let next_len = if out.is_empty() {
self.unpacked_size
.min(self.packed.len().saturating_mul(4).max(4096))
} else {
out.len().saturating_mul(2).min(self.unpacked_size)
};
out.resize(next_len, 0);
}
let status = state
.decompress(
&self.packed[in_pos..],
&mut out[out_pos..],
zlib_rs::InflateFlush::NoFlush,
)
.ok()?;
let next_in = state.total_in() as usize;
let next_out = state.total_out() as usize;
match status {
zlib_rs::Status::StreamEnd => {
out.truncate(next_out);
return (next_out == self.unpacked_size).then_some(out);
}
zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => {
in_pos = next_in;
out_pos = next_out;
}
zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None,
}
}
}
}
pub fn is_sgd5(file: &[u8]) -> bool {
memchr::memmem::find(file, MAGIC).is_some()
}
pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> {
memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at))
}
fn record(file: &[u8], at: usize) -> Option<Record<'_>> {
let u32_at = |o: usize| {
file.get(o..o + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize)
};
let n = u32_at(at.checked_sub(4)?)?;
let unpacked_size = u32_at(at + 8)?;
if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED {
return None;
}
let nul = at.checked_sub(6)?;
Some(Record {
offset: at,
name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(),
kind: file[at - 5],
packed: file.get(at + 12..at + n)?,
unpacked_size,
})
}
fn name_before(file: &[u8], nul: usize) -> Option<&str> {
let run = file[..nul]
.iter()
.rposition(|b| !b.is_ascii_graphic())
.map_or(0, |p| p + 1);
(run.saturating_sub(1)..nul)
.find(|&l| usize::from(file[l]) == nul - l)
.and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok())
}