diff --git a/README.md b/README.md index 1bd0c54868..69143c6b78 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,87 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder +## Scripted input for automated testing of the retail title + +Timed presses alone depend on load time and cache state. Frame-matched rules let an agent +wait for a known screen, press the virtual pad without window focus, and wait for a JSON event. +`XCL_PRESS_AT` still works and is ORed with rule input and physical controllers. + +1. Capture your own reference with `XCL_FRAME_DUMP=2`. From the title's `logs/frame_.bmp`, + keep the Legal Notices screen with Copyright selected as `references/legal-notices.bmp` + beside your rules file. References stay local: never commit captured game output. +2. Copy [examples/retail-input-rules.toml](examples/retail-input-rules.toml) to a local folder. + It compares the top-left 27 by 14 pixels of a 64 by 36 grayscale thumbnail, using mean + absolute difference on a 0–255 scale. Threshold 5 is a starting point; calibrate against + your own target and other screens. Both images use nearest-neighbor sampling and weighted + grayscale (30% red, 59% green, 11% blue). +3. Set the environment below in your usual test launcher. Wait for `GameInput: input_rule `, + parse the JSON suffix, and check `event == "completed"` and `rule == "legal-notices"`. + Keep the normal run timeout: an unmatched reference produces no completion event. + +```powershell +$env:XCL_NETWORK = '0' +$env:XCL_FRAME_DUMP = '2' +$env:XCL_INPUT_RULES = 'C:\Tests\retail-input-rules.toml' +$env:XCL_PRESS_AT = '6:A,9:A,12:A,15:A,18:A,21:A,24:A,27:A,30:A,33:A,36:A,39:A,42:A,45:A,48:A,51:A,54:A' +``` + +The example sends fallback A every three seconds from 57 seconds until a rule matches. Use no +other automated key source after 54 seconds: duplicate presses can toggle checkboxes off. +On a match, fallback stops before DOWN, a 6.5-second wait, DOWN and A; then the privacy, +terms and confirmation sequence runs after a three-second screen transition wait. +Button pulses last 0.2 seconds, with 0.8 seconds between +button starts by default. `wait N` sets the delay from the previous button's start (or adds +to a preceding wait). Input must be polled during the pulse to receive it. +Consecutive presses of the same button must start at least 0.3 seconds apart, leaving at least +0.1 seconds for release; shorter repeats are rejected with a configuration error. +If the fallback is holding the rule's first button when it matches, the sequence starts after +that fallback pulse plus the release margin. A different first button starts immediately. + +Rules and reference images load once at host startup, before title path remapping is installed. +Use host filesystem paths, not console mounts: rules are TOML; relative reference paths resolve +beside the rules file. Loading them after VFS setup could remap the host drive to the title's drive. + +```toml +[[rules]] +name = "legal-notices" # unique string, required +reference = "references/legal-notices.bmp" # local, uncompressed 24-bit BMP +region = [0.0, 0.0, 0.421875, 0.3888888888888889] # normalized x, y, width, height +threshold = 5.0 # maximum mean absolute difference +sequence = "DOWN, wait 6.5, DOWN, A" # comma-separated buttons / wait seconds +once = true # default; false repeats after cooldown +cooldown = 3.0 # seconds between matches, default 3 +``` + +Buttons: A, B, X, Y, UP, DOWN, LEFT, RIGHT, MENU, VIEW, LB, RB. There may be 1–32 rules, +evaluated in file order; only one sequence runs at a time. Cooldown is at least 0.2 seconds. +The optional `[fallback]` table has required `button` (string), `start` (nonnegative seconds) +and `interval` (seconds, greater than 0.2). It stops permanently on the first match. +Unknown fields, invalid regions, buttons or timings disable the configuration. A missing or +unreadable reference disables that rule and the fallback with a `disabled` warning; other +valid rules remain available. Neither rules nor fallback run without `XCL_FRAME_DUMP`. +Only decoded presented frame dumps are matched; intermediate targets cannot trigger input. +Frame dumps add readback and disk overhead; use the same settings when comparing test arms. + +For a frame-gated transition, split the example into two rules: `legal-notices` runs +`DOWN, wait 6.5, DOWN, A`; a second `terms` rule matches your own reference of the terms screen +with Privacy focused and unchecked, then runs `A, DOWN, A, DOWN, A`. This replaces the timed +terms-screen transition wait. Capture and calibrate that second reference locally too; no image +ships with the example. The warning countdown still needs enough time before Next can be selected. + +Each log event is a JSON object after the prefix, for example: + +```text +GameInput: input_rule {"event":"matched","rule":"legal-notices","frame":180,"t":63.5,"diff":0.0} +GameInput: input_rule {"event":"pressed","rule":"legal-notices","frame":180,"t":63.5,"button":"DOWN"} +GameInput: input_rule {"event":"completed","rule":"legal-notices","frame":180,"t":77.2} +``` + +`XCL_PRESS_AT`, `XCL_PRESS_A_AT`, fallback start, and the JSON event's `t` count seconds from guest +startup, after shader preparation. The log prefix still shows host uptime. Sequence waits are +relative to the matching frame, and sequence events retain its frame number. Fallback +presses use rule `$fallback`; disabled events have `rule` and `reason` (no frame or time). + ## Tests ```powershell diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 482f2d1ec2..82cecd091b 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1435,6 +1435,7 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI let n = PRESENTS.load(Ordering::Relaxed); // `XCL_TRACE_FRAME` also dumps intermediate targets; only the presented image belongs here. if tag == "frame" { + if decoded { crate::hle::gameinput::match_input_frame(&bmp, n); } if let Ok(mut last) = LAST_FRAME_DUMP.lock() { *last = Some(FrameDumpSample { frame: n, diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index 58aeb5c106..c42319cdf5 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -222,7 +222,7 @@ fn start() -> Instant { } /// A button by its name in `XCL_PRESS_AT`. -fn button_named(name: &str) -> Option { +pub(super) fn button_named(name: &str) -> Option { Some(match name.to_ascii_uppercase().as_str() { "A" => A, "B" => B, @@ -242,7 +242,7 @@ fn button_named(name: &str) -> Option { /// `XCL_PRESS_AT=s:BUTTON,…` ("14:A,18.5:DOWN,20:A"; buttons A B X Y UP DOWN LEFT RIGHT MENU /// VIEW LB RB) and `XCL_PRESS_A_AT=s,…`: buttons held for 200 ms at those seconds after the -/// host started (the log's times) – a title's menus walked without a person at the controls. +/// guest started (after shader preparation) – a title's menus walked without a person at the controls. fn parse_presses(script: &str, a_only: &str) -> Vec<(f64, u32)> { let mut v: Vec<(f64, u32)> = a_only.split(',').filter_map(|s| s.trim().parse().ok()).map(|s| (s, A)).collect(); for item in script.split(',').map(str::trim).filter(|s| !s.is_empty()) { @@ -254,15 +254,92 @@ fn parse_presses(script: &str, a_only: &str) -> Vec<(f64, u32)> { v } +static INPUT_EPOCH: OnceLock = OnceLock::new(); + +/// Start the scripted input clock before the guest runs its first code. +pub(crate) fn start_script_clock() { + let _ = INPUT_EPOCH.set(crate::log::uptime()); +} + +fn script_seconds(epoch: Option, host_now: f64) -> Option { + epoch.map(|start| host_now - start).filter(|&elapsed| elapsed >= 0.0) +} + +fn script_now() -> Option { + script_seconds(INPUT_EPOCH.get().copied(), crate::log::uptime()) +} + +fn scheduled_buttons(at: &[(f64, u32)], t: f64) -> u32 { + at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) +} + fn scripted() -> u32 { + let Some(t) = script_now() else { return 0 }; static AT: OnceLock> = OnceLock::new(); let at = AT.get_or_init(|| { let var = |n: &str| std::env::var(n).unwrap_or_default(); parse_presses(&var("XCL_PRESS_AT"), &var("XCL_PRESS_A_AT")) }); - // seconds since the host started, as the log's times (not since the title first polled) - let t = crate::log::uptime(); - at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) + let timed = scheduled_buttons(at, t); + let rules = frame_rules().and_then(|r| r.lock().ok()).map_or(0, |mut r| { + let (buttons, event) = r.buttons(t); + if let Some(event) = event { log_input_rule(&event); } + buttons + }); + timed | rules +} + +fn log_input_rule(event: &super::input_rules::Event) { + if let Ok(json) = serde_json::to_string(event) { crate::xlog_info!("GameInput: input_rule {json}"); } +} + +/// Bounded local configuration/reference reads; no title files are written. +fn input_rule_file(path: &std::path::Path, max: u64) -> Result, String> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(max + 1).read_to_end(&mut bytes)).map_err(|e| format!("{}: {e}", path.display()))?; + if bytes.len() as u64 > max { return Err(format!("{} exceeds {max} bytes", path.display())); } + Ok(bytes) +} + +/// Read host paths before the title's VFS hooks can remap their drive letters. +pub(crate) fn init_frame_rules() { let _ = frame_rules(); } + +fn frame_rules() -> Option<&'static Mutex> { + static RULES: OnceLock>> = OnceLock::new(); + RULES.get_or_init(|| { + let path = std::path::PathBuf::from(std::env::var_os("XCL_INPUT_RULES")?); + let load = || { + if std::env::var_os("XCL_FRAME_DUMP").is_none() { return Err("XCL_INPUT_RULES needs XCL_FRAME_DUMP=2 (presented frames)".into()); } + let text = String::from_utf8(input_rule_file(&path, 64 << 10)?).map_err(|e| e.to_string())?; + super::input_rules::Engine::parse(&text, |reference| { + let reference = path.parent().unwrap_or_else(|| std::path::Path::new(".")).join(reference); + super::input_rules::thumbnail(&input_rule_file(&reference, 32 << 20)?) + }) + }; + match load() { + Ok((engine, warnings)) => { + for (name, error) in warnings { input_rule_warning(&name, &error); } + Some(Mutex::new(engine)) + } + Err(e) => { input_rule_warning("$config", &e); None } + } + }).as_ref() +} + +fn input_rule_warning(name: &str, error: &str) { + let json = serde_json::json!({"event":"disabled", "rule":name, "reason":error}); + crate::xlog_warn!("GameInput: input_rule {json}"); +} + +/// Only decoded, presented image dumps call this; intermediate render targets cannot trigger keys. +pub(crate) fn match_input_frame(bmp: &[u8], frame: u64) { + let Some(rules) = frame_rules() else { return }; + let Ok(image) = super::input_rules::thumbnail(bmp) else { return }; + if let Ok(mut r) = rules.lock() { + let Some(t) = script_now() else { return }; + if let Some(event) = r.frame(&image, frame, t) { log_input_rule(&event); } + } } #[link(name = "user32")] @@ -1201,6 +1278,56 @@ pub fn exports() -> Vec<(&'static str, usize)> { #[cfg(test)] mod tests { + #[test] + fn shader_preparation_does_not_consume_scripted_input_times() { + let schedule = parse_presses("6:A", "9"); + let guest_start = 300.0; + assert_eq!(script_seconds(None, 299.0), None); + let time = |host| script_seconds(Some(guest_start), host).unwrap(); + assert_eq!(scheduled_buttons(&schedule, time(305.9)), 0); + assert_eq!(scheduled_buttons(&schedule, time(306.1)), A); + assert_eq!(scheduled_buttons(&schedule, time(309.1)), A); + + use crate::hle::input_rules::{Engine, HEIGHT, WIDTH}; + let image = [0; WIDTH * HEIGHT]; + let config = "[fallback]\nbutton='A'\nstart=57\ninterval=3\n[[rules]]\nname='menu'\nreference='sample.bmp'\nregion=[0.0,0.0,1.0,1.0]\nthreshold=0\nsequence='DOWN, wait 2, A'"; + let (mut engine, _) = Engine::parse(config, |_| Ok(image)).unwrap(); + assert_eq!(engine.buttons(time(356.9)).0, 0); + assert_eq!(engine.buttons(time(357.1)).0, A); + assert!(engine.frame(&image, 1, time(357.5)).is_some()); + assert_eq!(engine.buttons(time(357.6)).0, DPAD_DOWN); + assert_eq!(engine.buttons(time(359.4)).0, 0); + assert_eq!(engine.buttons(time(359.6)).0, A); + } + + #[test] + fn reading_history_keeps_the_release_between_scripted_presses() { + use crate::hle::input_rules::{Engine, WIDTH, HEIGHT}; + let rule = "[[rules]]\nname='menu'\nreference='sample.bmp'\nregion=[0.0,0.0,1.0,1.0]\nthreshold=0\n"; + let image = [0; WIDTH * HEIGHT]; + let samples = |mut engine: Engine, before_match: Option, matched: u64, times: &[u64]| { + let mut history = ReadingHistory::new(); + let mut record = |engine: &mut Engine, ms: u64| { + let mut state = GamepadState::default(); + merge_host_inputs(&mut state, false, || 0, |_| {}, || engine.buttons(ms as f64 / 1000.0).0); + history.record(state, ms * 1000); + }; + if let Some(ms) = before_match { record(&mut engine, ms); } + assert!(engine.frame(&image, 1, matched as f64 / 1000.0).is_some()); + for &ms in times { record(&mut engine, ms); } + let first = history.readings.front().unwrap().clone(); + let now = times.last().unwrap() * 1000; + let up = history.adjacent::(first.0, now).unwrap(); + let second = history.adjacent::(up.0, now).unwrap(); + assert_eq!([first.reading().state.buttons, up.reading().state.buttons, second.reading().state.buttons], [A, 0, A]); + let release = if before_match.is_some() { times[0] } else { times[1] }; + assert_eq!(up.reading().timestamp, release * 1000); + }; + let (repeat, _) = Engine::parse(&format!("{rule}sequence='A, wait 0.3, A'"), |_| Ok(image)).unwrap(); + samples(repeat, None, 0, &[190, 200, 210, 310]); + let (handoff, _) = Engine::parse(&format!("[fallback]\nbutton='A'\nstart=57\ninterval=3\n{rule}sequence='A'"), |_| Ok(image)).unwrap(); + samples(handoff, Some(57050), 57100, &[57110, 57190, 57200, 57290, 57310]); + } use super::*; #[test] diff --git a/crates/xcl/src/hle/input_rules.rs b/crates/xcl/src/hle/input_rules.rs new file mode 100644 index 0000000000..8737928e26 --- /dev/null +++ b/crates/xcl/src/hle/input_rules.rs @@ -0,0 +1,321 @@ +//! Pure frame matching and virtual-button scheduling; references are supplied by the caller. + +pub(super) const WIDTH: usize = 64; +pub(super) const HEIGHT: usize = 36; +pub(super) type Thumbnail = [u8; WIDTH * HEIGHT]; + +use std::path::Path; +use serde::Deserialize; + +const HOLD: f64 = 0.2; +const RELEASE_GAP: f64 = 0.1; +fn yes() -> bool { true } +fn cooldown() -> f64 { 3.0 } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Config { #[serde(default)] rules: Vec, fallback: Option } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Spec { + name: String, reference: std::path::PathBuf, region: [f64; 4], threshold: f64, sequence: String, + #[serde(default = "yes")] once: bool, + #[serde(default = "cooldown")] cooldown: f64, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Fallback { button: String, start: f64, interval: f64 } +struct Rule { spec: Spec, reference: Thumbnail, presses: Vec<(f64, u32, String)>, end: f64, last: Option } +struct Playing { rule: usize, start: f64, frame: u64, pressed: Option } +pub(super) struct Engine { + rules: Vec, fallback: Option, fallback_press: Option, + playing: Option, claimed: bool, last_frame: Option, +} +#[derive(serde::Serialize)] +pub(super) struct Event { + pub event: &'static str, pub rule: String, pub frame: u64, pub t: f64, + #[serde(skip_serializing_if = "Option::is_none")] pub diff: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub button: Option, +} + +/// Only the uncompressed 24-bit BMPs written by present::write_frame are accepted. +pub(super) fn thumbnail(b: &[u8]) -> Result { + let bad = || "expected an intact, uncompressed 24-bit BMP".to_string(); + let word = |at| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes).ok_or_else(bad); + if b.get(..2) != Some(b"BM") || b.get(26..30) != Some(&[1, 0, 24, 0]) || word(30)? != 0 { return Err(bad()); } + let (off, dib, w, signed_h) = (word(10)? as usize, word(14)? as usize, word(18)? as i32, word(22)? as i32); + if dib < 40 || off < 14usize.checked_add(dib).ok_or_else(bad)? || w <= 0 || signed_h == 0 { return Err(bad()); } + let (w, h) = (w as usize, signed_h.checked_abs().ok_or_else(bad)? as usize); + let row = w.checked_mul(3).and_then(|n| n.checked_add(3)).ok_or_else(bad)? & !3; + if off.checked_add(row.checked_mul(h).ok_or_else(bad)?).is_none_or(|n| n > b.len()) { return Err(bad()); } + let mut out = [0; WIDTH * HEIGHT]; + for y in 0..HEIGHT { + let sy = y * h / HEIGHT; + let sy = if signed_h > 0 { h - 1 - sy } else { sy }; + for x in 0..WIDTH { + let at = off + sy * row + (x * w / WIDTH) * 3; + out[y * WIDTH + x] = ((11 * b[at] as u16 + 59 * b[at + 1] as u16 + 30 * b[at + 2] as u16) / 100) as u8; + } + } + Ok(out) +} + +fn valid_region(r: [f64; 4]) -> bool { + r.iter().all(|v| v.is_finite()) && r[0] >= 0.0 && r[1] >= 0.0 && r[2] > 0.0 && r[3] > 0.0 + && r[0] + r[2] <= 1.0 && r[1] + r[3] <= 1.0 + && ((r[0] + r[2]) * WIDTH as f64).round() > (r[0] * WIDTH as f64).round() + && ((r[1] + r[3]) * HEIGHT as f64).round() > (r[1] * HEIGHT as f64).round() +} +fn difference(a: &Thumbnail, b: &Thumbnail, r: [f64; 4]) -> f64 { + let (x0, y0) = ((r[0] * WIDTH as f64).round() as usize, (r[1] * HEIGHT as f64).round() as usize); + let (x1, y1) = (((r[0] + r[2]) * WIDTH as f64).round() as usize, ((r[1] + r[3]) * HEIGHT as f64).round() as usize); + let sum: u32 = (y0..y1).flat_map(|y| (x0..x1).map(move |x| a[y * WIDTH + x].abs_diff(b[y * WIDTH + x]) as u32)).sum(); + sum as f64 / ((x1 - x0) * (y1 - y0)) as f64 +} +fn sequence(text: &str) -> Result<(Vec<(f64, u32, String)>, f64), String> { + let (mut presses, mut next, mut last) = (Vec::new(), 0.0, None); + for token in text.split(',').map(str::trim) { + if let Some(wait) = token.strip_prefix("wait ") { + let wait: f64 = wait.parse().map_err(|_| "bad wait seconds")?; + if !wait.is_finite() || !(HOLD..=600.0).contains(&wait) { return Err("wait must be 0.2..600 seconds".into()); } + next = last.take().unwrap_or(next) + wait; + } else { + let button = super::gameinput::button_named(token).ok_or_else(|| format!("unknown button {token:?}"))?; + // Repeated levels need a release interval; touching 200 ms pulses look like one hold. + if presses.last().is_some_and(|(at, previous, _)| *previous == button && next + 1e-9 < *at + HOLD + RELEASE_GAP) { + return Err("consecutive presses of the same button must start at least 0.3 seconds apart".into()); + } + presses.push((next, button, token.to_ascii_uppercase())); + last = Some(next); + next += 0.8; + } + if next > 3600.0 || presses.len() > 128 { return Err("sequence too long".into()); } + } + if presses.is_empty() { return Err("empty sequence".into()); } + Ok((presses, last.map_or(next, |t| t + HOLD))) +} + +impl Engine { + pub fn parse(text: &str, mut reference: impl FnMut(&Path) -> Result) -> Result<(Self, Vec<(String, String)>), String> { + let config: Config = toml::from_str(text).map_err(|e| e.to_string())?; + if config.rules.is_empty() || config.rules.len() > 32 { return Err("expected 1..32 rules".into()); } + if let Some(f) = &config.fallback { + if super::gameinput::button_named(&f.button).is_none() || !f.start.is_finite() || f.start < 0.0 + || !f.interval.is_finite() || f.interval <= HOLD { return Err("invalid fallback button/start/interval".into()); } + } + let (mut rules, mut warnings, mut names) = (Vec::new(), Vec::new(), std::collections::HashSet::new()); + for s in config.rules { + if s.name.is_empty() || s.name.len() > 128 || !names.insert(s.name.clone()) || !valid_region(s.region) + || !s.threshold.is_finite() || !(0.0..=255.0).contains(&s.threshold) || !s.cooldown.is_finite() || s.cooldown < HOLD { + return Err(format!("invalid or duplicate rule {:?}", s.name)); + } + let (presses, end) = sequence(&s.sequence).map_err(|e| format!("rule {:?}: {e}", s.name))?; + match reference(&s.reference) { + Ok(reference) => rules.push(Rule { spec: s, reference, presses, end, last: None }), + Err(e) => warnings.push((s.name, e)), + } + } + let fallback = if warnings.is_empty() { config.fallback } else { None }; + Ok((Self { rules, fallback, fallback_press: None, playing: None, claimed: false, last_frame: None }, warnings)) + } + pub fn frame(&mut self, image: &Thumbnail, frame: u64, t: f64) -> Option { + if !t.is_finite() || self.last_frame.is_some_and(|last| frame <= last) { return None; } + self.last_frame = Some(frame); + if self.playing.is_some() { return None; } + for (index, r) in self.rules.iter_mut().enumerate() { + if r.last.is_some_and(|last| r.spec.once || t - last < r.spec.cooldown) { continue; } + let diff = difference(image, &r.reference, r.spec.region); + if diff <= r.spec.threshold { + let mut start = t; + if let Some(f) = self.fallback.as_ref().filter(|f| !self.claimed && t >= f.start) { + let elapsed = t - f.start; + if elapsed % f.interval < HOLD && super::gameinput::button_named(&f.button) == Some(r.presses[0].1) { + let released = f.start + (elapsed / f.interval).floor() * f.interval + HOLD + RELEASE_GAP; + start = start.max(released - r.presses[0].0); + } + } + r.last = Some(t); + self.claimed = true; + self.playing = Some(Playing { rule: index, start, frame, pressed: None }); + return Some(Event { event: "matched", rule: r.spec.name.clone(), frame, t, diff: Some(diff), button: None }); + } + } + None + } + pub fn buttons(&mut self, t: f64) -> (u32, Option) { + if !t.is_finite() { return (0, None); } + if let Some(p) = &mut self.playing { + let r = &self.rules[p.rule]; + let elapsed = t - p.start; + let event = |event, button| Event { event, rule: r.spec.name.clone(), frame: p.frame, t, diff: None, button }; + if elapsed >= r.end { + let e = event("completed", None); + self.playing = None; + return (0, Some(e)); + } + if let Some((i, (_, button, name))) = r.presses.iter().enumerate().find(|(_, (at, _, _))| elapsed >= *at && elapsed < *at + HOLD) { + let e = (p.pressed != Some(i)).then(|| event("pressed", Some(name.clone()))); + p.pressed = Some(i); + return (*button, e); + } + return (0, None); + } + if let Some(f) = self.fallback.as_ref().filter(|f| !self.claimed && t >= f.start) { + let elapsed = t - f.start; + if elapsed % f.interval < HOLD { + let n = (elapsed / f.interval).floor() as u64; + let e = (self.fallback_press != Some(n)).then(|| Event { event: "pressed", rule: "$fallback".into(), frame: self.last_frame.unwrap_or(0), t, diff: None, button: Some(f.button.clone()) }); + self.fallback_press = Some(n); + return (super::gameinput::button_named(&f.button).unwrap_or(0), e); + } + } + (0, None) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + const RULE: &str = "[[rules]]\nname='menu'\nreference='local.bmp'\nregion=[0.0,0.0,0.5,0.5]\nthreshold=5\nsequence='DOWN, wait 5, A'\n"; + fn engine(text: &str) -> Engine { Engine::parse(text, |_| Ok([0; WIDTH * HEIGHT])).unwrap().0 } + fn bmp(top_down: bool) -> Vec { + let mut b = vec![0; 70]; + b[..2].copy_from_slice(b"BM"); + for (at, v) in [(10, 54u32), (14, 40), (18, 2), (22, if top_down { (-2i32) as u32 } else { 2 })] { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + } + b[26..28].copy_from_slice(&1u16.to_le_bytes()); + b[28..30].copy_from_slice(&24u16.to_le_bytes()); + let (top, bottom) = if top_down { (54, 62) } else { (62, 54) }; + b[top..top + 6].fill(30); + b[bottom..bottom + 6].fill(210); + b + } + #[test] + fn synthetic_bmp_orientation_padding_and_bad_headers() { + let t = thumbnail(&bmp(false)).unwrap(); + assert_eq!(t, thumbnail(&bmp(true)).unwrap()); + assert_eq!((t[0], t[WIDTH * HEIGHT - 1]), (30, 210)); + assert!(thumbnail(&bmp(false)[..60]).is_err()); + let mut b = bmp(false); b[30] = 1; + assert!(thumbnail(&b).is_err(), "compressed BMP cannot trigger input"); + b[30] = 0; b[10] = 0; + assert!(thumbnail(&b).is_err(), "pixel data cannot overlap the header"); + } + #[test] + fn identical_different_and_region_limited_frames() { + let a = [0; WIDTH * HEIGHT]; let mut b = a; + assert_eq!(difference(&a, &b, [0.0, 0.0, 0.5, 0.5]), 0.0); + b[WIDTH * HEIGHT - 1] = 255; + assert_eq!(difference(&a, &b, [0.0, 0.0, 0.5, 0.5]), 0.0); + b.fill(30); + assert_eq!(difference(&a, &b, [0.0, 0.0, 0.5, 0.5]), 30.0); + } + #[test] + fn parser_rejects_unknown_fields_bad_regions_times_and_buttons() { + for bad in [RULE.replace("threshold=5", "threshold=nan"), RULE.replace("0.5,0.5", "1.1,0.5"), + RULE.replace("DOWN, wait 5, A", "NOPE"), RULE.replace("wait 5", "wait -1"), + format!("{RULE}typo=true\n"), format!("{RULE}{RULE}")] { + assert!(Engine::parse(&bad, |_| Ok([0; WIDTH * HEIGHT])).is_err(), "{bad}"); + } + } + #[test] + fn touching_same_button_pulses_are_rejected_or_have_a_release() { + let text = RULE.replace("DOWN, wait 5, A", "A, wait 0.2, A"); + // Rejection is valid; accepting this sequence must never merge the two pulses. + if let Ok((mut e, _)) = Engine::parse(&text, |_| Ok([0; WIDTH * HEIGHT])) { + e.frame(&[0; WIDTH * HEIGHT], 1, 0.0).unwrap(); + assert_eq!(e.buttons(0.19).0, super::super::gameinput::A); + assert_eq!(e.buttons(0.20).0, 0, "the title needs a button-up between repeated presses"); + assert_eq!(e.buttons(0.21).0, 0); + } + } + #[test] + fn repeated_button_parser_requires_a_release_margin() { + for text in ["A, wait 0.2, A", "A, wait 0.299, a", "A, wait 0.2, A, DOWN"] { + let error = sequence(text).unwrap_err(); + assert!(error.contains("0.3"), "{error}"); + } + assert!(sequence("A, wait 0.3, a").is_ok()); + assert!(sequence("A, A").is_ok()); + assert!(sequence("A, wait 0.2, DOWN").is_ok()); + } + #[test] + fn spaced_repeated_buttons_expose_button_up_at_the_boundary() { + let mut e = engine(&RULE.replace("DOWN, wait 5, A", "A, wait 0.3, A")); + e.frame(&[0; WIDTH * HEIGHT], 1, 0.0).unwrap(); + assert_eq!(e.buttons(0.19).0, super::super::gameinput::A); + assert_eq!(e.buttons(0.20).0, 0); + assert_eq!(e.buttons(0.21).0, 0); + assert_eq!(e.buttons(0.30).0, super::super::gameinput::A); + } + #[test] + fn missing_reference_disables_rule_and_fallback_without_pressing() { + let text = format!("[fallback]\nbutton='A'\nstart=0\ninterval=3\n{RULE}"); + let (mut e, warnings) = Engine::parse(&text, |p| { assert_eq!(p, Path::new("local.bmp")); Err("missing".into()) }).unwrap(); + assert_eq!(warnings.len(), 1); + assert!(e.frame(&[0; WIDTH * HEIGHT], 1, 0.0).is_none()); + assert_eq!(e.buttons(0.0).0, 0); + } + #[test] + fn sequence_timing_once_and_fallback_handoff() { + let mut e = engine(&format!("[fallback]\nbutton='A'\nstart=57\ninterval=3\n{RULE}")); + assert_eq!(e.buttons(57.0).0, super::super::gameinput::A); + assert_eq!(e.buttons(57.3).0, 0); + assert_eq!(e.frame(&[0; WIDTH * HEIGHT], 20, 58.0).unwrap().event, "matched"); + assert_eq!(e.buttons(58.0).0, super::super::gameinput::DPAD_DOWN); + assert_eq!(e.buttons(58.3).0, 0); + assert_eq!(e.buttons(60.0).0, 0, "fallback stopped before the sequence"); + assert_eq!(e.buttons(63.0).0, super::super::gameinput::A); + assert_eq!(e.buttons(63.3).1.unwrap().event, "completed"); + assert!(e.frame(&[0; WIDTH * HEIGHT], 21, 64.0).is_none(), "once"); + + let same = RULE.replace("DOWN, wait 5, A", "A"); + let mut e = engine(&format!("[fallback]\nbutton='A'\nstart=57\ninterval=3\n{same}")); + assert_eq!(e.buttons(57.05).0, super::super::gameinput::A); + assert_eq!(e.frame(&[0; WIDTH * HEIGHT], 20, 57.10).unwrap().event, "matched"); + for t in [57.11, 57.19, 57.20, 57.29] { + let (buttons, event) = e.buttons(t); + assert_eq!(buttons, 0, "fallback-to-rule A needs a release interval at {t}"); + assert!(event.is_none(), "the delayed rule press has not started"); + } + let (buttons, event) = e.buttons(57.31); + assert_eq!(buttons, super::super::gameinput::A); + assert_eq!(event.unwrap().rule, "menu"); + assert_eq!(e.buttons(57.51).1.unwrap().event, "completed"); + + let mut e = engine(&format!("[fallback]\nbutton='A'\nstart=57\ninterval=3\n{RULE}")); + assert_eq!(e.buttons(57.05).0, super::super::gameinput::A); + e.frame(&[0; WIDTH * HEIGHT], 20, 57.10).unwrap(); + assert_eq!(e.buttons(57.11).0, super::super::gameinput::DPAD_DOWN, "different button starts immediately"); + } + #[test] + fn repeated_rules_need_a_new_frame_cooldown_and_no_active_sequence() { + let text = RULE.replace("sequence='DOWN, wait 5, A'", "sequence='A'\nonce=false\ncooldown=3"); + let mut e = engine(&text); + assert!(e.frame(&[0; WIDTH * HEIGHT], 5, 0.0).is_some()); + assert!(e.frame(&[0; WIDTH * HEIGHT], 6, 0.1).is_none()); + e.buttons(0.3); + assert!(e.frame(&[0; WIDTH * HEIGHT], 7, 2.9).is_none()); + assert!(e.frame(&[0; WIDTH * HEIGHT], 7, 3.1).is_none(), "same sampled frame"); + assert!(e.frame(&[0; WIDTH * HEIGHT], 8, 3.1).is_some()); + } + #[test] + fn multi_step_sequence_and_events_are_json() { + let mut e = engine(&RULE.replace("DOWN, wait 5, A", "DOWN, wait 5, DOWN, A, wait 1.8, A, DOWN, A, DOWN, A")); + assert!(e.frame(&[20; WIDTH * HEIGHT], 1, 57.0).is_none(), "different screen"); + let event = e.frame(&[0; WIDTH * HEIGHT], 2, 58.0).unwrap(); + let json: serde_json::Value = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap(); + assert_eq!(json["event"], "matched"); + assert_eq!(json["rule"], "menu"); + assert_eq!(e.buttons(58.0).1.unwrap().event, "pressed"); + assert!(e.buttons(58.1).1.is_none(), "one event per pulse"); + for (t, button) in [(63.0, "DOWN"), (63.8, "A"), (65.6, "A"), (66.4, "DOWN"), + (67.2, "A"), (68.0, "DOWN"), (68.8, "A")] { + assert_eq!(e.buttons(t + 0.01).1.unwrap().button.as_deref(), Some(button)); + } + assert_eq!(e.buttons(69.1).1.unwrap().event, "completed"); + assert_eq!(e.buttons(72.0).0, 0, "fallback stays stopped"); + } +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index abea3ae4ee..95e5d6d505 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -18,6 +18,7 @@ pub mod d3d12x; pub mod dstorage; pub mod dxcompiler; pub mod gameinput; +mod input_rules; pub mod kbm; pub mod kernelx; pub mod mfplat; diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index a9412c658c..4bc6217b73 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -36,6 +36,8 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + // Load host files before the title's VFS remaps console drive letters. + crate::hle::gameinput::init_frame_rules(); if let Err(e) = crate::hle::d3d12x::present::preparation::before_guest(&boot) { crate::xlog_error!("Shader preparation: {e}"); eprintln!("xcl: {e}"); @@ -156,6 +158,7 @@ pub fn host_main(boot_path: &Path) -> i32 { }; unsafe { crate::hle::kernelx::adopt_title_hooks(&main) }; crate::report::write_final(None); + crate::hle::gameinput::start_script_clock(); let code = crate::loader::run_main(&main); crate::xlog_info!("game entry point returned code {code}"); crate::report::write_final(None); diff --git a/examples/retail-input-rules.toml b/examples/retail-input-rules.toml new file mode 100644 index 0000000000..4a9761fa67 --- /dev/null +++ b/examples/retail-input-rules.toml @@ -0,0 +1,21 @@ +# Capture your own Legal Notices frame with Copyright selected. No image ships here. +# All reference paths are relative to this file. References remain local. +# Before this rule, use XCL_PRESS_AT for A at 6,9,...,54 seconds only. +[fallback] +button = "A" +start = 57.0 +interval = 3.0 + +[[rules]] +name = "legal-notices" +reference = "references/legal-notices.bmp" +# Top-left 27x14 of the 64x36 grey thumbnail (normalised x,y,width,height). +region = [0.0, 0.0, 0.421875, 0.3888888888888889] +threshold = 5.0 +once = true +cooldown = 3.0 +# DOWN selects the warning; wait before moving to Next. +# The Photosensitivity Next button is enabled about 5.3 s after the screen appears. +# The last five buttons accept privacy, terms of service and confirmation. +# The terms screen needs about 2-3 seconds after the warning before it takes input. +sequence = "DOWN, wait 6.5, DOWN, A, wait 3, A, DOWN, A, DOWN, A"