diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index d99f32f24..4ab0a5189 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -568,6 +568,22 @@ impl Game<'_> { "generate_structures": options.structures, "bonus_chest": options.bonus_chest(), }), + Mode::CreateFlat { + name, + seed, + options, + flat, + .. + } => json!({ + "mode": "customize-flat", + "fields": { "name": name, "seed": seed }, + "superflat": options.flat, + "biome": flat.settings().biome, + "layers": flat.settings().layers.iter().map(|layer| json!({ + "block": layer.block, + "height": layer.height, + })).collect::>(), + }), Mode::Edit { world, name, diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 454f9f2eb..d7c4f2b03 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -93,7 +93,12 @@ impl WorldRequest { level.hardcore = o.hardcore; level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); level.allow_commands = Some(o.commands(creative)); - horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + horizon_client::save::write_world_gen_settings_with( + &save_root, + level.seed, + o.world_gen(), + o.flat_settings(), + )?; // WorldCreationUiState.getGameRules, written with the level. level.game_rules = o.rules.by_name(); } diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 9984cdcdf..b2fcfe8f4 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -14,10 +14,12 @@ use std::{ }; mod create_world; +mod flat; #[cfg(test)] mod tests; pub mod world_management; pub use create_world::{DIFFICULTIES, WorldOptions}; +pub use flat::{FlatLayer, FlatSettings, State as FlatEditor}; /// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. const LIST_TOP: f32 = 49.0; @@ -102,6 +104,16 @@ pub enum Mode { return_to: Box, }, Multiplayer(crate::multiplayer::Screen), + /// CreateFlatWorldScreen over Create New World: the fields that screen + /// keeps and the superflat editor on top of them. + CreateFlat { + name: String, + seed: String, + creative: bool, + focus: u8, + options: WorldOptions, + flat: flat::State, + }, } #[derive(Clone, Debug, PartialEq)] pub enum Action { @@ -129,6 +141,8 @@ pub struct Title { /// Direct Connection's address, synchronized with `options.txt`'s `lastServer`. pub last_server: String, pub saves: PathBuf, + /// The prepared resource root: the flat preset list and block registry. + resources: PathBuf, pub started: std::time::Instant, search: String, search_focused: bool, @@ -234,6 +248,7 @@ impl Title { mode, last_server: String::new(), saves, + resources: resources.to_owned(), started: now, search: String::new(), search_focused: false, @@ -320,6 +335,64 @@ impl Title { self.return_to_list(None); } } + /// A press on the superflat screens: their list, share box or buttons. + fn flat_click(&mut self, x: f32, y: f32, size: (f32, f32), hit: Option) { + match hit { + Some(70) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.remove_selected(); + } + } + Some(71) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.open_presets(); + } + } + Some(72) => self.close_flat(true), + Some(73) => self.close_flat(false), + Some(74) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.apply_share(); + } + } + Some(75) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.back_to_layers(); + } + } + None => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::click(flat, (x, y), size); + } + } + _ => {} + } + } + /// Return to Create New World, keeping (`apply`) or dropping the layers. + fn close_flat(&mut self, apply: bool) { + let mode = std::mem::replace(&mut self.mode, Mode::Main); + if let Mode::CreateFlat { + name, + seed, + creative, + focus, + mut options, + flat, + } = mode + { + if apply { + options.flat = true; + options.flat_settings = Some(flat.settings); + } + self.mode = Mode::Create { + name, + seed, + creative, + focus, + options, + }; + } + } fn matches_search(&self, world: &WorldEntry) -> bool { let filter = self.search.to_lowercase(); world.name.to_lowercase().contains(&filter) || world.folder.to_lowercase().contains(&filter) @@ -370,6 +443,10 @@ impl Title { if let Mode::Multiplayer(screen) = &mut self.mode { return screen.drag(cursor.1, size); } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::drag(flat, cursor, size); + return; + } if let Mode::Select { worlds, .. } = &self.mode { let (top, bottom, _, content) = self.world_list(worlds, size); let mut scroll = self.scroll.get(); @@ -385,6 +462,9 @@ impl Title { if let Mode::Multiplayer(screen) = &mut self.mode { screen.release(); } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::release(flat); + } self.scroll.get_mut().release(); } /// Mouse wheel over the classic world and server lists. @@ -396,6 +476,10 @@ impl Title { screen.wheel(delta, cursor, size); return; } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::wheel(flat, delta, cursor, size); + return; + } let Mode::Select { worlds, .. } = &self.mode else { return; }; @@ -720,6 +804,7 @@ impl Title { Mode::Create { creative, options, .. } => create_world::buttons(w, h, *creative, options), + Mode::CreateFlat { flat, .. } => flat::buttons(w, h, flat), Mode::Edit { world, name, .. } => { let x = (w / 2.0).floor() - 100.0; let top = edit_top(h); @@ -1042,6 +1127,7 @@ impl Title { options, .. } => self.draw_create(atlas, batch, cursor, name, seed, *focus, options), + Mode::CreateFlat { flat, .. } => flat::draw(self, atlas, batch, cursor, flat), Mode::Edit { name, focused, .. } => { crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); centered( @@ -1248,6 +1334,10 @@ impl Title { .into_iter() .find(|b| b.enabled && x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + 20.0) .map(|b| b.id); + if matches!(self.mode, Mode::CreateFlat { .. }) { + self.flat_click(x, y, (w, h), hit); + return (Action::None, hit.is_some()); + } let action = self.click_action(x, y, (w, h), hit); // World list selection is silent; launching its selected entry sounds. let sound = hit.is_some() || matches!(action, Action::Play { .. }); @@ -1416,6 +1506,27 @@ impl Title { *self.rules.get_mut() = Some(RulesScreen::for_creation(&options.rules)); Action::None } + ( + Mode::Create { + name, + seed, + creative, + focus, + options, + }, + Some(26), + ) => { + let flat = flat::State::new(&self.resources, options.flat_settings.clone()); + self.mode = Mode::CreateFlat { + name: name.clone(), + seed: seed.clone(), + creative: *creative, + focus: *focus, + options: options.clone(), + flat, + }; + Action::None + } ( Mode::Create { creative, options, .. @@ -1669,6 +1780,16 @@ impl Title { self.return_to_list(Some(&folder)); } Mode::Error { return_to, .. } => self.mode = *return_to.clone(), + Mode::CreateFlat { .. } => { + if matches!(&self.mode, Mode::CreateFlat { flat, .. } if flat.page == flat::Page::Presets) + { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.back_to_layers(); + } + } else { + self.close_flat(false); + } + } Mode::Create { .. } => self.cancel_create(), _ => self.mode = Mode::Main, } @@ -1697,6 +1818,7 @@ const SEARCH: crate::clipboard::FieldId = ("world.search", 0); const EDIT_NAME: crate::clipboard::FieldId = ("world.edit-name", 0); const WORLD_NAME: crate::clipboard::FieldId = ("world.name", 0); const WORLD_SEED: crate::clipboard::FieldId = ("world.seed", 0); +const FLAT_SHARE: crate::clipboard::FieldId = ("world.flat-share", 0); /// The focused field of the world screens and the server screens: the list's /// search, a world name or seed, or Add Server, Direct Connection and Join a /// Friend. @@ -1720,6 +1842,9 @@ fn caret_field<'a>( _ => None, }, Mode::Multiplayer(screen) => screen.focused_text(), + Mode::CreateFlat { flat, .. } if flat.page == flat::Page::Presets && flat.share_focused => { + Some((FLAT_SHARE, &mut flat.share, 1230)) + } _ => None, } } diff --git a/crates/horizon-client/src/title/create_world.rs b/crates/horizon-client/src/title/create_world.rs index 65d4f60ac..c0611f0d5 100644 --- a/crates/horizon-client/src/title/create_world.rs +++ b/crates/horizon-client/src/title/create_world.rs @@ -32,6 +32,8 @@ pub struct WorldOptions { pub commands: Option, /// The Superflat world preset instead of Default. pub flat: bool, + /// CreateFlatWorldScreen's layers and biome, kept with the world type. + pub flat_settings: Option, pub structures: bool, pub bonus_chest: bool, /// `getGameRules`: the Game Rules screen's values, saved with the world. @@ -45,6 +47,7 @@ impl Default for WorldOptions { difficulty: 2, commands: None, flat: false, + flat_settings: None, structures: true, bonus_chest: false, rules: crate::gamerules::GameRules::default(), @@ -67,6 +70,10 @@ impl WorldOptions { .unwrap_or(2), commands: Some(commands), flat: generation.flat, + flat_settings: generation + .flat + .then(|| super::flat::FlatSettings::from_world(dir)) + .flatten(), structures: generation.structures, bonus_chest: generation.bonus_chest, rules: crate::gamerules::GameRules::load(dir), @@ -92,6 +99,12 @@ impl WorldOptions { bonus_chest: self.bonus_chest(), } } + /// The custom layers, as `write_world_gen_settings_with` takes them. + pub fn flat_settings(&self) -> Option { + self.flat_settings + .as_ref() + .map(super::flat::FlatSettings::to_tag) + } /// A press on one of the open tab's cycle buttons or switches. pub(super) fn press(&mut self, id: u8, creative: &mut bool) { match id { @@ -105,7 +118,13 @@ impl WorldOptions { } 23 => self.difficulty = (self.difficulty + 1) % DIFFICULTIES.len(), 24 => self.commands = Some(!self.commands(*creative)), - 25 => self.flat = !self.flat, + 25 => { + self.flat = !self.flat; + if self.flat { + // setWorldType starts the generator from the flat preset. + self.flat_settings = Some(super::flat::FlatSettings::default()); + } + } 27 => self.structures = !self.structures, 28 => self.bonus_chest = !self.bonus_chest, _ => {} @@ -247,13 +266,13 @@ pub(super) fn buttons(w: f32, h: f32, creative: bool, o: &WorldOptions) -> Vec, + pub structure_overrides: Vec, +} +impl Default for FlatSettings { + fn default() -> Self { + // worldgen/world_preset/flat.json's overworld. + Self { + biome: "minecraft:plains".into(), + features: false, + lakes: false, + layers: vec![ + FlatLayer { + block: "minecraft:bedrock".into(), + height: 1, + }, + FlatLayer { + block: "minecraft:dirt".into(), + height: 2, + }, + FlatLayer { + block: "minecraft:grass_block".into(), + height: 1, + }, + ], + structure_overrides: vec!["minecraft:strongholds".into(), "minecraft:villages".into()], + } + } +} +impl FlatSettings { + /// A saved world's flat generator settings, for Re-Create. + pub fn from_world(dir: &Path) -> Option { + let settings = crate::save::world_gen_settings(dir)?; + let generator = settings + .get("dimensions")? + .get("minecraft:overworld")? + .get("generator")?; + if crate::save::text(generator.get("type"))?.trim_start_matches("minecraft:") != "flat" { + return None; + } + Self::from_tag(generator.get("settings")?) + } + pub fn from_tag(tag: &Tag) -> Option { + let Some(Tag::List(list)) = tag.get("layers") else { + return None; + }; + let layers: Vec = list + .iter() + .filter_map(|layer| { + Some(FlatLayer { + block: crate::save::text(layer.get("block"))?, + height: crate::save::number(layer.get("height"))?.clamp(0, Y_SIZE as i64) + as i32, + }) + }) + .collect(); + // `layers: []` is a valid void flat world; a list whose entries all + // fail to parse is not. + if layers.is_empty() && !list.is_empty() { + return None; + } + let flag = |key: &str, default: bool| { + crate::save::number(tag.get(key)).map_or(default, |value| value != 0) + }; + let structure_overrides = match tag.get("structure_overrides") { + Some(Tag::String(text)) => vec![text.to_string_lossy()], + Some(Tag::List(list)) => list + .iter() + .filter_map(|value| crate::save::text(Some(value))) + .collect(), + _ => Vec::new(), + }; + Some(Self { + biome: crate::save::text(tag.get("biome")).unwrap_or_else(|| "minecraft:plains".into()), + features: flag("features", false), + lakes: flag("lakes", false), + layers, + structure_overrides, + }) + } + /// FlatLevelGeneratorSettings.CODEC, as world_gen_settings stores it. + pub fn to_tag(&self) -> Tag { + let string = |text: &str| Tag::String(text.into()); + Tag::compound([ + ("biome", string(&self.biome)), + ("features", Tag::Byte(i8::from(self.features))), + ("lakes", Tag::Byte(i8::from(self.lakes))), + ( + "layers", + Tag::List( + self.layers + .iter() + .map(|layer| { + Tag::compound([ + ("block", string(&layer.block)), + ("height", Tag::Int(layer.height)), + ]) + }) + .collect(), + ), + ), + ( + "structure_overrides", + Tag::List( + self.structure_overrides + .iter() + .map(|id| string(id)) + .collect(), + ), + ), + ]) + } + /// `CreateFlatWorldScreen.save`: the text the preset screen shows. + pub fn to_share(&self) -> String { + let layers = self + .layers + .iter() + .map(|layer| { + if layer.height == 1 { + layer.block.clone() + } else { + format!("{}*{}", layer.height, layer.block) + } + }) + .collect::>() + .join(","); + format!("{layers};{}", self.biome) + } + /// `PresetFlatWorldScreen.fromString`: `layers;biome`, keeping the + /// decorations the screen was opened with. `None` for a malformed list, + /// as vanilla falls back to the preset's own settings. + pub fn parse( + text: &str, + blocks: &BTreeSet, + biomes: &BTreeSet, + base: &Self, + ) -> Option { + let (layer_text, biome_text) = text.split_once(';').unwrap_or((text, "")); + let mut layers = Vec::new(); + let mut total = 0; + for part in layer_text.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let (height, block) = match part.split_once('*') { + Some((height, block)) => (height.trim().parse::().ok()?, block.trim()), + None => (1, part), + }; + let block = namespaced(block); + if !blocks.is_empty() && !blocks.contains(&block) { + return None; + } + let height = height.max(0).min(Y_SIZE - total); + if height == 0 { + continue; + } + total += height; + layers.push(FlatLayer { block, height }); + } + if layers.is_empty() { + return None; + } + let mut biome = namespaced(biome_text.trim()); + if biome == "minecraft:" || biome.is_empty() { + biome = "minecraft:plains".into(); + } + if !biomes.is_empty() && !biomes.contains(&biome) { + biome = "minecraft:plains".into(); + } + Some(Self { + biome, + layers, + ..base.clone() + }) + } +} +/// `Identifier.parse`: bare names get the default namespace. +fn namespaced(id: &str) -> String { + if id.is_empty() || id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Page { + Layers, + Presets, +} + +#[derive(Clone, Debug)] +pub struct State { + pub(super) page: Page, + pub(super) settings: FlatSettings, + /// The preset screen's share box (`createWorld.customize.presets.share`). + pub(super) share: String, + pub(super) share_focused: bool, + /// The selected layer, in the list's top-first order. + pub(super) selected: Option, + pub(super) scroll: ui::Scroll, + preset_selected: Option, + preset_scroll: ui::Scroll, + presets: Vec, + blocks: BTreeSet, + biomes: BTreeSet, +} +#[derive(Clone, Debug)] +struct Preset { + id: String, + display: String, + settings: FlatSettings, +} +impl State { + /// The layers the editor holds, for the control socket's state. + pub fn settings(&self) -> &FlatSettings { + &self.settings + } + pub(super) fn new(root: &Path, current: Option) -> Self { + let settings = current.unwrap_or_default(); + let (presets, blocks, biomes) = load(root); + Self { + page: Page::Layers, + share: settings.to_share(), + settings, + share_focused: false, + selected: None, + scroll: ui::Scroll::default(), + preset_selected: None, + preset_scroll: ui::Scroll::default(), + presets, + blocks, + biomes, + } + } + pub(super) fn open_presets(&mut self) { + self.page = Page::Presets; + self.preset_selected = None; + self.preset_scroll = ui::Scroll::default(); + self.share = self.settings.to_share(); + self.share_focused = false; + } + pub(super) fn back_to_layers(&mut self) { + self.page = Page::Layers; + self.share_focused = false; + } + pub(super) fn remove_selected(&mut self) { + let Some(row) = self.selected else { + return; + }; + let index = self.settings.layers.len().wrapping_sub(1 + row); + if index < self.settings.layers.len() { + self.settings.layers.remove(index); + } + self.selected = None; + } + /// PresetFlatWorldScreen's Select: parse the share text into the settings + /// the Create New World screen keeps. + pub(super) fn apply_share(&mut self) { + // PresetFlatWorldScreen keeps the selected preset's decorations while + // the share text supplies its layers and biome. + let base = self + .preset_selected + .and_then(|index| self.presets.get(index)) + .map(|preset| preset.settings.clone()) + .unwrap_or_else(|| self.settings.clone()); + // A malformed list falls back to FlatLevelGeneratorSettings.getDefault. + let settings = + FlatSettings::parse(&self.share, &self.blocks, &self.biomes, &base).unwrap_or_default(); + self.settings = settings; + self.share = self.settings.to_share(); + self.page = Page::Layers; + self.share_focused = false; + self.selected = None; + } + fn select_preset(&mut self, index: usize) { + let Some(preset) = self.presets.get(index) else { + return; + }; + self.preset_selected = Some(index); + self.share = preset.settings.to_share(); + self.share_focused = false; + } + fn selecting(&self) -> Option { + self.preset_selected + } +} + +/// `/data//worldgen/flat_level_generator_preset/.json`, +/// in the order of the `visible` tag, plus the block and biome ids the share +/// text is checked against. +fn load(root: &Path) -> (Vec, BTreeSet, BTreeSet) { + let mut presets = Vec::new(); + let tag_path = + root.join("data/minecraft/tags/worldgen/flat_level_generator_preset/visible.json"); + if let Ok(text) = std::fs::read_to_string(tag_path) + && let Ok(Value::Object(tag)) = serde_json::from_str(&text) + && let Some(Value::Array(ids)) = tag.get("values") + { + for id in ids.iter().filter_map(Value::as_str) { + let Some((namespace, path)) = id.split_once(':') else { + continue; + }; + let path = root.join(format!( + "data/{namespace}/worldgen/flat_level_generator_preset/{path}.json" + )); + let Ok(text) = std::fs::read_to_string(path) else { + continue; + }; + let Ok(value) = serde_json::from_str::(&text) else { + continue; + }; + let Some(settings) = preset_settings(&value) else { + continue; + }; + presets.push(Preset { + id: id.to_owned(), + display: value["display"] + .as_str() + .unwrap_or("minecraft:grass_block") + .to_owned(), + settings, + }); + } + } + let blocks = registry_ids(root, "minecraft:block"); + let biomes = json_keys(&root.join("worldgen/biomes.json")); + (presets, blocks, biomes) +} +fn preset_settings(value: &Value) -> Option { + let settings = value.get("settings")?; + let layers = settings + .get("layers")? + .as_array()? + .iter() + .filter_map(|layer| { + Some(FlatLayer { + block: layer.get("block")?.as_str()?.to_owned(), + height: layer.get("height")?.as_i64()? as i32, + }) + }) + .collect::>(); + if layers.is_empty() { + return None; + } + let structure_overrides = match settings.get("structure_overrides") { + Some(Value::String(id)) => vec![id.clone()], + Some(Value::Array(ids)) => ids + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + }; + Some(FlatSettings { + biome: settings + .get("biome") + .and_then(Value::as_str) + .unwrap_or("minecraft:plains") + .to_owned(), + features: settings + .get("features") + .and_then(Value::as_bool) + .unwrap_or(false), + lakes: settings + .get("lakes") + .and_then(Value::as_bool) + .unwrap_or(false), + layers, + structure_overrides, + }) +} +/// The ids of a registry in the prepared `registries.json`. +fn registry_ids(root: &Path, registry: &str) -> BTreeSet { + let Ok(text) = std::fs::read_to_string(root.join("registries.json")) else { + return BTreeSet::new(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return BTreeSet::new(); + }; + value + .get(registry) + .and_then(|registry| registry.get("entries")) + .and_then(Value::as_object) + .map(|entries| entries.keys().cloned().collect()) + .unwrap_or_default() +} +fn json_keys(path: &Path) -> BTreeSet { + let Ok(text) = std::fs::read_to_string(path) else { + return BTreeSet::new(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return BTreeSet::new(); + }; + value + .as_object() + .map(|entries| entries.keys().cloned().collect()) + .unwrap_or_default() +} + +/// CreateFlatWorldScreen's list and the preset screen's list. +fn list_area(state: &State, size: (f32, f32)) -> (f32, f32, f32, f32) { + let (w, h) = (size.0.ceil(), size.1.ceil()); + let (top, bottom) = match state.page { + Page::Layers => (43.0, h - 60.0), + Page::Presets => (80.0, h - 37.0), + }; + let left = ((w - ROW_WIDTH) * 0.5).floor(); + let rows = match state.page { + Page::Layers => HEADER + state.settings.layers.len() as f32 * LAYER_ROW + 4.0, + Page::Presets => state.presets.len() as f32 * PRESET_ROW + 4.0, + }; + (top, bottom, left, rows) +} + +pub(super) fn buttons(w: f32, h: f32, state: &State) -> Vec