WIP: feat(mods): a randomizer example mod, OoT Randomizer 9.1's logic and settings, seeds placed through the Modding API #1959
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!1959
Loading…
Reference in a new issue
No description provided.
Delete branch "HumanBean/Longshot:feat/randomizer"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
A randomizer for Longshot as an example mod (
modapi/examples/randomizer), built on the Modding API in #1958 and opened against itsmod-apibranch. Its generator follows OoT Randomizer 9.1 (logic, settings, presets, tricks, assumed fill, a solver that proves each seed beatable, hints by OoTR's distributions, spoiler log or race mode, hash icons); OoTR's tables are read as data (OoTR is MIT at its top level; its notice is insrc/data/LICENSE-OoTR.txt), the engine is the mod's own. In the game today it shuffles the chests and drops it can bind to OoTR locations at run time (no table of the game's ids is committed); the rest waits on API additions being built on this branch: rewards for songs, gifts, shops, scrubs, cows and tokens; settings in the content stage (gossip-stone hints); world state; age and spawn; dungeon items and doors; items.remove; cutscene skips; new items; entrances.Core addition:
content.read.placements(map), a map's placements read from the player's own game.Read first: the mod's README (players, racers, the parity table, the API gaps, where every table came from),
src/gen/,src/game/bind.ts.Testing
Tested: not in the game yet. In the fake game: 54 seeds over 9 presets and both modes, each beatable, settings and exclusions kept, hints true; the same seed text gives the same seed.
Still to test:
bound N of Mline, a bound chest giving the seed's item, starting items once, the time to make a seed in the game (by hand)Measurements
TODO: the time to make a seed in the game's QuickJS, and the main thread's cost per frame while the mod runs.
Risks
An example mod: nothing changes for a player who doesn't add it.
content.read.placementsreads a map's files only when a mod asks.Checklist
Ready for review
main; the title is a Conventional Commit. (On #1958'smod-api.)mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
Assisted-by:/Co-Authored-By:trailers.Ready to merge
🤖 Generated with Claude Code
https://claude.ai/code/session_017vw8e3nBDxBnhodLguFyEt
longshot/content's read.placements(map, { param }) answers the actors placed in one of the game's maps, from its Banc/<folder>/<map>_Dynamic and _Static files as the RomFS layers serve them: each { id, actor, layer, position, params }, the id being the placement id items.checked names a check by and rules.rewards takes. A randomizer or a tracker then learns the game's checks at run time from the player's game, with no table of ids (game data) in the mod. host/mod_read.c mod_read_placements_json (bounded BYML reading, 8 MiB at most), host/modapi/content_read.c's reader thread (the Banc folders listed once; each call reads the files again), the schema (content.read.toml, PlacementsOptions) and the generated files, services.c's feature, the fake game's contentData({ placements }). Tests: tests/test_mod_content.py (the reader over made-up files, both byte orders, the filter, refusals), tests/test_modrt.py check_content_read (the call in the real runtime). API version stays 37. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017vw8e3nBDxBnhodLguFyEtPossibly related, for context:
Recommendation: Request changes. The randomizer cannot load from a clean checkout because its generator is missing. The placements reader can report failed reads as successful, and the mod can change a save with rewards that differ from the seed it verified.
The placements API would let mods discover checks from the player's own game at runtime. The randomizer is a useful first client, but it needs a complete generator, proof that the game delivers what the solver verifies, and save-safe activation. The API also needs bounded delivery and reliable error reporting.
Does it help: Unproven. The PR reports 54 fake-game seeds across nine presets and two modes, without a run commit or results. The reported sweep cannot be reproduced from this head because its generator imports are missing. There is no in-game result, seed generation time, or frame-time comparison.
Other systems: Other content readers share the same queue and now scan Banc on their first row or text read. Placements also exercise shared RomFS and zstd code, and large answers are parsed on the game thread before the settlement budget is checked again. Rewards and grants affect save slots and other mods using the reward claim. The diff has no renderer, VRAM, audio or input changes. Evidence on Windows, Linux and Steam Deck is missing.
Switches: No RX_, HOS_ or LONGSHOT_ switches. The example adds 30 Mods-tab settings. Seed defaults to empty, preset to S9 Tournament, shuffle to game mode, and race to off. Logic, guarantee, bridge, Ganon's boss key, forest, Door of Time, fountain, fortress, Kakariko gate, small keys, boss keys, maps and compasses, Kokiri Sword, songs, tokens, freestanding items, shops, scrubs, cows, item pool, starting age, hint distribution and hint text default to Preset. Both count overrides default to 0 for Preset, trials to −1 for Preset, tricks, exclusions and starting items to 'preset', and custom settings to '{}'. Show hash and show hints default to on. The empty seed and spoiler-only choices need to honor their stated effects. Count controls should use the selected condition's supported range.
Reviewed:
7117cab56cagainstfa574bf340: Read the repository AGENTS.md, CONTRIBUTING.md, standards and Forgejo template, the five commits, all authored changes, and the placements reader and its BYML helpers in full. Read the relevant caller and dependency sections in RomFS, zstd, the runtime, rewards, items, storage, workers, and the test harnesses. Skimmed generated bindings and docs, and sampled the generated OoTR tables against the importer. The upstream OoTR source, Tooling checkout, and docs/review-checklist.md were unavailable. The advertised src/gen directory is absent at HEAD. No comments, reviews or recorded runs were supplied.; nothing run (a code review).Checked and fine:
Blocking (to change before merge)
Waiting on the author (a run, a measurement or a decision; no edit does it)
Testing: Read-only review. git diff --check passed. No build, script or test was run. The reported fake-game sweep and its game-mode assumptions could not be verified at this head. There are no in-game runs, CI results or measurements in the supplied record.
Overlaps and merge order: Depends on Longshot #1958. Land the Modding API first, then update this PR against the merged base and rerun the checks. No other overlap was established from the checkout.
Automated code review by BeanBot (gpt-6.2-sol), on the pull request's opening. Nothing was run; a maintainer decides.
@ -399,0 +443,4 @@else continue;const int has_dynamic = dict_get(&x, a, "Dynamic", &dt, &dv) && dt == 0xC1;if (param && !(has_dynamic && dict_get(&x, dv, param, &t, &tv))) continue;char head[64];Validate three finite numeric coordinates before promising a numeric triple. Also exclude zero hashes, which rewards.add refuses.
@ -110,6 +110,7 @@ static void list_names(void) {if (!hos_romfs_dir) return;list_dir("RSDB", ".rstbl.byml.zs", tables, &ntables);list_dir("Mals", ".sarc.zs", archives, &narchives);list_dir("Banc", "", bancs, &nbancs); /* (the maps' folders: Banc/KokiriForest, Banc/DreamWorld...; "." and ".." too) */Discover Banc files in the merged namespace. The first 64 base entries can omit valid maps, and row and text reads now pay for this scan.
@ -234,0 +243,4 @@if (!strcmp(base, ".") || !strcmp(base, "..")) continue;char rel[300], path[1100];snprintf(rel, sizeof rel, "%.150s/%.63s_%s.bcett.byml.zs", bancs[b], j->key, layers[l]);if (!hos_romfs_resolve(rel, path, sizeof path)) {The reader and game threads can resolve the same layered path concurrently. Synchronize RomfsPath.logged.
@ -234,0 +244,4 @@char rel[300], path[1100];snprintf(rel, sizeof rel, "%.150s/%.63s_%s.bcett.byml.zs", bancs[b], j->key, layers[l]);if (!hos_romfs_resolve(rel, path, sizeof path)) {snprintf(path, sizeof path, "%s/%s", hos_romfs_dir ? hos_romfs_dir : ".", rel);Check path construction and the dictionary read for deep UTF-8 roots. Truncation currently looks like a missing map.
@ -234,0 +250,4 @@fclose(f);}size_t n = 0;uint8_t *data = hos_zs_read(path, &n, MODREAD_FILE);The zstd dictionary initializer must finish before concurrent readers traverse its table.
@ -234,0 +253,4 @@uint8_t *data = hos_zs_read(path, &n, MODREAD_FILE);files++;if (!data || mod_read_placements_json(data, n, names[l], j->file[0] ? j->file : NULL, &json, &len, &count, &why) < 0)hos_log_at(MODRT_LOG_WARN, "mods: content.read: %s: %s", rel, data ? why : "it cannot be read or decompressed");Reject a failed layer and discard the accumulated JSON. Logging and continuing can return partial or invalid data.
@ -234,0 +271,4 @@}free(json);hos_log_at(MODRT_LOG_INFO, "mods: content.read: map %s: %d placements", j->key, count);settle_json(j->promise, out, out ? len + 2 : 0);Bound pending bytes and page large results. A single answer is parsed on the game thread before the settlement budget is checked again.
@ -0,0 +129,4 @@for (const kind of [...kinds].sort()) {const ls = (logical.get(kind) ?? []).slice().sort((a, b) => (a.name < b.name ? -1 : 1));const ps = (physical.get(kind) ?? []).slice().sort((a, b) => (a.p.id < b.p.id ? -1 : 1));const bound = ls.length > 0 && ls.length === ps.length;Equal counts can pair an incidental drop with a missing chest. Require evidence that each physical placement is the persistent check the solver models.
@ -0,0 +28,4 @@import { inputOf } from "./game/input.js";import { ALL_MAPS, type Binding, type DropLocation, type Placed } from "./game/bind.js";import { ITEM_ACTORS, progressive, tierActor } from "./game/names.js";import { plain } from "./gen/hints.js";HEAD is missing every src/gen module. The root gen/ ignore rule matches this path. Commit the generator under a tracked directory.
@ -0,0 +50,4 @@// ---- 1 to 3: read the game's checks, bind them, make the seed ----const worker = start("src/worker.ts");Defer the worker and gameplay work until a seed is configured. Release the worker after completion or failure.
@ -0,0 +83,4 @@return;}const placements: Record<string, Placed[] | null> = {};const answers = await Promise.all(ALL_MAPS.map((map) => read.placements(map, { param: "Drop__DropActor" }).catch(() => null)));Read and send compact batches within the worker limit. Propagate read errors instead of counting them as absent maps.
@ -0,0 +100,4 @@log.info(`bound ${view.bound} of ${view.locations} OoTR drop locations to the game's placements (${b.groups.length} groups)`);const unbound = b.report.filter((r) => !r.bound && r.locations && r.placements);if (unbound.length) log.debug(`counts that differ (not bound): ${unbound.map((r) => `${r.group} ${r.kind} ${r.locations}/${r.placements}`).join(", ")}`);input.available = Object.keys(b.placement);Include the physical binding in the race fingerprint. The same logical names and groups can map to different chests.
@ -0,0 +125,4 @@function rewardFor(location: string, item: string): void {const id = binding?.placement[location];if (!id) return;const learned = new Map(Object.entries(binding!.learned));Two progressive chests in a loaded room can both give the same tier. Resolve at collection or leave those rewards vanilla.
@ -0,0 +127,4 @@if (!id) return;const learned = new Map(Object.entries(binding!.learned));const actor = tierActor(item, progressive(item) ? tiersHeld(item) : 0, learned);if (!actor) { log.debug(`${location}: ${item} has no name in the game; its chest keeps its own`); return; }Validate item delivery before accepting the seed. A silently skipped reward or grant invalidates the solver's result.
@ -0,0 +142,4 @@view.warnings.push(...s.warnings, ...s.adjusted.map((a) => `${a.setting}: ${JSON.stringify(a.to)} (${a.why})`));for (const [loc, id] of Object.entries(binding?.placement ?? {})) placementOf.set(id, loc);for (const p of s.placements) itemAt.set(p.location, p.item);const shuffled = s.placements.filter((p) => p.kind === "shuffled" && binding?.placement[p.location]);Full mode is labeled spoiler-only. Skip all rewards and starting grants in that mode.
@ -0,0 +145,4 @@const shuffled = s.placements.filter((p) => p.kind === "shuffled" && binding?.placement[p.location]);for (let i = 0; i < shuffled.length; i += 32) {const batch = shuffled.slice(i, i + 32);work.push(() => { for (const p of batch) rewardFor(p.location, p.item); view.rewards = rules.size; });Keep play gated until the complete reward set is installed. Roll back the rules if any addition fails.
@ -0,0 +182,4 @@if (slot === null || state().mode !== "play") return;const mine = save.get("seed") as string | null;if (mine && mine !== seed.digest) {view.warnings.push("this save was started with another seed: its items are that seed's");Check save compatibility before installing rewards. The warning currently leaves the other seed's rules active.
@ -0,0 +171,4 @@};parts.forEach((p, i) => work.push(set(`${key}/${i}`, p)));work.push(set(`${key}/parts`, parts.length));work.push(set("spoiler/last", key));Publish spoiler/last only after every part succeeds. A quota failure currently leaves a broken log advertised as complete.
@ -0,0 +191,4 @@for (let i = 0; i < count; i++) {const actor = tierActor(item, i);if (!actor) continue;grant(actor, { key: `start:${seed.digest.slice(0, 16)}:${slot}:${item}:${i}` });A slot number can be reused, and queued grants can follow a slot switch. Scope delivery and deduplication to the playthrough.
@ -0,0 +202,4 @@let started = false;update.on(() => {for (let i = 0; i < 2 && work.length; i++) work.shift()!();if (!started && seed && state().mode === "play") { started = true; startPlaythrough(); }The start latch can be set before a fresh game has a slot. Keep attempting initialization until the active playthrough can receive its kit.
@ -0,0 +211,4 @@checked.on((e) => {if (!seed || e.resets) return;const loc = placementOf.get(e.id);if (!loc || checkedIds.has(e.id)) return;Rebuild checked IDs and reward tiers when a save loads. Reloading before a check must make it eligible again.
@ -0,0 +240,4 @@const stones = list({ near: { position: me, within: 4 }, nearest: true, limit: 16 }).filter((a) => /Gossip/i.test(a.type));if (!stones.length) return;// (the map's stones in the order of their positions; each shows one of the seed's hints, the same one every time)const all = list({ near: { position: me, within: 300 } }).filter((a) => /Gossip/i.test(a.type) && a.position)Key hints by stable stone ID and clear the displayed hint when disabled or changing maps.
@ -0,0 +47,4 @@assert.ok(item, "the spoiler names the sword chest's item");// (S9 Tournament shuffles the Kokiri Sword: the chest drops the seed's item, as the game's actor of it)const actor = ITEM_ACTORS[item.replace(/ \(\d+ rupees\)$/, "")]?.[0];if (actor) assert.equal(game.dropFor(SWORD, "Weapon_Sword_Kokiri"), actor, `${item} as ${actor}`);Assert a known reward unconditionally and let spoiler work finish before asserting that race mode wrote nothing.
@ -0,0 +85,4 @@"in the game: the maps bind, the seed is made and its rewards set": { game: true, timeout: 36000, run: async (game, assert) => {await game.loadSave("kokiri-start");await game.frames(60);if (!game.logs.some((l) => l.text.startsWith("bound ") || l.text.includes("reading")) && !game.logs.some((l) => l.text.startsWith("seed ")))Detect the seed setting directly. Slow binding or startup failure should fail the game test. Check an actual chest's delivered item.
@ -903,0 +922,4 @@const list = this.placed[map];if (!list)return null;void outputs;Apply content.place outputs in the fake game and use own-key map lookup.
@ -3471,6 +3474,11 @@ def check_content_read(exe, tmp, c):fr = {"ActorMsg/Enemy.msbt": mc.msbt([("Enemy_Octorok_Name", "Octorok rouge")])}(rom / "Mals" / "USen.Product.1.sarc.zs").write_bytes(mc.arch.sarc(en))(rom / "Mals" / "EUfr.Product.1.sarc.zs").write_bytes(mc.arch.sarc(fr))(rom / "Banc" / "KokiriForest").mkdir(parents=True)Cover the real compressed and merged path, including the Windows UTF-8 directory lookup, with a portable harness that honors CC.
7117cab56c7193c397857193c397850e191c62490e191c6249d4c0763424d4c07634244cfda780a54cfda780a5c577a2ff9bc577a2ff9b4eb8a526384eb8a526385eda12542cab66188a3a5e431939575e43193957f0cc576c76View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.