From 7305ec1d0f55ce7160cea84ba55c461671d41f71 Mon Sep 17 00:00:00 2001 From: Shaydera Date: Fri, 20 Nov 2026 19:36:47 +0100 Subject: [PATCH] Read Forever spell data from the Forever build The game data export also downloads the spell icons, channel spells and class spells of the newest Forever build. A Forever log reads these tables, every other game keeps the retail ones. --- crates/openlogs-cli/src/game_data.rs | 33 ++++++++- crates/openlogs-gamedata/src/download.rs | 60 +++++++++++++-- crates/openlogs-gamedata/src/lib.rs | 11 +-- crates/openlogs-gamedata/tests/download.rs | 78 ++++++++++++++++++++ crates/openlogs-gamedata/tests/online.rs | 20 ++++- crates/openlogs-wasm/src/engine.rs | 85 ++++++++++++++++++---- crates/openlogs-wasm/src/lib.rs | 12 +-- crates/openlogs-wasm/tests/engine.rs | 64 +++++++++++++++- ui/scripts/fetch-images.mjs | 4 +- ui/src/api/client.test.ts | 60 +++++++++++++++ ui/src/api/client.ts | 33 +++++---- ui/src/components/SettingsDialog.tsx | 2 +- ui/src/currentGame.ts | 9 ++- ui/src/engine/engine.ts | 9 ++- ui/src/engine/worker.ts | 8 +- ui/src/gameData.test.ts | 65 +++++++++++++++++ ui/src/gameData.ts | 72 +++++++++++++----- 17 files changed, 545 insertions(+), 80 deletions(-) create mode 100644 crates/openlogs-gamedata/tests/download.rs diff --git a/crates/openlogs-cli/src/game_data.rs b/crates/openlogs-cli/src/game_data.rs index 427362f..d97bc33 100644 --- a/crates/openlogs-cli/src/game_data.rs +++ b/crates/openlogs-cli/src/game_data.rs @@ -4,8 +4,8 @@ use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; use openlogs_gamedata::{ - HttpFetch, download_boss_portraits, download_dungeons, download_map_art, - download_spell_classes, download_spell_tables, + HttpFetch, download_boss_portraits, download_dungeons, download_forever_tables, + download_map_art, download_spell_classes, download_spell_tables, }; /// Downloads the game data from wago.tools into the files the app loads from `game-data/`. @@ -16,6 +16,7 @@ pub fn export(out_dir: &Path) -> Result<(), Box> { let dungeons = download_dungeons(&fetch)?; let portraits = download_boss_portraits(&fetch)?; let map_art = download_map_art(&fetch)?; + let forever = download_forever_tables(&fetch)?; let fetched_unix_ms = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(); fs::create_dir_all(out_dir)?; @@ -28,6 +29,20 @@ pub fn export(out_dir: &Path) -> Result<(), Box> { fs::write(out_dir.join("dungeons.json"), dungeons.to_json())?; fs::write(out_dir.join("boss-portraits.json"), portraits.to_json())?; fs::write(out_dir.join("map-art.json"), map_art.to_json())?; + let forever_dir = out_dir.join("forever"); + fs::create_dir_all(&forever_dir)?; + fs::write( + forever_dir.join("spell-icons.json"), + forever.spells.icons.to_json(), + )?; + fs::write( + forever_dir.join("channel-spells.json"), + forever.spells.channels.to_json(), + )?; + fs::write( + forever_dir.join("spell-classes.json"), + forever.classes.to_json(), + )?; // Written last: the app reads the tables only once the manifest names them. let manifest = serde_json::json!({ "fetchedUnixMs": fetched_unix_ms, @@ -37,6 +52,12 @@ pub fn export(out_dir: &Path) -> Result<(), Box> { "dungeons": dungeons.len(), "bossPortraits": portraits.len(), "mapArt": map_art.maps.len(), + "forever": { + "build": forever.build, + "spellIcons": forever.spells.icons.len(), + "channelSpells": forever.spells.channels.len(), + "spellClasses": forever.classes.class_spell_count(), + }, }); fs::write(out_dir.join("manifest.json"), manifest.to_string())?; println!( @@ -50,5 +71,13 @@ pub fn export(out_dir: &Path) -> Result<(), Box> { map_art.maps.len(), out_dir.display() ); + println!( + "Forever {}: {} spells, {} channel spells and {} class spells written to {}", + forever.build, + forever.spells.icons.len(), + forever.spells.channels.len(), + forever.classes.class_spell_count(), + forever_dir.display() + ); Ok(()) } diff --git a/crates/openlogs-gamedata/src/download.rs b/crates/openlogs-gamedata/src/download.rs index eb23598..3451194 100644 --- a/crates/openlogs-gamedata/src/download.rs +++ b/crates/openlogs-gamedata/src/download.rs @@ -21,6 +21,9 @@ pub const WAGO_UI_MAP_ASSIGNMENT_URL: &str = "https://wago.tools/db2/UiMapAssign pub const WAGO_UI_MAP_GROUP_MEMBER_URL: &str = "https://wago.tools/db2/UiMapGroupMember/csv"; pub const WAGO_AREA_TABLE_URL: &str = "https://wago.tools/db2/AreaTable/csv"; pub const WAGO_MAP_URL: &str = "https://wago.tools/db2/Map/csv"; +/// The newest build of each product, as `{ "": { "version": "…" }, … }`. +pub const WAGO_LATEST_BUILDS_URL: &str = "https://wago.tools/api/builds/latest"; +pub const FOREVER_PRODUCT: &str = "wowf"; #[derive(Debug, Error)] pub enum DownloadError { @@ -38,6 +41,10 @@ pub enum DownloadError { BossPortraits(#[from] BossPortraitError), #[error("downloaded map art data is invalid: {0}")] MapArt(#[from] MapArtError), + #[error("downloaded build list is invalid: {0}")] + Builds(#[from] serde_json::Error), + #[error("wago.tools lists no build of {0}")] + NoBuild(&'static str), } /// The tables read from the spells' `SpellMisc` rows. @@ -46,20 +53,61 @@ pub struct SpellTables { pub channels: ChannelSpells, } +/// The spell tables of the Forever build they were exported from. +pub struct ForeverTables { + pub build: String, + pub spells: SpellTables, + pub classes: SpellClasses, +} + /// Builds the spell icon and channel tables from the wago.tools exports. pub fn download_spell_tables(fetch: &F) -> Result { - let spell_misc = fetch.get(WAGO_SPELL_MISC_URL)?; - let manifest = fetch.get(WAGO_MANIFEST_URL)?; + spell_tables(fetch, None) +} + +/// Builds the class and crowd-control spell table from the wago.tools exports. +pub fn download_spell_classes(fetch: &F) -> Result { + spell_classes(fetch, None) +} + +/// Builds the spell tables of the newest Forever build. +pub fn download_forever_tables(fetch: &F) -> Result { + let build = latest_build(fetch, FOREVER_PRODUCT)?; + Ok(ForeverTables { + spells: spell_tables(fetch, Some(&build))?, + classes: spell_classes(fetch, Some(&build))?, + build, + }) +} + +fn latest_build(fetch: &F, product: &'static str) -> Result { + let builds: serde_json::Value = serde_json::from_slice(&fetch.get(WAGO_LATEST_BUILDS_URL)?)?; + builds[product]["version"] + .as_str() + .map(str::to_string) + .ok_or(DownloadError::NoBuild(product)) +} + +/// A table of `build`, or of the newest retail build without one. +fn table_url(base: &str, build: Option<&str>) -> String { + match build { + Some(build) => format!("{base}?build={build}"), + None => base.to_string(), + } +} + +fn spell_tables(fetch: &F, build: Option<&str>) -> Result { + let spell_misc = fetch.get(&table_url(WAGO_SPELL_MISC_URL, build))?; + let manifest = fetch.get(&table_url(WAGO_MANIFEST_URL, build))?; Ok(SpellTables { icons: SpellIconTable::from_csv(&spell_misc, &manifest)?, channels: ChannelSpells::from_csv(&spell_misc)?, }) } -/// Builds the class and crowd-control spell table from the wago.tools exports. -pub fn download_spell_classes(fetch: &F) -> Result { - let spell_class_options = fetch.get(WAGO_SPELL_CLASS_OPTIONS_URL)?; - let spell_effect = fetch.get(WAGO_SPELL_EFFECT_URL)?; +fn spell_classes(fetch: &F, build: Option<&str>) -> Result { + let spell_class_options = fetch.get(&table_url(WAGO_SPELL_CLASS_OPTIONS_URL, build))?; + let spell_effect = fetch.get(&table_url(WAGO_SPELL_EFFECT_URL, build))?; Ok(SpellClasses::from_csv(&spell_class_options, &spell_effect)?) } diff --git a/crates/openlogs-gamedata/src/lib.rs b/crates/openlogs-gamedata/src/lib.rs index 7503514..2e20fab 100644 --- a/crates/openlogs-gamedata/src/lib.rs +++ b/crates/openlogs-gamedata/src/lib.rs @@ -29,11 +29,12 @@ pub use curated::{ RAID_FRAME_AURAS_FILE, RaidFrameAura, RaidFrameAuras, }; pub use download::{ - DownloadError, SpellTables, WAGO_AREA_TABLE_URL, WAGO_DUNGEON_ENCOUNTER_URL, - WAGO_JOURNAL_ENCOUNTER_CREATURE_URL, WAGO_JOURNAL_ENCOUNTER_URL, WAGO_MANIFEST_URL, - WAGO_MAP_CHALLENGE_MODE_URL, WAGO_MAP_URL, WAGO_SPELL_CLASS_OPTIONS_URL, WAGO_SPELL_EFFECT_URL, - WAGO_SPELL_MISC_URL, WAGO_UI_MAP_ASSIGNMENT_URL, WAGO_UI_MAP_GROUP_MEMBER_URL, - download_boss_portraits, download_dungeons, download_map_art, download_spell_classes, + DownloadError, FOREVER_PRODUCT, ForeverTables, SpellTables, WAGO_AREA_TABLE_URL, + WAGO_DUNGEON_ENCOUNTER_URL, WAGO_JOURNAL_ENCOUNTER_CREATURE_URL, WAGO_JOURNAL_ENCOUNTER_URL, + WAGO_LATEST_BUILDS_URL, WAGO_MANIFEST_URL, WAGO_MAP_CHALLENGE_MODE_URL, WAGO_MAP_URL, + WAGO_SPELL_CLASS_OPTIONS_URL, WAGO_SPELL_EFFECT_URL, WAGO_SPELL_MISC_URL, + WAGO_UI_MAP_ASSIGNMENT_URL, WAGO_UI_MAP_GROUP_MEMBER_URL, download_boss_portraits, + download_dungeons, download_forever_tables, download_map_art, download_spell_classes, download_spell_tables, }; pub use dungeons::{Dungeon, DungeonBoss, DungeonTable, DungeonTableError, KeyTimer}; diff --git a/crates/openlogs-gamedata/tests/download.rs b/crates/openlogs-gamedata/tests/download.rs new file mode 100644 index 0000000..726d0c7 --- /dev/null +++ b/crates/openlogs-gamedata/tests/download.rs @@ -0,0 +1,78 @@ +use std::sync::Mutex; + +use openlogs_gamedata::{ + DownloadError, Fetch, FetchError, WAGO_LATEST_BUILDS_URL, download_forever_tables, +}; + +const SPELL_MISC: &str = + "ID,Attributes_1,DifficultyID,SpellIconFileDataID,SpellID\n1,0,0,132276,5487\n"; +const MANIFEST: &str = + "ID,FilePath,FileName\n132276,Interface\\Icons\\,Ability_Racial_BearForm.blp\n"; +const SPELL_CLASS_OPTIONS: &str = "ID,SpellID,SpellClassSet\n1,5487,7\n"; +const SPELL_EFFECT: &str = "ID,EffectAura,SpellID\n1,0,5487\n"; + +/// Answers wago.tools requests from fixed tables and records every URL asked for. +struct FakeWago { + latest_builds: &'static str, + asked: Mutex>, +} + +impl FakeWago { + fn new(latest_builds: &'static str) -> Self { + Self { + latest_builds, + asked: Mutex::new(Vec::new()), + } + } +} + +impl Fetch for FakeWago { + fn get(&self, url: &str) -> Result, FetchError> { + self.asked.lock().unwrap().push(url.to_string()); + let table = url + .strip_prefix("https://wago.tools/db2/") + .and_then(|rest| rest.split('/').next()); + let body = match table { + None if url == WAGO_LATEST_BUILDS_URL => self.latest_builds, + Some("SpellMisc") => SPELL_MISC, + Some("ManifestInterfaceData") => MANIFEST, + Some("SpellClassOptions") => SPELL_CLASS_OPTIONS, + Some("SpellEffect") => SPELL_EFFECT, + _ => return Err(FetchError::Status(404)), + }; + Ok(body.as_bytes().to_vec()) + } +} + +#[test] +fn forever_tables_come_from_the_latest_forever_build() { + let wago = + FakeWago::new(r#"{"wow":{"version":"12.1.5.70961"},"wowf":{"version":"1.60.1.70959"}}"#); + + let tables = download_forever_tables(&wago).unwrap(); + + assert_eq!(tables.build, "1.60.1.70959"); + assert_eq!( + tables.spells.icons.icon(5487), + Some("ability_racial_bearform") + ); + assert!(tables.classes.is_class_spell(5487)); + let asked = wago.asked.lock().unwrap(); + let tables_asked: Vec<&String> = asked + .iter() + .filter(|url| url.as_str() != WAGO_LATEST_BUILDS_URL) + .collect(); + assert_eq!(tables_asked.len(), 4, "asked {asked:?}"); + for url in tables_asked { + assert!(url.ends_with("/csv?build=1.60.1.70959"), "asked {url}"); + } +} + +#[test] +fn a_latest_builds_answer_without_forever_is_an_error() { + let wago = FakeWago::new(r#"{"wow":{"version":"12.1.5.70961"}}"#); + + let err = download_forever_tables(&wago).err().unwrap(); + + assert!(matches!(err, DownloadError::NoBuild("wowf")), "got {err}"); +} diff --git a/crates/openlogs-gamedata/tests/online.rs b/crates/openlogs-gamedata/tests/online.rs index 7760e2f..98a2fda 100644 --- a/crates/openlogs-gamedata/tests/online.rs +++ b/crates/openlogs-gamedata/tests/online.rs @@ -1,8 +1,8 @@ //! Hits the real services. `cargo test -p openlogs-gamedata --test online -- --ignored` use openlogs_gamedata::{ - HttpFetch, download_boss_portraits, download_dungeons, download_map_art, - download_spell_classes, download_spell_tables, + HttpFetch, download_boss_portraits, download_dungeons, download_forever_tables, + download_map_art, download_spell_classes, download_spell_tables, }; #[test] @@ -63,3 +63,19 @@ fn wago_tools_provides_every_table() { assert_eq!((sszorak_room.zone, sszorak_room.floor), (16915, Some(3))); assert_eq!(map_art.pins[&3420].ui_map_id, 2609, "Sszorak has a pin"); } + +#[test] +#[ignore = "needs network access to wago.tools"] +fn wago_tools_provides_the_forever_tables() { + let tables = download_forever_tables(&HttpFetch::for_bulk_data()).unwrap(); + assert!(tables.build.starts_with("1."), "got build {}", tables.build); + assert!( + tables.spells.icons.icon(5487).is_some(), + "Bear Form has an icon" + ); + assert!( + tables.classes.class_spell_count() > 1_000, + "got {} class spells", + tables.classes.class_spell_count() + ); +} diff --git a/crates/openlogs-wasm/src/engine.rs b/crates/openlogs-wasm/src/engine.rs index 85052c3..04cab2f 100644 --- a/crates/openlogs-wasm/src/engine.rs +++ b/crates/openlogs-wasm/src/engine.rs @@ -25,6 +25,60 @@ use serde_json::Value; /// Pulls kept loaded: the shown pull and the one it is compared with. const LOADED_PULLS: usize = 2; +/// The games with spell tables of their own. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DataGame { + Retail, + Forever, +} + +impl DataGame { + /// Forever has its own tables; every other game reads retail's. The app follows the same + /// rule (`dataGameOf`). + pub fn of(flavor: Option) -> Self { + match flavor { + Some(GameFlavor::Forever) => Self::Forever, + _ => Self::Retail, + } + } + + pub fn from_name(name: &str) -> Result { + match name { + "retail" => Ok(Self::Retail), + "forever" => Ok(Self::Forever), + _ => Err(format!("No game data for the game {name}")), + } + } +} + +#[derive(Default)] +struct GameTables { + channels: ChannelSpells, + spell_classes: SpellClasses, +} + +#[derive(Default)] +struct TablesByGame { + retail: GameTables, + forever: GameTables, +} + +impl TablesByGame { + fn of_flavor(&self, flavor: Option) -> &GameTables { + match DataGame::of(flavor) { + DataGame::Retail => &self.retail, + DataGame::Forever => &self.forever, + } + } + + fn of_mut(&mut self, game: DataGame) -> &mut GameTables { + match game { + DataGame::Retail => &mut self.retail, + DataGame::Forever => &mut self.forever, + } + } +} + /// One open log: its index, the most recently loaded pulls and the game data reports use. pub struct Engine { indexer: Indexer, @@ -33,8 +87,7 @@ pub struct Engine { fights: Vec, curated: Curated, dungeons: Option, - channels: ChannelSpells, - spell_classes: SpellClasses, + spell_tables: TablesByGame, pass: Option, } @@ -46,8 +99,7 @@ impl Default for Engine { fights: Vec::new(), curated: Curated::bundled(), dungeons: None, - channels: ChannelSpells::default(), - spell_classes: SpellClasses::default(), + spell_tables: TablesByGame::default(), pass: None, } } @@ -59,16 +111,22 @@ impl Engine { Ok(()) } - pub fn set_channel_spells(&mut self, json: &str) -> Result<(), String> { - self.channels = ChannelSpells::from_json(json).map_err(|err| err.to_string())?; + pub fn set_channel_spells(&mut self, game: DataGame, json: &str) -> Result<(), String> { + self.spell_tables.of_mut(game).channels = + ChannelSpells::from_json(json).map_err(|err| err.to_string())?; Ok(()) } - pub fn set_spell_classes(&mut self, json: &str) -> Result<(), String> { - self.spell_classes = SpellClasses::from_json(json).map_err(|err| err.to_string())?; + pub fn set_spell_classes(&mut self, game: DataGame, json: &str) -> Result<(), String> { + self.spell_tables.of_mut(game).spell_classes = + SpellClasses::from_json(json).map_err(|err| err.to_string())?; Ok(()) } + fn tables(&self) -> &GameTables { + self.spell_tables.of_flavor(self.index.flavor) + } + /// Starts indexing a new log; the previous log and its pulls are dropped. pub fn begin_index(&mut self) { self.indexer = Indexer::new(); @@ -159,7 +217,7 @@ impl Engine { ) -> Result<(), String> { let summary = self.summary(fight_index)?.clone(); let mut fight = load_fight_slice(part, base_offset, &summary); - ready_for_reports(&mut fight, self.index.flavor, &self.spell_classes); + ready_for_reports(&mut fight, self.index.flavor, &self.tables().spell_classes); self.fights.retain(|pulled| pulled.index != fight_index); self.fights.insert( 0, @@ -210,7 +268,8 @@ impl Engine { let summary = summary_of(&self.index, fight_index)?; let mut fight = load_fight_slice_with(part, base_offset, summary, pass.actors.carried_over()); - ready_for_reports(&mut fight, self.index.flavor, &self.spell_classes); + let tables = self.spell_tables.of_flavor(self.index.flavor); + ready_for_reports(&mut fight, self.index.flavor, &tables.spell_classes); let mut cuts = PullCuts::new(&fight); for command in &mut pass.commands { command.add(fight_index, &fight, &self.curated, &mut cuts); @@ -409,7 +468,7 @@ impl Engine { json(openlogs_service::timeline( self.fight(args.fight_index)?, curated, - &self.channels, + &self.tables().channels, args.filter, args.scope, args.metric, @@ -432,8 +491,8 @@ impl Engine { json(openlogs_service::replay( self.fight(args.fight_index)?, curated, - &self.channels, - &self.spell_classes, + &self.tables().channels, + &self.tables().spell_classes, self.index.advanced_logging, )) } diff --git a/crates/openlogs-wasm/src/lib.rs b/crates/openlogs-wasm/src/lib.rs index 4cd08e2..e387f06 100644 --- a/crates/openlogs-wasm/src/lib.rs +++ b/crates/openlogs-wasm/src/lib.rs @@ -5,7 +5,7 @@ mod engine; use std::cell::RefCell; -pub use engine::Engine; +pub use engine::{DataGame, Engine}; use wasm_bindgen::prelude::*; thread_local! { @@ -39,12 +39,14 @@ impl Session { self.engine.set_dungeons(json).map_err(to_js) } - pub fn set_channel_spells(&mut self, json: &str) -> Result<(), JsValue> { - self.engine.set_channel_spells(json).map_err(to_js) + pub fn set_channel_spells(&mut self, json: &str, game: &str) -> Result<(), JsValue> { + let game = DataGame::from_name(game).map_err(to_js)?; + self.engine.set_channel_spells(game, json).map_err(to_js) } - pub fn set_spell_classes(&mut self, json: &str) -> Result<(), JsValue> { - self.engine.set_spell_classes(json).map_err(to_js) + pub fn set_spell_classes(&mut self, json: &str, game: &str) -> Result<(), JsValue> { + let game = DataGame::from_name(game).map_err(to_js)?; + self.engine.set_spell_classes(game, json).map_err(to_js) } pub fn begin_index(&mut self) { diff --git a/crates/openlogs-wasm/tests/engine.rs b/crates/openlogs-wasm/tests/engine.rs index 2ceb80d..698e7d1 100644 --- a/crates/openlogs-wasm/tests/engine.rs +++ b/crates/openlogs-wasm/tests/engine.rs @@ -1,6 +1,6 @@ use openlogs_gamedata::DungeonTable; use openlogs_parser::Timestamp; -use openlogs_wasm::Engine; +use openlogs_wasm::{DataGame, Engine}; use serde_json::{Value, json}; const FIXTURE: &str = include_str!("../../openlogs-index/tests/fixtures/mini_raid.txt"); @@ -896,6 +896,66 @@ fn a_run_opens_like_a_pull_with_boss_phases_and_no_boss_hp() { ); } +/// The class each player of the open-world log's combat pull takes from their casts. +fn classes_from_casts(engine: Engine, log: &str) -> (Value, Value) { + let (mut engine, view) = open_with(engine, log); + let pull = view["fights"] + .as_array() + .unwrap() + .iter() + .find(|f| !f["combat"].is_null()) + .unwrap()["index"] + .as_u64() + .unwrap() as u32; + load(&mut engine, log, pull); + let report = call( + &engine, + "damage_done_report", + json!({ "fightIndex": pull, "filter": whole_pull() }), + ); + let class_of = |name: &str| { + report["roster"] + .as_array() + .unwrap() + .iter() + .find(|p| p["name"] == name) + .unwrap()["classId"] + .clone() + }; + ( + class_of("Ravel-Ashwood-Normal-EU"), + class_of("Brakk-Thornfield-Normal-EU"), + ) +} + +#[test] +fn a_log_reads_the_spell_classes_of_its_own_game() { + const FOREVER: &str = + include_str!("../../openlogs-index/tests/fixtures/forever_open_world.txt"); + let retail = FOREVER.replacen("PROJECT_ID,18", "PROJECT_ID,1", 1); + let rogue_and_warrior = r#"{"classSpells":[100,1657],"crowdControl":[],"families":[4,8]}"#; + let warrior_and_rogue = r#"{"classSpells":[100,1657],"crowdControl":[],"families":[8,4]}"#; + let engine = |retail_table: &str, forever_table: &str| { + let mut engine = Engine::default(); + engine + .set_spell_classes(DataGame::Retail, retail_table) + .unwrap(); + engine + .set_spell_classes(DataGame::Forever, forever_table) + .unwrap(); + engine + }; + + assert_eq!( + classes_from_casts(engine(warrior_and_rogue, rogue_and_warrior), FOREVER), + (json!(4), json!(1)) + ); + assert_eq!( + classes_from_casts(engine(rogue_and_warrior, warrior_and_rogue), &retail), + (json!(4), json!(1)) + ); +} + #[test] fn players_without_a_spec_take_the_class_of_their_casts() { const OPEN_WORLD: &str = @@ -904,7 +964,7 @@ fn players_without_a_spec_take_the_class_of_their_casts() { let charge_and_sinister_strike = r#"{"classSpells":[100,1657],"crowdControl":[],"families":[4,8]}"#; engine - .set_spell_classes(charge_and_sinister_strike) + .set_spell_classes(DataGame::Forever, charge_and_sinister_strike) .unwrap(); let (mut engine, view) = open_with(engine, OPEN_WORLD); let pull = view["fights"] diff --git a/ui/scripts/fetch-images.mjs b/ui/scripts/fetch-images.mjs index 87fefbc..7f987b5 100644 --- a/ui/scripts/fetch-images.mjs +++ b/ui/scripts/fetch-images.mjs @@ -14,8 +14,9 @@ const ATTEMPTS = 4; const TIMEOUT_MS = 30_000; const readJson = async (path) => JSON.parse(await readFile(join(ui, path), 'utf8')); -const [spellIcons, portraits, mapArt, classesSpecs] = await Promise.all([ +const [spellIcons, foreverSpellIcons, portraits, mapArt, classesSpecs] = await Promise.all([ readJson('public/game-data/spell-icons.json'), + readJson('public/game-data/forever/spell-icons.json'), readJson('public/game-data/boss-portraits.json'), readJson('public/game-data/map-art.json'), readJson('../crates/openlogs-gamedata/data/classes_specs.json'), @@ -23,6 +24,7 @@ const [spellIcons, portraits, mapArt, classesSpecs] = await Promise.all([ const iconNames = [ ...spellIcons.names, + ...foreverSpellIcons.names, ...classesSpecs.classes.map((c) => classIconName(c.token)), ...classesSpecs.specs.map((s) => s.icon), ...NAMED_ICONS, diff --git a/ui/src/api/client.test.ts b/ui/src/api/client.test.ts index acad276..35dc80c 100644 --- a/ui/src/api/client.test.ts +++ b/ui/src/api/client.test.ts @@ -185,6 +185,51 @@ describe('opening logs', () => { expect(given).toEqual(['keys', classes, '{"ids":[5143]}']); }); + it('gives a Forever log the Forever tables and a retail log the retail ones', async () => { + const fake = fakeEngine(); + const given: [string, string][] = []; + fake.engine.setChannelSpells = async (json, game) => void given.push([json, game]); + fake.engine.setSpellClasses = async (json, game) => void given.push([json, game]); + fake.engine.finishIndex = async (logId) => ({ ...view(logId), game: { kind: logId.startsWith('f') ? 'forever' : 'retail' } }); + const api = createClient({ + engine: () => fake.engine, + dungeons: async () => null, + channelSpells: async (game) => `${game}-channels`, + spellClasses: async (game) => `${game}-classes`, + db: memoryDatabase(), + now: () => 1, + }); + await api.openLog(source('f.txt', 10)); + await api.openLog(source('r.txt', 10)); + await api.openLog(source('f.txt', 11)); + expect(given).toEqual([ + ['forever-channels', 'forever'], + ['forever-classes', 'forever'], + ['retail-channels', 'retail'], + ['retail-classes', 'retail'], + ]); + }); + + it('gives a Forever log reopened from its stored index the Forever tables', async () => { + const db = memoryDatabase(); + const forever = (engine: Engine) => { + engine.finishIndex = async (logId) => ({ ...view(logId), game: { kind: 'forever' } }); + engine.restoreIndex = async (_, logId) => ({ ...view(logId), game: { kind: 'forever' }, cacheHit: true }); + }; + const first = fakeEngine(); + forever(first.engine); + const deps = { dungeons: async () => null, channelSpells: async () => null, spellClasses: async () => 'classes', db, now: () => 1 }; + await createClient({ engine: () => first.engine, ...deps }).openLog(source('f.txt', 10)); + + const second = fakeEngine(); + forever(second.engine); + const given: string[] = []; + second.engine.setSpellClasses = async (_, game) => void given.push(game); + const reopened = await createClient({ engine: () => second.engine, ...deps }).openLog(source('f.txt', 10)); + expect(reopened.cacheHit).toBe(true); + expect(given).toEqual(['forever']); + }); + it('opens a log without a game table the engine rejects', async () => { const fake = fakeEngine(); fake.engine.setChannelSpells = async () => { @@ -377,6 +422,21 @@ describe('following a log that grows', () => { expect(result).not.toBeNull(); }); + it('gives a log the Forever tables once its growth shows it is a Forever log', async () => { + const fake = fakeEngine(); + const given: string[] = []; + fake.engine.setSpellClasses = async (_, game) => void given.push(game); + fake.engine.refreshIndex = async (logId) => ({ ...view(logId), game: { kind: 'forever' } }); + const api = createClient({ engine: () => fake.engine, dungeons: async () => null, channelSpells: async () => null, spellClasses: async () => '{}', db: memoryDatabase(), now: () => 1 }); + const log = growable('today.txt', 0); + await api.openLog(log); + + log.grow(10); + await api.followLog('today.txt', false); + + expect(given).toEqual(['retail', 'forever']); + }); + it('feeds each appended byte once, also when later refreshes find no growth', async () => { const { api, fed } = client(); const log = growable('raid.txt', 10 * MiB); diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts index 497f4ba..3cefa0e 100644 --- a/ui/src/api/client.ts +++ b/ui/src/api/client.ts @@ -1,5 +1,5 @@ import { type Engine, workerEngine } from '../engine/engine'; -import { channelSpellsJson, dungeonsJson, spellClassesJson } from '../gameData'; +import { type DataGame, channelSpellsJson, dataGameOf, dungeonsJson, spellClassesJson } from '../gameData'; import { t } from '../i18n/i18n'; import { browserDatabase, type Database } from './db'; import { fileGone, fileMissing, type LogSource, reopenHandle } from './logSource'; @@ -59,8 +59,8 @@ interface IndexUse { export interface ClientDeps { engine: () => Engine; dungeons: () => Promise; - channelSpells: () => Promise; - spellClasses: () => Promise; + channelSpells: (game: DataGame) => Promise; + spellClasses: (game: DataGame) => Promise; db: Database; now: () => number; } @@ -96,7 +96,8 @@ export function createClient({ engine: getEngine, dungeons, channelSpells, spell forgotten: boolean; } | null = null; const openings = new Set<{ logId: string; forgotten: boolean }>(); - const gameDataLoaded = { dungeons: false, channelSpells: false, spellClasses: false }; + /** `dungeons`, or a spell table and its game such as `spellClasses:forever`. */ + const gameDataLoaded = new Set(); let latestOpen = 0; let queue: Promise = Promise.resolve(); @@ -145,22 +146,18 @@ export function createClient({ engine: getEngine, dungeons, channelSpells, spell await useIndex(key); } - async function loadTable(table: keyof typeof gameDataLoaded, load: () => Promise, give: (json: string) => Promise) { - if (gameDataLoaded[table]) return; + /** Without game data, logs still open: run results and channels then come from the log alone. */ + async function loadTable(table: string, load: () => Promise, give: (json: string) => Promise) { + if (gameDataLoaded.has(table)) return; const json = await load().catch(() => null); if (json === null) return; // A table the engine rejects is asked for again with the next log; this one opens without it. - gameDataLoaded[table] = await give(json).then( - () => true, - () => false, - ); + if (await give(json).then(() => true, () => false)) gameDataLoaded.add(table); } - /** Without game data, logs still open: run results and channels then come from the log alone. */ - async function loadGameData(engine: Engine) { - await loadTable('dungeons', dungeons, (json) => engine.setDungeons(json)); - await loadTable('channelSpells', channelSpells, (json) => engine.setChannelSpells(json)); - await loadTable('spellClasses', spellClasses, (json) => engine.setSpellClasses(json)); + async function loadSpellTables(engine: Engine, game: DataGame) { + await loadTable(`channelSpells:${game}`, () => channelSpells(game), (json) => engine.setChannelSpells(json, game)); + await loadTable(`spellClasses:${game}`, () => spellClasses(game), (json) => engine.setSpellClasses(json, game)); } async function index( @@ -169,13 +166,14 @@ export function createClient({ engine: getEngine, dungeons, channelSpells, spell superseded: () => boolean, ): Promise<{ view: LogView; key: string; followedBytes: number }> { const engine = getEngine(); - await loadGameData(engine); + await loadTable('dungeons', dungeons, (json) => engine.setDungeons(json)); const key = await indexKey(engine, source); const stored = await quietly(() => db.get('indexes', key)); if (stored) { const view = await quietly(() => engine.restoreIndex(stored.json, source.id, source.name, source.size)); if (view) { await quietly(() => useIndex(key)); + await loadSpellTables(engine, dataGameOf(view.game)); return { view, key, followedBytes: 0 }; } } @@ -193,6 +191,7 @@ export function createClient({ engine: getEngine, dungeons, channelSpells, spell const view = await engine.finishIndex(source.id, source.name, source.size); const json = await engine.indexJson(); await quietly(() => storeIndex(key, json)); + await loadSpellTables(engine, dataGameOf(view.game)); return { view, key, followedBytes: source.size }; } @@ -266,6 +265,8 @@ export function createClient({ engine: getEngine, dungeons, channelSpells, spell log.followedBytes += await engine.feed(await readSome(source, log.followedBytes)); } const view = await engine.refreshIndex(source.id, source.name, source.size, settleAll); + // A log opened before its header was written learns its game only now. + await loadSpellTables(engine, dataGameOf(view.game)); await storeFollowed(engine, log, view, settleAll); return view; } finally { diff --git a/ui/src/components/SettingsDialog.tsx b/ui/src/components/SettingsDialog.tsx index a76aa63..ce993f0 100644 --- a/ui/src/components/SettingsDialog.tsx +++ b/ui/src/components/SettingsDialog.tsx @@ -8,7 +8,7 @@ import { THEMES, type ThemeName } from '../theme'; import { effectiveScale, SCALE_AT_BASE, UI_SIZES } from '../uiScale'; import { useAutoScale } from '../hooks/useAutoScale'; -const TABLES: { key: keyof Omit; name: MessageKey; entries: MessageKey }[] = [ +const TABLES: { key: keyof Omit; name: MessageKey; entries: MessageKey }[] = [ { key: 'spellIcons', name: 'settings.spellIcons', entries: 'settings.entries.spellIcons' }, { key: 'channelSpells', name: 'settings.channelSpells', entries: 'settings.entries.spellIcons' }, { key: 'dungeons', name: 'settings.dungeons', entries: 'settings.entries.dungeons' }, diff --git a/ui/src/currentGame.ts b/ui/src/currentGame.ts index 365f198..5ec63a3 100644 --- a/ui/src/currentGame.ts +++ b/ui/src/currentGame.ts @@ -1,12 +1,19 @@ import type { Game } from './api/types'; let game: Game | null = null; +const listeners = new Set<() => void>(); -/** The game of the open log, which decides how names read; the store keeps it in step. */ +/** The game of the open log, which decides how names read and which spell icons show; the store keeps it in step. */ export function currentGame(): Game | null { return game; } export function setCurrentGame(next: Game | null) { game = next; + listeners.forEach((listener) => listener()); +} + +export function subscribeCurrentGame(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); } diff --git a/ui/src/engine/engine.ts b/ui/src/engine/engine.ts index 8ed5cdf..faf546a 100644 --- a/ui/src/engine/engine.ts +++ b/ui/src/engine/engine.ts @@ -1,4 +1,5 @@ import type { LogView } from '../api/types'; +import type { DataGame } from '../gameData'; import type { EngineMethod, EngineRequest, EngineResponse } from './protocol'; /** The analysis engine (Rust, as WebAssembly) in its Web Worker. It holds one log at a time. */ @@ -8,9 +9,9 @@ export interface Engine { /** The Mythic+ dungeon table, which decides run results and key timers. */ setDungeons(json: string): Promise; /** The spells the game channels, which draw as channels where the log has no channel aura. */ - setChannelSpells(json: string): Promise; + setChannelSpells(json: string, game: DataGame): Promise; /** Which spells belong to a player class and which of those are crowd control. */ - setSpellClasses(json: string): Promise; + setSpellClasses(json: string, game: DataGame): Promise; beginIndex(): Promise; /** Takes ownership of `bytes`, which are empty afterwards; resolves to how many it took. */ feed(bytes: Uint8Array): Promise; @@ -77,8 +78,8 @@ export function workerEngine(): Engine { return { indexFormatVersion: () => send('index_format_version'), setDungeons: (json) => send('set_dungeons', [json]), - setChannelSpells: (json) => send('set_channel_spells', [json]), - setSpellClasses: (json) => send('set_spell_classes', [json]), + setChannelSpells: (json, game) => send('set_channel_spells', [json, game]), + setSpellClasses: (json, game) => send('set_spell_classes', [json, game]), beginIndex: () => send('begin_index'), feed: async (bytes) => { const { length } = bytes; diff --git a/ui/src/engine/worker.ts b/ui/src/engine/worker.ts index d933c7c..5db7c6b 100644 --- a/ui/src/engine/worker.ts +++ b/ui/src/engine/worker.ts @@ -10,12 +10,12 @@ const ready = init(); let session: Session | undefined; const GAME_DATA = ['set_dungeons', 'set_channel_spells', 'set_spell_classes'] as const; type GameDataMethod = (typeof GAME_DATA)[number]; -/** Given again to a session that replaces one that trapped. */ -const gameData = new Map(); +/** Given again to a session that replaces one that trapped; one entry per table and game. */ +const gameData = new Map(); function openSession(): Session { const fresh = new Session(); - gameData.forEach((json, method) => fresh[method](json)); + gameData.forEach(({ method, args }) => Reflect.apply(fresh[method] as (...args: unknown[]) => unknown, fresh, args)); return fresh; } @@ -24,7 +24,7 @@ scope.onmessage = async ({ data: { id, method, args } }) => { await ready; session ??= openSession(); const result: unknown = Reflect.apply(session[method] as (...args: unknown[]) => unknown, session, args); - if ((GAME_DATA as readonly string[]).includes(method)) gameData.set(method as GameDataMethod, args[0] as string); + if ((GAME_DATA as readonly string[]).includes(method)) gameData.set(`${method}:${String(args[1] ?? '')}`, { method: method as GameDataMethod, args }); scope.postMessage({ id, result }); } catch (error) { if (error instanceof WebAssembly.RuntimeError) { diff --git a/ui/src/gameData.test.ts b/ui/src/gameData.test.ts index 97879e7..bd58d51 100644 --- a/ui/src/gameData.test.ts +++ b/ui/src/gameData.test.ts @@ -47,4 +47,69 @@ describe('game data tables', () => { await vi.advanceTimersByTimeAsync(1); expect(mapArtRequests(), 'a loaded table is kept').toBe(2); }); + + it('asks for no Forever table when the export has none', async () => { + const requested: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + requested.push(url); + if (url.includes('manifest.json')) return json('{"fetchedUnixMs":1}'); + return json('{}'); + }), + ); + const { spellClassesJson } = await import('./gameData'); + + expect(await spellClassesJson('forever')).toBeNull(); + expect(requested.filter((url) => url.includes('forever/'))).toEqual([]); + }); + + it('reads the Forever tables from their own directory', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + if (url.includes('manifest.json')) return json('{"fetchedUnixMs":1,"forever":{"build":"1.60.1.71037","spellIcons":1,"channelSpells":1,"spellClasses":1}}'); + if (url.includes('forever/spell-classes.json')) return json('forever classes'); + if (url.includes('spell-classes.json')) return json('retail classes'); + return new Response('', { status: 404 }); + }), + ); + const { spellClassesJson } = await import('./gameData'); + + expect(await spellClassesJson('forever')).toBe('forever classes'); + expect(await spellClassesJson('retail')).toBe('retail classes'); + }); + + it('shows the spell icons of the game of the open log', async () => { + const icons = (name: string) => json(JSON.stringify({ ids: [5487], icons: [0], names: [name] })); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + if (url.includes('manifest.json')) return json('{"fetchedUnixMs":1,"forever":{"build":"1.60.1.71037","spellIcons":1,"channelSpells":1,"spellClasses":1}}'); + if (url.includes('forever/spell-icons.json')) return icons('ability_racial_bearform'); + if (url.includes('spell-icons.json')) return icons('retail_icon'); + return new Response('', { status: 404 }); + }), + ); + const { setCurrentGame } = await import('./currentGame'); + const { iconTables, loadIconTables, spellIconName, subscribeIconTables } = await import('./gameData'); + const bearForm = () => { + const spells = iconTables().spells; + return spells && spellIconName(spells, 5487); + }; + const notified = vi.fn(); + subscribeIconTables(notified); + + setCurrentGame({ kind: 'forever' }); + loadIconTables(); + await vi.waitFor(() => expect(bearForm()).toBe('ability_racial_bearform')); + + notified.mockClear(); + setCurrentGame({ kind: 'retail' }); + expect(notified).toHaveBeenCalled(); + await vi.waitFor(() => expect(bearForm()).toBe('retail_icon')); + + setCurrentGame({ kind: 'forever' }); + expect(bearForm(), 'a loaded table is shown again at once').toBe('ability_racial_bearform'); + }); }); diff --git a/ui/src/gameData.ts b/ui/src/gameData.ts index 5907d82..750aeb7 100644 --- a/ui/src/gameData.ts +++ b/ui/src/gameData.ts @@ -1,4 +1,5 @@ -import type { MapArtTable } from './api/types'; +import type { Game, MapArtTable } from './api/types'; +import { currentGame, subscribeCurrentGame } from './currentGame'; /** Game data shipped next to the app in `game-data/`, written by `openlogs-cli export-game-data`. */ export interface GameDataManifest { @@ -13,6 +14,16 @@ export interface GameDataManifest { bossPortraits: number; /** Absent in an export made before map art was exported. */ mapArt?: number; + /** The spell tables of the Forever build, in `forever/`; absent in an export made before them. */ + forever?: { build: string; spellIcons: number; channelSpells: number; spellClasses: number }; +} + +/** The games with spell tables of their own. */ +export type DataGame = 'retail' | 'forever'; + +/** Forever has its own tables; every other game reads retail's. The engine follows the same rule (`DataGame::of`). */ +export function dataGameOf(game: Game | null): DataGame { + return game?.kind === 'forever' ? 'forever' : 'retail'; } /** Spell ID → icon name, as sorted parallel arrays. */ @@ -23,6 +34,7 @@ export interface SpellIcons { } export interface IconTables { + /** Of the open log's game. */ spells: SpellIcons | null; /** Encounter ID → Encounter Journal portrait name. */ portraits: Record | null; @@ -51,19 +63,21 @@ export function gameDataManifest(): Promise { } /** A table named by the manifest; the manifest's time keeps browser caches from serving an older export. */ -async function tableText(file: string): Promise { +async function tableText(file: string, game: DataGame = 'retail'): Promise { const manifest = await gameDataManifest(); - return manifest ? fetchText(`${file}?v=${manifest.fetchedUnixMs}`) : null; + if (!manifest || (game === 'forever' && !manifest.forever)) return null; + const path = game === 'forever' ? `forever/${file}` : file; + return fetchText(`${path}?v=${manifest.fetchedUnixMs}`); } /** The Mythic+ dungeon table for the engine. */ export const dungeonsJson = (): Promise => tableText('dungeons.json').catch(() => null); /** The spells the game channels, for the engine. */ -export const channelSpellsJson = (): Promise => tableText('channel-spells.json').catch(() => null); +export const channelSpellsJson = (game: DataGame): Promise => tableText('channel-spells.json', game).catch(() => null); /** The class and crowd-control spells, for the engine. */ -export const spellClassesJson = (): Promise => tableText('spell-classes.json').catch(() => null); +export const spellClassesJson = (game: DataGame): Promise => tableText('spell-classes.json', game).catch(() => null); /** Decodes the export's spell IDs, stored as differences to the previous ID. */ export function decodeSpellIcons(table: { ids: number[]; icons: number[]; names: string[] }): SpellIcons { @@ -92,29 +106,51 @@ export function spellIconName(spells: SpellIcons, spellId: number): string | nul /** A table that could not be loaded is asked for again after this long. */ const RETRY_MS = 30_000; +const spellIcons: Record = { retail: null, forever: null }; +let portraits: IconTables['portraits'] = null; +let mapArt: IconTables['mapArt'] = null; let tables: IconTables = { spells: null, portraits: null, mapArt: null }; const listeners = new Set<() => void>(); -const nextAttempt: Record = { spells: 0, portraits: 0, mapArt: 0 }; +/** By table, and for spell icons by game too, such as `spells:forever`. */ +const nextAttempt = new Map(); + +function publish() { + tables = { spells: spellIcons[dataGameOf(currentGame())], portraits, mapArt }; + listeners.forEach((listener) => listener()); +} -function loadTable(key: K, file: string, parse: (text: string) => IconTables[K]) { - if (tables[key] !== null || Date.now() < nextAttempt[key]) return; - nextAttempt[key] = Number.POSITIVE_INFINITY; - void tableText(file) +function loadTable(table: string, loaded: boolean, read: () => Promise, keep: (text: string) => void) { + if (loaded || Date.now() < (nextAttempt.get(table) ?? 0)) return; + nextAttempt.set(table, Number.POSITIVE_INFINITY); + void read() .then((text) => { - if (text === null) throw new Error(`${file} is missing`); - tables = { ...tables, [key]: parse(text) }; - listeners.forEach((listener) => listener()); + if (text === null) throw new Error(`${table} is missing`); + keep(text); + publish(); }) - .catch(() => (nextAttempt[key] = Date.now() + RETRY_MS)); + .catch(() => nextAttempt.set(table, Date.now() + RETRY_MS)); } -/** Components re-render through `subscribeIconTables` when the tables arrive. */ +/** Components re-render through `subscribeIconTables` when the tables arrive or the open log's game changes. */ export function loadIconTables() { - loadTable('spells', 'spell-icons.json', (text) => decodeSpellIcons(JSON.parse(text))); - loadTable('portraits', 'boss-portraits.json', (text) => JSON.parse(text)); - loadTable('mapArt', 'map-art.json', (text) => JSON.parse(text)); + const game = dataGameOf(currentGame()); + loadTable(`spells:${game}`, spellIcons[game] !== null, () => tableText('spell-icons.json', game), (text) => { + spellIcons[game] = decodeSpellIcons(JSON.parse(text)); + }); + loadTable('portraits', portraits !== null, () => tableText('boss-portraits.json'), (text) => { + portraits = JSON.parse(text); + }); + loadTable('mapArt', mapArt !== null, () => tableText('map-art.json'), (text) => { + mapArt = JSON.parse(text); + }); } +subscribeCurrentGame(() => { + publish(); + // The tables load on first use (`useIconSrc`); before that, a game change has nothing to load for. + if (listeners.size > 0) loadIconTables(); +}); + export const iconTables = () => tables; export function subscribeIconTables(listener: () => void): () => void {