Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 204 additions & 0 deletions d3d12/crates/leonida-lua/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,3 +1030,207 @@ fn the_example_mod_ships_disabled_and_runs_when_enabled() {
assert!(log.iter().any(|l| l == "the F4 menu was opened"), "{log:?}");
assert_eq!(status(&rt, "Example Lua mod"), Status::Running);
}

/// Runs `mods/gate_driver`'s logic (driver.lua) on a stub: a simulated clock of 0.1 s steps and 3 frames a
/// step, a player whose position is known from `ready_at` and who walks only while W is held.
const GATE_HARNESS: &str = r#"
local driver = require("driver")
function run(config, seconds, ready_at, moves, jump_until)
local t, f, held, pos = 0, 0, {}, { 0, 0, 0 }
local d = driver.new({
time = function() return t end,
frame = function() return f end,
position = function()
if t >= ready_at then return pos[1], pos[2], pos[3] end
return nil, "not yet"
end,
hold = function(list) held = {} for _, k in ipairs(list) do held[k] = true end end,
release = function() held = {} end,
shot = function() return "shot.png" end,
log = function(...) leonida.log(...) end,
}, config)
while t < seconds and d.state ~= "done" do
t = t + 0.1
f = f + 3
if moves and held.W and t >= ready_at then pos[1] = pos[1] + 0.5 end
-- Until then the title moves the player itself, far, as a load or a cutscene does.
if jump_until and t < jump_until and t >= ready_at then pos[2] = pos[2] + 100 end
d:step()
end
leonida.log("END", d.state)
end
"#;

fn gate_driver_logs(scenario: &str) -> Vec<String> {
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../mods/gate_driver");
let dir = tempfile::tempdir().unwrap();
let at = dir.path().join("gate_test");
std::fs::create_dir_all(&at).unwrap();
std::fs::copy(source.join("driver.lua"), at.join("driver.lua")).unwrap();
std::fs::write(
at.join("mod.json"),
r#"{"name": "Gate test", "script": "main.lua"}"#,
)
.unwrap();
std::fs::write(at.join("main.lua"), format!("{GATE_HARNESS}\n{scenario}\n")).unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let report = rt.load_dir(dir.path());
assert_eq!(
report,
[("Gate test".to_owned(), Status::Running)],
"{:?}",
fake.logs()
);
fake.of("Gate test")
}

fn seconds_of(line: &str) -> f64 {
line.split_whitespace()
.find_map(|w| w.strip_prefix("t="))
.unwrap()
.parse()
.unwrap()
}

#[test]
fn the_gate_driver_presses_through_the_menus_then_stands_still() {
let log = gate_driver_logs(r#"run({ mode = "idle" }, 400, 120, true)"#);
let presses: Vec<&String> = log.iter().filter(|l| l.starts_with("GATE PRESS")).collect();
let control = log
.iter()
.position(|l| l.starts_with("GATE CONTROL"))
.expect("no control");
assert!((3..=6).contains(&presses.len()), "{log:?}");
// Not before frames come (600 frames and 20 s), then one every 25 s, none once in control.
assert!(seconds_of(presses[0]) >= 20.0, "{log:?}");
assert!(
log[control..].iter().all(|l| !l.starts_with("GATE PRESS")),
"{log:?}"
);
assert!(log[control].ends_with("mode=idle"), "{log:?}");
assert!(
log.iter().filter(|l| l.starts_with("GATE MARK")).count() >= 20,
"{log:?}"
);
assert_eq!(
log.iter().filter(|l| l.starts_with("GATE SHOT")).count(),
2,
"{log:?}"
);
// Still: the marks stay at the place control was shown.
assert!(
log.iter()
.filter(|l| l.starts_with("GATE MARK"))
.all(|l| l.ends_with("from_control_m=0.0")),
"{log:?}"
);
assert_eq!(log.last().unwrap(), "END idle");
}

#[test]
fn the_gate_driver_roams_once_in_control() {
let log = gate_driver_logs(r#"run({ mode = "roam" }, 200, 50, true)"#);
assert!(
log.iter()
.any(|l| l.starts_with("GATE CONTROL") && l.ends_with("mode=roam")),
"{log:?}"
);
let last_mark = log
.iter()
.rev()
.find(|l| l.starts_with("GATE MARK"))
.unwrap();
let away: f64 = last_mark
.rsplit("from_control_m=")
.next()
.unwrap()
.parse()
.unwrap();
assert!(away > 10.0, "{log:?}");
}

#[test]
fn the_gate_driver_fails_without_a_position_or_without_control() {
let log = gate_driver_logs(r#"run({ give_up = 200 }, 400, 1e9, true)"#);
assert!(
log.iter().any(|l| l.starts_with("GATE FAIL no position")),
"{log:?}"
);
assert_eq!(log.last().unwrap(), "END done");
// The position comes but the player never moves: it keeps pressing, then gives up.
let log = gate_driver_logs(r#"run({ give_up = 200 }, 400, 50, false)"#);
assert!(
!log.iter().any(|l| l.starts_with("GATE CONTROL")),
"{log:?}"
);
assert!(
log.iter().any(|l| l.starts_with("GATE FAIL no control")),
"{log:?}"
);
// A probe that shows no move asks for a press at the menus' pace, not right away: one every 25 s.
let presses: Vec<f64> = log
.iter()
.filter(|l| l.starts_with("GATE PRESS"))
.map(|l| seconds_of(l))
.collect();
assert!(presses.len() <= 9, "{log:?}");
assert!(presses.windows(2).all(|w| w[1] - w[0] >= 24.9), "{log:?}");
}

#[test]
fn a_jump_of_the_player_is_not_control() {
// The title moves the player 1,000 m a second until t = 150 (a cutscene): no control before it stops.
let log = gate_driver_logs(r#"run({ mode = "idle" }, 300, 60, true, 150)"#);
let control = log
.iter()
.find(|l| l.starts_with("GATE CONTROL"))
.expect("no control");
assert!(seconds_of(control) >= 150.0, "{log:?}");
assert!(
log.iter()
.any(|l| l.starts_with("GATE PROBE") && l.ends_with("placed")),
"{log:?}"
);
// A jump is no screen waiting for Enter: no press once the position is known.
assert!(
log.iter()
.filter(|l| l.starts_with("GATE PRESS"))
.all(|l| seconds_of(l) < 60.0),
"{log:?}"
);
}

#[test]
fn the_gate_driver_ships_disabled_and_loads_when_enabled() {
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../mods/gate_driver");
let manifest = std::fs::read_to_string(source.join("mod.json")).unwrap();
assert!(
!crate::manifest::parse("gate_driver", &manifest)
.unwrap()
.enabled
);
let dir = tempfile::tempdir().unwrap();
let at = dir.path().join("gate_driver");
std::fs::create_dir_all(&at).unwrap();
std::fs::write(at.join("mod.json"), manifest.replace("false", "true")).unwrap();
for file in ["main.lua", "driver.lua"] {
std::fs::copy(source.join(file), at.join(file)).unwrap();
}
std::fs::write(
at.join("gate.txt"),
"mode = roam\ngive_up = 600\nnot_a_setting = 3\n",
)
.unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
assert_eq!(
rt.load_dir(dir.path()),
[("Gate driver".to_owned(), Status::Running)]
);
assert_eq!(fake.of("Gate driver"), ["GATE loaded mode=roam"]);
// Frames before any position: it waits, no failure.
pass(&mut rt, 1);
pass(&mut rt, 2);
assert_eq!(status(&rt, "Gate driver"), Status::Running);
}
33 changes: 33 additions & 0 deletions docs/lua-modding.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,39 @@ go on. A syntax error or a missing script is the same at load. A Rust panic in t
`"name"` (shown in logs). A folder without `"script"` (an asset mod, `docs/modding.md`) is not a Lua mod and is left
alone; a mod can have both. Load order is the folder names', sorted.

## The gate's driver mod

`mods/gate_driver` takes a run from the title's menus into the world with no person, for in-game gates and A/Bs. It
ships disabled: a run enables a copy of it in a mods folder of its own (`LEONIDA_MODS`). It needs
`LEONIDA_GAME_ACTIONS=1`, for `leonida.player_position()`.

- **The menus.** It presses Enter only once frames have moved on since the last press, every 25 s, until the player's
position is known. A start that takes minutes to compile pipelines does not throw its presses away.
- **Control.** Holding W for 3 s must move the player at least 1 m and at most 30 m. More is the title placing the
player itself (a load, a cutscene), not a walk: it tries again (`GATE PROBE ... placed`). Less is a screen that
still waits (`GATE PROBE ... still`): it presses once more, at the menus' pace, and tries again.
- **Limits.** In `idle`, a mark at 0.0 m does not tell a player standing still from one the title holds (a cutscene
can start after control and hold the player); `roam` shows it. With a cold pipeline cache the world can take
minutes, and the player can stay held: `GATE CONTROL` then comes late, or `GATE FAIL no control` at 900 s.
- **Then.** `idle` (the default) stands still, for measuring. `roam` walks a fixed loop: W, with short J and L turns
(the stand-in pad's right stick turns the camera).
- **Its log lines.** Through `leonida.log`, the log is also its heartbeat:
- `GATE PRESS`, and `GATE PROBE ... placed` or `still` when holding W showed no control;
- `GATE CONTROL t=... frame=... moved=... mode=...`;
- `GATE MARK t=... frame=... <mode> from_control_m=...`, every 10 s. A cutscene can still follow control: the
title moves the player for it, kilometres away, and puts them back after, to 0.0 again in `idle`;
- `GATE SHOT`, two screenshots at 10 s and 120 s after control (diagnostics builds), in `LEONIDA_SCREENSHOTS`
when set, else beside the runtime;
- `GATE FAIL no position` or `GATE FAIL no control`, after 900 s.

Distances only: never a position.
- **Its settings.** A `gate.txt` beside the copy sets `mode = roam` and any number of `driver.lua`'s defaults
(`give_up = 600`, ...), one a line.

The logic is in `driver.lua`, which takes the calls it uses as an argument. `crates/leonida-lua` tests it on a stub
with a simulated clock. A route of your own, a saved place to start from and the run's screenshots are game data:
keep them on your machine.

## What is not here, and why

- `leonida.teleport(x, y, z [, hold_seconds])` (true line, or nil and why) and `leonida.player_position()` (x, y, z) move
Expand Down
140 changes: 140 additions & 0 deletions mods/gate_driver/driver.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
-- The gate's driver (docs/lua-modding.md): from the title's menus into the world with no person, then still or
-- walking a looped course. It only uses what it is given (`api`), so a test can run it with a stub.
--
-- States: boot (frames must be coming) -> menus (Enter now and then, only once frames have moved on since the last
-- press, until the player's position is known) -> probe (W held: the player must move) -> idle or roam.
-- It writes, through api.log, "GATE PRESS", "GATE PROBE", "GATE CONTROL", "GATE MARK" every mark_every seconds,
-- "GATE SHOT" and "GATE FAIL <why>": distances only, never a position.

local M = {}

M.defaults = {
mode = "idle", -- "idle": stand still once in control (for measuring); "roam": walk the loop below
boot_frames = 600, -- frames presented before the first press
boot_seconds = 20,
press_every = 25, -- seconds between presses of Enter in the menus
press_seconds = 0.2,
give_up = 900, -- seconds with no control: GATE FAIL
probe_seconds = 3, -- W held to show control
probe_metres = 1.0, -- the least it must move
-- The most: more is not a walk but the title placing the player (a load, a cutscene), which shows no control.
probe_max_metres = 30,
mark_every = 10,
shots = { 10, 120 }, -- seconds after control (screenshots exist in diagnostics builds)
-- The roam loop: seconds, keys held. J and L turn the camera (the stand-in pad's right stick), W walks.
roam = { { 4, { "W" } }, { 0.4, { "W", "L" } }, { 4, { "W" } }, { 0.4, { "W", "J" } } },
}

function M.new(api, config)
local cfg = {}
for k, v in pairs(M.defaults) do cfg[k] = v end
for k, v in pairs(config or {}) do cfg[k] = v end
return setmetatable({ api = api, cfg = cfg, state = "boot", presses = 0, roam_step = 1, shots_done = 0 },
{ __index = M })
end

local function distance(a, b)
return math.sqrt((a[1] - b[1]) ^ 2 + (a[2] - b[2]) ^ 2 + (a[3] - b[3]) ^ 2)
end

function M:position()
local x, y, z = self.api.position()
if type(x) == "number" then return { x, y, z } end
return nil
end

function M:say(...)
self.api.log("GATE", ...)
end

function M:fail(why, now)
self.api.release()
self:say("FAIL", why, string.format("t=%.1f", now))
self.state = "done"
end

function M:press(now, frame)
self.api.hold({ "Enter" })
self.release_at = now + self.cfg.press_seconds
self.last_press, self.press_frame = now, frame
self.presses = self.presses + 1
self:say("PRESS", self.presses, string.format("t=%.1f", now), "frame=" .. frame)
end

function M:step()
local now, frame = self.api.time(), self.api.frame()
if self.state == "done" then return end
if self.release_at and now >= self.release_at then
self.api.release()
self.release_at = nil
end
local in_control = self.state == "idle" or self.state == "roam"
if not in_control and now >= self.cfg.give_up then
return self:fail(self:position() and "no control" or "no position", now)
end
if self.state == "boot" then
if frame >= self.cfg.boot_frames and now >= self.cfg.boot_seconds then self.state = "menus" end
elseif self.state == "menus" then
local may_press = not self.release_at and (self.press_frame == nil or frame >= self.press_frame + 3)
and (self.last_press == nil or now - self.last_press >= self.cfg.press_every)
if self:position() and not self.want_press then
-- Once Enter is up: a probe holding W would cut its press short.
if not self.release_at then self.state = "probe" end
elseif may_press then
self:press(now, frame)
self.want_press = false
end
elseif self.state == "probe" then
if not self.probe then
local at = self:position()
if not at then
self.state = "menus"
return
end
self.release_at = nil
self.api.hold({ "W" })
self.probe = { from = at, ends = now + self.cfg.probe_seconds }
return
end
if now < self.probe.ends then return end
self.api.release()
local at = self:position()
local moved = at and distance(at, self.probe.from) or 0
self.probe = nil
if moved >= self.cfg.probe_metres and moved <= self.cfg.probe_max_metres then
self.control_at, self.last_mark, self.home = now, now, at
self.state = self.cfg.mode == "roam" and "roam" or "idle"
self:say("CONTROL", string.format("t=%.1f", now), "frame=" .. frame, string.format("moved=%.2f", moved),
"mode=" .. self.state)
elseif moved > self.cfg.probe_max_metres then
-- The title placed the player itself (a load, a cutscene): no screen to press through, show control again.
self:say("PROBE", string.format("t=%.1f", now), string.format("moved=%.1f", moved), "placed")
else
-- A screen may still want a press: one, at the menus' pace (press_every, frames moving on), then show
-- control again.
self:say("PROBE", string.format("t=%.1f", now), string.format("moved=%.1f", moved), "still")
self.state, self.want_press = "menus", true
end
else
if self.state == "roam" and (self.roam_until == nil or now >= self.roam_until) then
local leg = self.cfg.roam[self.roam_step]
self.api.hold(leg[2])
self.roam_until = now + leg[1]
self.roam_step = self.roam_step % #self.cfg.roam + 1
end
local since = now - self.control_at
if self.shots_done < #self.cfg.shots and since >= self.cfg.shots[self.shots_done + 1] then
self.shots_done = self.shots_done + 1
local taken, why = self.api.shot()
self:say("SHOT", self.shots_done, taken and "taken" or ("not taken: " .. tostring(why)))
end
if now - self.last_mark >= self.cfg.mark_every then
self.last_mark = now
local at = self:position()
self:say("MARK", string.format("t=%.1f", now), "frame=" .. frame, self.state,
string.format("from_control_m=%.1f", at and distance(at, self.home) or -1))
end
end
end

return M
Loading