From 8976bd37d4bcbe006c56e936a64b7d4a6daaddec Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:47:36 +0200 Subject: [PATCH] Select resource packs as vanilla's PackSelectionModel does, compared with vanilla horizon_client::packs::SelectionModel ports PackRepository's selection and PackSelectionModel (default positions, fixed and required packs, moving up and down, commit), and the pack screen uses it. The new pack_selection harness drives vanilla's model and Horizon's through 4,000 random action sequences; every state matches. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- .../examples/pack_selection_fixture.rs | 100 ++++++++++ crates/horizon-client/src/game/packs.rs | 35 ++-- crates/horizon-client/src/options_ui.rs | 61 +++--- crates/horizon-client/src/packs.rs | 181 ++++++++++++++++++ .../parity/VanillaPackSelectionOracle.java | 111 +++++++++++ tools/test_pack_selection_parity.py | 98 ++++++++++ 7 files changed, 539 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-client/examples/pack_selection_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java create mode 100644 tools/test_pack_selection_parity.py diff --git a/README.md b/README.md index 0c70f54e6..4ef3f3cb1 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete and verified against vanilla by differential tests). The percentage is the average; `tests/test_parity.py` keeps it in sync with this table. Last audited 2026-10-12 against the harness results: 270 harnesses pass. Two still differ -from vanilla in places: `mob_ai` (78 of 79 scenarios; a tempted ghastling) and +from vanilla in places: `mob_ai` (83 of 84 scenarios; a tempted ghastling) and `sculk` (427 of 435; shrieker warnings and warden summoning). | Subsystem | Score | Main gaps | @@ -134,9 +134,9 @@ from vanilla in places: `mob_ai` (78 of 79 scenarios; a tempted ghastling) and | Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included | | World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla | | Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded | -| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (78 of 79 scenarios, villager and copper golem brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | +| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (83 of 84 scenarios, villager and copper golem brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | | Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla | -| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), the player list matches over 872,000 draw calls with heads drawn from players' skins (authlib's textures, SkinManager's lookup, legacy skin conversion), and the chat matches focused and scrolled; the chat input box and command suggestions are not compared, and there is no resource pack screen | +| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), the player list matches over 872,000 draw calls with heads drawn from players' skins (authlib's textures, SkinManager's lookup, legacy skin conversion), and the chat matches focused and scrolled; the resource pack screen's selection (moving packs between the lists, ordering, required and fixed packs) matches over 4,000 cases; the pack screen's drawing, its incompatibility confirmation, and the chat input box and command suggestions are not compared | | Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla | | Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers (6,000 cases), crafters (4,000 crafts) and block entity removal (containers spill, 4,000 cases) match vanilla; copper golems sort chests as vanilla's brain does (7 scenarios, tick for tick); 8 of 435 sculk scenarios differ (shrieker warnings and warden summoning) | diff --git a/crates/horizon-client/examples/pack_selection_fixture.rs b/crates/horizon-client/examples/pack_selection_fixture.rs new file mode 100644 index 000000000..65ed2471a --- /dev/null +++ b/crates/horizon-client/examples/pack_selection_fixture.rs @@ -0,0 +1,100 @@ +//! Headless transport for the pack selection parity gate: builds each +//! case's `horizon_client::packs::SelectionModel`, applies its actions and +//! writes both lists with each entry's select/unselect/move flags after +//! every action, and the committed selection. +#![forbid(unsafe_code)] +use horizon_client::packs::{Position, Selectable, SelectionModel}; +use serde_json::{Value, json}; +use std::{ + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn lists(m: &SelectionModel) -> Value { + let side = |selected: bool| -> Value { + let list = if selected { &m.selected } else { &m.unselected }; + (0..list.len()) + .map(|i| { + let mut flags = String::new(); + for (on, c) in [ + (m.can_select(selected, i), 's'), + (m.can_unselect(selected, i), 'u'), + (m.can_move_up(selected, i), '^'), + (m.can_move_down(selected, i), 'v'), + ] { + if on { + flags.push(c); + } + } + json!([list[i].id, flags]) + }) + .collect() + }; + json!({"unselected": side(false), "selected": side(true)}) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [inputs, output] = args.as_slice() else { + return Err("usage: pack_selection_fixture INPUTS OUTPUT".into()); + }; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let c: Value = serde_json::from_str(line)?; + let packs = c["packs"] + .as_array() + .into_iter() + .flatten() + .map(|p| Selectable { + id: p["id"].as_str().unwrap_or("").to_owned(), + required: p["required"].as_bool().unwrap_or(false), + position: if p["position"] == "top" { + Position::Top + } else { + Position::Bottom + }, + fixed: p["fixed"].as_bool().unwrap_or(false), + compatible: p["compat"] == "compatible", + }) + .collect(); + let selected: Vec = c["selected"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect(); + let mut m = SelectionModel::new(packs, &selected); + let mut steps = vec![lists(&m)]; + for op in c["ops"].as_array().into_iter().flatten() { + let sel = op["list"] == "selected"; + let len = if sel { + m.selected.len() + } else { + m.unselected.len() + }; + if len > 0 { + let i = op["index"].as_i64().unwrap_or(0).rem_euclid(len as i64) as usize; + match op["op"].as_str() { + Some("activate") => { + m.activate(sel, i, op["confirm"].as_bool().unwrap_or(false)); + } + Some("up") => { + m.move_by(sel, i, true); + } + Some("down") => { + m.move_by(sel, i, false); + } + _ => return Err(format!("unknown op {op}").into()), + } + } + steps.push(lists(&m)); + } + writeln!(out, "{}", json!({"steps": steps, "committed": m.commit()}))?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index fe438915d..85ff5f508 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -57,28 +57,19 @@ impl Game<'_> { /// PackSelectionModel: available (unselected) and selected (top first). pub(super) fn refresh_pack_lists(&mut self) { let all = packs::discover(&self.vanilla_root(), &packs_dir()); - let selected_ids = &self.settings.resource_packs; - let mut selected: Vec = selected_ids - .iter() - .rev() - .filter_map(|id| { - if id == "vanilla" { - Some(vanilla_entry()) - } else { - all.iter().find(|p| &p.id == id).map(entry) - } - }) - .collect(); - if !selected.iter().any(|p| p.id == "vanilla") { - selected.push(vanilla_entry()); - } - let available = all - .iter() - .filter(|p| !selected_ids.contains(&p.id)) - .map(entry) - .collect(); - self.ui.options.available = available; - self.ui.options.selected = selected; + let mut choices = vec![packs::Selectable::vanilla()]; + choices.extend( + all.iter() + .map(|p| packs::Selectable::optional(&p.id, p.compatible)), + ); + let model = packs::SelectionModel::new(choices, &self.settings.resource_packs); + let mut entries: Vec = all.iter().map(entry).collect(); + entries.push(vanilla_entry()); + let o = &mut self.ui.options; + o.available = entries; + o.selected = Vec::new(); + o.pack_model = model; + o.sync_pack_lists(); } /// Rebuild the overlay and reload what can change while running. pub(super) fn reload_packs(&mut self) { diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index a934e287e..b65cb8904 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -617,6 +617,8 @@ pub struct OptionsUi { /// Packs: (available, selected top-first). pub available: Vec, pub selected: Vec, + /// The selection logic behind the two lists (`PackSelectionModel`). + pub pack_model: crate::packs::SelectionModel, packs_changed: bool, pub in_world: bool, /// Scroll the selected language into the middle on the next layout. @@ -636,6 +638,7 @@ impl Default for OptionsUi { language_search: search, available: Vec::new(), selected: Vec::new(), + pack_model: Default::default(), packs_changed: false, in_world: false, center_language: false, @@ -1586,31 +1589,21 @@ impl OptionsUi { index, .. } => { - if pack.required { - continue; - } + let _ = pack; + // TransferableSelectionList.PackEntry.mouseClicked: the + // right quarters of a selected pack's icon move it, the + // icon otherwise selects or unselects it. let on_icon = x < wd.x + 34.0; - if selected && on_icon && x >= wd.x + 18.0 { - // Right half of the icon: move up (top) or down (bottom). - let up = y < wd.y + 18.0; - let target = if up { - index.checked_sub(1) - } else { - Some(index + 1) - }; - if let Some(t) = target - .filter(|t| *t < self.selected.len() && !self.selected[*t].required) - { - self.selected.swap(index, t); - self.packs_changed = true; - } - } else if selected { - let p = self.selected.remove(index); - self.available.insert(0, p); - self.packs_changed = true; + let m = &mut self.pack_model; + let changed = if selected && on_icon && x >= wd.x + 18.0 { + m.move_by(true, index, y < wd.y + 18.0) } else { - let p = self.available.remove(index); - self.selected.insert(0, p); + // No confirmation screen yet: an incompatible pack + // is selected as if its warning were accepted. + m.activate(selected, index, true) + }; + if changed { + self.sync_pack_lists(); self.packs_changed = true; } } @@ -1620,6 +1613,21 @@ impl OptionsUi { } events } + /// Orders the two entry lists as the selection model has them. + pub fn sync_pack_lists(&mut self) { + let all: Vec = self + .available + .drain(..) + .chain(self.selected.drain(..)) + .collect(); + let pick = |ids: &[crate::packs::Selectable]| -> Vec { + ids.iter() + .filter_map(|s| all.iter().find(|e| e.id == s.id).cloned()) + .collect() + }; + self.available = pick(&self.pack_model.unselected); + self.selected = pick(&self.pack_model.selected); + } pub fn release(&mut self) { self.dragging = None; } @@ -1643,11 +1651,8 @@ impl OptionsUi { } } Page::Packs if self.packs_changed => { - let mut ids: Vec = - self.selected.iter().rev().map(|p| p.id.clone()).collect(); - if !ids.contains(&"vanilla".to_owned()) { - ids.insert(0, "vanilla".into()); - } + // PackSelectionModel.commit: bottom first, required packs kept. + let ids = self.pack_model.commit(); s.resource_packs = ids.clone(); events.push(Event::Packs(ids)); } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index b5205922b..1e0c35358 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -418,6 +418,187 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { } } +/// `Pack.Position`: where a pack goes when it is added to a list. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Position { + Top, + Bottom, +} +/// A pack as the selection sees it (`PackSelectionConfig` and its +/// compatibility). +#[derive(Clone, Debug, PartialEq)] +pub struct Selectable { + pub id: String, + pub required: bool, + pub position: Position, + pub fixed: bool, + pub compatible: bool, +} +impl Selectable { + /// A pack from `resourcepacks/` or a built-in optional one: not + /// required, added on top, free to move (`FolderRepositorySource`). + pub fn optional(id: &str, compatible: bool) -> Self { + Self { + id: id.to_owned(), + required: false, + position: Position::Top, + fixed: false, + compatible, + } + } + /// The vanilla pack: required, at the bottom (`BuiltInPackSource`). + pub fn vanilla() -> Self { + Self { + id: "vanilla".into(), + required: true, + position: Position::Bottom, + fixed: false, + compatible: true, + } + } +} + +/// `Pack.Position.insert`: below or above the packs fixed at that end. +fn insert(list: &mut Vec, pack: Selectable, reverse: bool) { + let own = pack.position; + let side = match (own, reverse) { + (Position::Top, false) | (Position::Bottom, true) => Position::Top, + _ => Position::Bottom, + }; + let pinned = |p: &Selectable| p.fixed && p.position == own; + if side == Position::Bottom { + let i = list.iter().take_while(|p| pinned(p)).count(); + list.insert(i, pack); + } else { + let i = list.len() - list.iter().rev().take_while(|p| pinned(p)).count(); + list.insert(i, pack); + } +} + +/// `PackSelectionModel` over a `PackRepository`: the packs not selected +/// (in id order) and the selected ones, top first, as the pack screen's two +/// lists show them. +#[derive(Clone, Debug, Default)] +pub struct SelectionModel { + available: Vec, + pub unselected: Vec, + pub selected: Vec, +} +impl SelectionModel { + /// `available` in any order; `selected` as options.txt lists them, + /// bottom first. + pub fn new(mut available: Vec, selected: &[String]) -> Self { + // PackRepository.available is a TreeMap by id (String.compareTo). + available.sort_by(|a, b| a.id.encode_utf16().cmp(b.id.encode_utf16())); + available.dedup_by(|a, b| a.id == b.id); + let mut m = Self { + available, + ..Self::default() + }; + let mut chosen = m.rebuild(selected); + chosen.reverse(); + m.unselected = m + .available + .iter() + .filter(|p| !chosen.iter().any(|c| c.id == p.id)) + .cloned() + .collect(); + m.selected = chosen; + m + } + /// `PackRepository.rebuildSelected`: the named packs that exist, and + /// every required one. + fn rebuild(&self, ids: &[String]) -> Vec { + let mut out: Vec = ids + .iter() + .filter_map(|id| self.available.iter().find(|p| p.id == *id).cloned()) + .collect(); + for p in &self.available { + if p.required && !out.iter().any(|o| o.id == p.id) { + insert(&mut out, p.clone(), false); + } + } + out + } + fn list(&self, selected: bool) -> &Vec { + if selected { + &self.selected + } else { + &self.unselected + } + } + pub fn can_select(&self, selected: bool, _: usize) -> bool { + !selected + } + pub fn can_unselect(&self, selected: bool, i: usize) -> bool { + selected && !self.selected[i].required + } + pub fn can_move_up(&self, selected: bool, i: usize) -> bool { + i > 0 && !self.list(selected)[i - 1].fixed + } + pub fn can_move_down(&self, selected: bool, i: usize) -> bool { + let list = self.list(selected); + i + 1 < list.len() && !list[i + 1].fixed + } + /// `EntryBase.toggleSelection`: to the other list, at its default + /// position (from the other end). + fn toggle(&mut self, selected: bool, i: usize) { + let (from, to) = if selected { + (&mut self.selected, &mut self.unselected) + } else { + (&mut self.unselected, &mut self.selected) + }; + let p = from.remove(i); + insert(to, p, true); + } + /// `PackEntry`'s activation (a click on the icon, or the select key): + /// select, an incompatible pack only once its confirmation was + /// accepted, or else unselect. True when the lists changed. + pub fn activate(&mut self, selected: bool, i: usize, confirmed: bool) -> bool { + if self.can_select(selected, i) { + if self.unselected[i].compatible || confirmed { + self.toggle(false, i); + return true; + } + false + } else if self.can_unselect(selected, i) { + self.toggle(true, i); + true + } else { + false + } + } + /// Whether activating the entry asks first (`handlePackSelection`'s + /// ConfirmScreen for an incompatible pack). + pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool { + self.can_select(selected, i) && !self.unselected[i].compatible + } + /// `moveUp` / `moveDown` when allowed. + pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool { + let ok = if up { + self.can_move_up(selected, i) + } else { + self.can_move_down(selected, i) + }; + if ok { + let list = if selected { + &mut self.selected + } else { + &mut self.unselected + }; + let p = list.remove(i); + list.insert(if up { i - 1 } else { i + 1 }, p); + } + ok + } + /// `commit`: the repository's selection, bottom first, as options.txt + /// stores it. + pub fn commit(&self) -> Vec { + let ids: Vec = self.selected.iter().rev().map(|p| p.id.clone()).collect(); + self.rebuild(&ids).into_iter().map(|p| p.id).collect() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java new file mode 100644 index 000000000..6d0cbe30f --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java @@ -0,0 +1,111 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.screens.packs.PackSelectionModel; +import net.minecraft.network.chat.Component; +import net.minecraft.server.packs.PackLocationInfo; +import net.minecraft.server.packs.PackSelectionConfig; +import net.minecraft.server.packs.repository.Pack; +import net.minecraft.server.packs.repository.PackCompatibility; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.PackSource; +import net.minecraft.world.flag.FeatureFlagSet; + +/** + * Runs the resource pack screen's selection logic: a PackRepository of the + * case's packs (required, default position, fixed position, compatibility) + * with an initial selection, a PackSelectionModel over it, and the actions + * TransferableSelectionList.PackEntry performs on a click or key press: + * select (an incompatible pack only once its ConfirmScreen is accepted), + * unselect, move up, move down. After each action: both lists and every + * entry's canSelect, canUnselect, canMoveUp and canMoveDown; at the end the + * repository's selection after commit. + * + * Input lines: case JSON. Output lines: {steps:[...], committed:[...]} or {error}. + */ +public final class VanillaPackSelectionOracle { + static JsonObject lists(PackSelectionModel model) { + var o = new JsonObject(); + for (String side : new String[] {"unselected", "selected"}) { + var a = new JsonArray(); + var entries = side.equals("selected") ? model.getSelected().toList() : model.getUnselected().toList(); + for (var e : entries) { + var row = new JsonArray(); + row.add(e.getId()); + row.add((e.canSelect() ? "s" : "") + (e.canUnselect() ? "u" : "") + (e.canMoveUp() ? "^" : "") + (e.canMoveDown() ? "v" : "")); + a.add(row); + } + o.add(side, a); + } + return o; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + JsonObject c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + try { + List packs = new ArrayList<>(); + for (var p : c.getAsJsonArray("packs")) { + var o = p.getAsJsonObject(); + String id = o.get("id").getAsString(); + var location = new PackLocationInfo(id, Component.literal(id), PackSource.DEFAULT, Optional.empty()); + var compatibility = switch (o.get("compat").getAsString()) { + case "old" -> PackCompatibility.TOO_OLD; + case "new" -> PackCompatibility.TOO_NEW; + default -> PackCompatibility.COMPATIBLE; + }; + var metadata = new Pack.Metadata(Component.literal(id), compatibility, FeatureFlagSet.of(), List.of()); + var config = new PackSelectionConfig(o.get("required").getAsBoolean(), + o.get("position").getAsString().equals("top") ? Pack.Position.TOP : Pack.Position.BOTTOM, o.get("fixed").getAsBoolean()); + packs.add(new Pack(location, null, metadata, config)); + } + var repository = new PackRepository(consumer -> packs.forEach(consumer)); + repository.reload(); + List initial = new ArrayList<>(); + for (var s : c.getAsJsonArray("selected")) initial.add(s.getAsString()); + repository.setSelected(initial); + var model = new PackSelectionModel(e -> { }, p -> null, repository, r -> { }); + var steps = new JsonArray(); + steps.add(lists(model)); + for (var step : c.getAsJsonArray("ops")) { + var o = step.getAsJsonObject(); + var entries = o.get("list").getAsString().equals("selected") ? model.getSelected().toList() : model.getUnselected().toList(); + if (!entries.isEmpty()) { + var e = entries.get(Math.floorMod(o.get("index").getAsInt(), entries.size())); + switch (o.get("op").getAsString()) { + // PackEntry.keyPressed(select) / a click on the icon: handlePackSelection or unselect. + case "activate" -> { + if (e.canSelect()) { + if (e.getCompatibility().isCompatible() || o.get("confirm").getAsBoolean()) e.select(); + } else if (e.canUnselect()) { + e.unselect(); + } + } + case "up" -> { if (e.canMoveUp()) e.moveUp(); } + case "down" -> { if (e.canMoveDown()) e.moveDown(); } + default -> throw new IllegalArgumentException(o.toString()); + } + } + steps.add(lists(model)); + } + result.add("steps", steps); + model.commit(); + var committed = new JsonArray(); + for (var p : repository.getSelectedPacks()) committed.add(p.getId()); + result.add("committed", committed); + } catch (Throwable error) { + result.addProperty("error", String.valueOf(error)); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py new file mode 100644 index 000000000..8610d85f3 --- /dev/null +++ b/tools/test_pack_selection_parity.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Compare the resource pack screen's selection with the vanilla client's. + +Each case is a pack repository (packs required or not, added at the top or +the bottom, fixed in place or not, compatible, too old or too new), an +initial selection as options.txt stores it, and the actions the screen's +entries take on a click or key press: select (an incompatible pack only when +its confirmation is accepted), unselect, move up, move down. The Java oracle +(VanillaPackSelectionOracle) runs vanilla's PackRepository and +PackSelectionModel; examples/pack_selection_fixture runs +horizon_client::packs::SelectionModel, which the game's pack screen uses. +After every action both lists, in order, with each entry's canSelect, +canUnselect, canMoveUp and canMoveDown, and the selection committed at the +end must agree. + + test_pack_selection_parity.py [--count N] [--detail N] +""" +import argparse +import json +import os +import random +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab + import test_rust_parity as base + import test_model_baking_parity as baking + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +IDS = ['vanilla', 'programmer_art', 'file/Faithful.zip', 'file/alpha', 'file/Zeta pack', 'file/zeta', 'file/é', + 'file/0', 'server', 'world', 'fabric', 'file/a.zip', 'file/A.zip', 'file/b'] + + +def cases(count): + rng = random.Random(0x5041434B) + out = [] + for _ in range(count): + ids = rng.sample(IDS, rng.randint(1, 9)) + packs = [{'id': i, 'required': rng.random() < 0.2, 'position': rng.choice(['top', 'top', 'bottom']), + 'fixed': rng.random() < 0.2, 'compat': rng.choice(['compatible'] * 4 + ['old', 'new'])} for i in ids] + selected = rng.sample(ids + ['file/missing'], rng.randint(0, len(ids))) + ops = [{'list': rng.choice(['selected', 'unselected']), 'index': rng.randint(-2, 8), + 'op': rng.choice(['activate', 'activate', 'up', 'down']), 'confirm': rng.random() < 0.5} + for _ in range(rng.randint(0, 16))] + out.append({'packs': packs, 'selected': selected, 'ops': ops}) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=4000) + parser.add_argument('--detail', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-pack-selection-parity'; build.mkdir(parents=True, exist_ok=True) + chosen = cases(args.count) + inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + classes = build / 'classes'; classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', + inputs, build / 'vanilla.jsonl'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'pack_selection_fixture', '--', + inputs, build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust) == len(chosen) + errors = [v['error'] for v in vanilla if 'error' in v] + bad = [(c, v, r) for c, v, r in zip(chosen, vanilla, rust) if 'error' not in v and v != r] + for e in sorted(set(errors))[:5]: + print('ORACLE ERROR', e) + for c, v, r in bad[:args.detail]: + print('MISMATCH', json.dumps(c)) + step = next((i for i, (a, b) in enumerate(zip(v['steps'], r['steps'])) if a != b), None) + if step is None: + print(f' committed: vanilla {v["committed"]} | horizon {r["committed"]}') + else: + print(f' after action {step}: vanilla {v["steps"][step]}\n horizon {r["steps"][step]}') + steps = sum(len(v.get('steps', [])) for v in vanilla) + print(f'{len(chosen) - len(bad) - len(errors)}/{len(chosen)} pack selections match ({steps} states); {len(errors)} oracle errors') + if bad or errors: + sys.exit(1) + print('pack selection parity ok') + + +if __name__ == '__main__': + main()