b99de58761
A world can now be opened to the local network from World Options in the pause menu (LAN on or off, port, command access, forcing the game mode, plus the default and personal game mode, cheats and difficulty), or with horizon-ctl lan open. The hosted world runs a server inside the game that speaks the vanilla 26.3 protocol: server list status, offline-mode login, the configuration phase with the synchronized registries and tags (sent as known-pack references to vanilla clients and in full to clients that know no packs), then the play state with chunks and light, time, weather, the player list, the host and other guests as visible players, mobs and dropped items, block changes, chat and keep-alives. Network I/O runs on its own threads and a world that is not open pays one check per tick. A vanilla 26.3 client and a second Horizon client were verified joining and seeing each other and the terrain. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
283 lines
9.5 KiB
Rust
283 lines
9.5 KiB
Rust
//! What the configuration phase sends: the synchronized registries (names in
|
|
//! network order, with their data for clients that do not know the vanilla
|
|
//! pack) and the tags of every registry, loaded from the prepared resources
|
|
//! (`data/minecraft/...`) and the registries report.
|
|
use horizon_protocol::{
|
|
packets::configuration::{RegistryData, RegistryEntry, RegistryTags, TagEntry, UpdateTags},
|
|
registry::{Builtin, Dynamic},
|
|
};
|
|
use horizon_world::nbt::{JavaString, Tag};
|
|
use serde_json::Value;
|
|
use std::{
|
|
collections::{BTreeMap, HashMap, HashSet},
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
/// RegistryDataLoader.SYNCHRONIZED_REGISTRIES, in vanilla's order.
|
|
pub const SYNCHRONIZED: &[&str] = &[
|
|
"minecraft:worldgen/biome",
|
|
"minecraft:chat_type",
|
|
"minecraft:trim_pattern",
|
|
"minecraft:trim_material",
|
|
"minecraft:wolf_variant",
|
|
"minecraft:wolf_sound_variant",
|
|
"minecraft:pig_variant",
|
|
"minecraft:pig_sound_variant",
|
|
"minecraft:frog_variant",
|
|
"minecraft:cat_variant",
|
|
"minecraft:cat_sound_variant",
|
|
"minecraft:cow_sound_variant",
|
|
"minecraft:cow_variant",
|
|
"minecraft:chicken_sound_variant",
|
|
"minecraft:chicken_variant",
|
|
"minecraft:zombie_nautilus_variant",
|
|
"minecraft:painting_variant",
|
|
"minecraft:sulfur_cube_archetype",
|
|
"minecraft:dimension_type",
|
|
"minecraft:damage_type",
|
|
"minecraft:banner_pattern",
|
|
"minecraft:enchantment",
|
|
"minecraft:jukebox_song",
|
|
"minecraft:instrument",
|
|
"minecraft:test_environment",
|
|
"minecraft:test_instance",
|
|
"minecraft:dialog",
|
|
"minecraft:world_clock",
|
|
"minecraft:timeline",
|
|
"minecraft:decorated_pot_pattern",
|
|
"minecraft:block_transformer",
|
|
"minecraft:worldgen/block_state_provider",
|
|
];
|
|
/// KnownPack.vanilla("core") for this version.
|
|
pub const CORE_PACK: (&str, &str, &str) = ("minecraft", "core", horizon_protocol::GAME_VERSION);
|
|
|
|
/// A data-driven registry: entry names in network order and their JSON.
|
|
struct Entries {
|
|
names: Vec<String>,
|
|
json: Vec<Value>,
|
|
}
|
|
|
|
pub struct SyncData {
|
|
pub builtin: Builtin,
|
|
/// Entry names per synchronized registry (for id lookups).
|
|
pub dynamic: Dynamic,
|
|
registries: Vec<(String, Entries)>,
|
|
pub tags: UpdateTags,
|
|
pub features: Vec<String>,
|
|
}
|
|
|
|
/// Every `*.json` under `dir`, as (path without extension relative to dir, value), sorted.
|
|
fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap<String, Value>) {
|
|
let Ok(read) = std::fs::read_dir(dir) else {
|
|
return;
|
|
};
|
|
for entry in read.flatten() {
|
|
let path = entry.path();
|
|
let name = entry.file_name().to_string_lossy().into_owned();
|
|
if path.is_dir() {
|
|
walk(&path, &format!("{prefix}{name}/"), out);
|
|
} else if let Some(stem) = name.strip_suffix(".json")
|
|
&& let Ok(text) = std::fs::read_to_string(&path)
|
|
&& let Ok(value) = serde_json::from_str::<Value>(&text)
|
|
{
|
|
out.insert(format!("{prefix}{stem}"), value);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A JSON value as the NBT that vanilla's NbtOps would produce from the codec
|
|
/// (integers are ints, other numbers doubles, booleans bytes).
|
|
pub fn json_to_nbt(v: &Value) -> Tag {
|
|
match v {
|
|
Value::Null => Tag::compound(Vec::<(&str, Tag)>::new()),
|
|
Value::Bool(b) => Tag::Byte(i8::from(*b)),
|
|
Value::Number(n) => match n.as_i64() {
|
|
Some(i) => match i32::try_from(i) {
|
|
Ok(i) => Tag::Int(i),
|
|
Err(_) => Tag::Long(i),
|
|
},
|
|
None => Tag::Double(n.as_f64().unwrap_or(0.0).to_bits()),
|
|
},
|
|
Value::String(s) => Tag::String(JavaString::from(s.as_str())),
|
|
Value::Array(a) => Tag::List(a.iter().map(json_to_nbt).collect()),
|
|
Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), json_to_nbt(v)))),
|
|
}
|
|
}
|
|
|
|
impl SyncData {
|
|
pub fn load(resources: &Path) -> Result<Self, String> {
|
|
let builtin = Builtin::find(resources)
|
|
.and_then(|p| Builtin::load(&p).ok())
|
|
.ok_or("registries.json not found next to the resources")?;
|
|
let root: PathBuf = resources.join("data/minecraft");
|
|
let mut registries = Vec::new();
|
|
let mut dynamic = Dynamic::default();
|
|
for key in SYNCHRONIZED {
|
|
let path = key.trim_start_matches("minecraft:");
|
|
let mut found = BTreeMap::new();
|
|
walk(&root.join(path), "", &mut found);
|
|
let (names, json): (Vec<_>, Vec<_>) = found
|
|
.into_iter()
|
|
.map(|(n, v)| (format!("minecraft:{n}"), v))
|
|
.unzip();
|
|
dynamic.registries.insert(
|
|
(*key).to_owned(),
|
|
names.iter().map(|n| (n.clone(), None)).collect(),
|
|
);
|
|
registries.push(((*key).to_owned(), Entries { names, json }));
|
|
}
|
|
let tags = Self::load_tags(&root, &builtin, &dynamic);
|
|
Ok(Self {
|
|
builtin,
|
|
dynamic,
|
|
registries,
|
|
tags,
|
|
features: vec!["minecraft:vanilla".to_owned()],
|
|
})
|
|
}
|
|
|
|
/// The id of a name in a built-in or synchronized registry.
|
|
pub fn id(&self, registry: &str, name: &str) -> Option<i32> {
|
|
if let Some(ids) = self.builtin.get(registry) {
|
|
return ids.id(name);
|
|
}
|
|
self.dynamic
|
|
.registries
|
|
.get(registry)?
|
|
.iter()
|
|
.position(|(n, _)| n == name)
|
|
.map(|i| i as i32)
|
|
}
|
|
|
|
/// ClientboundRegistryDataPacket per registry. With `known_pack` the
|
|
/// client rebuilds the entries from its own data, so none is sent.
|
|
pub fn registry_packets(&self, known_pack: bool) -> Vec<RegistryData> {
|
|
self.registries
|
|
.iter()
|
|
.map(|(key, e)| RegistryData {
|
|
registry: key.clone(),
|
|
entries: e
|
|
.names
|
|
.iter()
|
|
.zip(&e.json)
|
|
.map(|(name, json)| RegistryEntry {
|
|
id: name.clone(),
|
|
data: if known_pack {
|
|
None
|
|
} else {
|
|
Some(json_to_nbt(json))
|
|
},
|
|
})
|
|
.collect(),
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn registry_names<'a>(
|
|
builtin: &'a Builtin,
|
|
dynamic: &'a Dynamic,
|
|
key: &str,
|
|
) -> Option<HashMap<&'a str, i32>> {
|
|
if let Some(ids) = builtin.get(key) {
|
|
return Some(
|
|
ids.names
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, n)| (n.as_str(), i as i32))
|
|
.collect(),
|
|
);
|
|
}
|
|
dynamic.registries.get(key).map(|v| {
|
|
v.iter()
|
|
.enumerate()
|
|
.map(|(i, (n, _))| (n.as_str(), i as i32))
|
|
.collect()
|
|
})
|
|
}
|
|
|
|
/// TagNetworkSerialization.serializeTagsToNetwork from the tag files.
|
|
fn load_tags(root: &Path, builtin: &Builtin, dynamic: &Dynamic) -> UpdateTags {
|
|
let tag_root = root.join("tags");
|
|
let mut registries = Vec::new();
|
|
let mut keys: Vec<String> = builtin
|
|
.registries
|
|
.keys()
|
|
.chain(dynamic.registries.keys())
|
|
.cloned()
|
|
.collect();
|
|
keys.sort();
|
|
for key in keys {
|
|
let dir = tag_root.join(key.trim_start_matches("minecraft:"));
|
|
if !dir.is_dir() {
|
|
continue;
|
|
}
|
|
let mut files = BTreeMap::new();
|
|
walk(&dir, "", &mut files);
|
|
if files.is_empty() {
|
|
continue;
|
|
}
|
|
let Some(names) = Self::registry_names(builtin, dynamic, &key) else {
|
|
continue;
|
|
};
|
|
let mut tags = Vec::new();
|
|
for name in files.keys() {
|
|
let mut ids = Vec::new();
|
|
let mut seen = HashSet::new();
|
|
Self::expand(&files, name, &names, &mut ids, &mut seen);
|
|
tags.push(TagEntry {
|
|
name: format!("minecraft:{name}"),
|
|
ids,
|
|
});
|
|
}
|
|
registries.push(RegistryTags {
|
|
registry: key,
|
|
tags,
|
|
});
|
|
}
|
|
UpdateTags { registries }
|
|
}
|
|
|
|
fn expand(
|
|
files: &BTreeMap<String, Value>,
|
|
tag: &str,
|
|
names: &HashMap<&str, i32>,
|
|
out: &mut Vec<i32>,
|
|
seen: &mut HashSet<String>,
|
|
) {
|
|
if !seen.insert(tag.to_owned()) {
|
|
return;
|
|
}
|
|
let Some(values) = files.get(tag).and_then(|v| v["values"].as_array()) else {
|
|
return;
|
|
};
|
|
for value in values {
|
|
let id = value
|
|
.as_str()
|
|
.or_else(|| value["id"].as_str())
|
|
.unwrap_or_default();
|
|
if let Some(reference) = id.strip_prefix('#') {
|
|
let reference = reference.trim_start_matches("minecraft:");
|
|
Self::expand(files, reference, names, out, seen);
|
|
} else if let Some(&n) = names.get(id)
|
|
&& !out.contains(&n)
|
|
{
|
|
out.push(n);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn json_becomes_nbt() {
|
|
let v: Value = serde_json::from_str(r#"{"a":1,"b":[true,2.5],"c":"x"}"#).unwrap();
|
|
let t = json_to_nbt(&v);
|
|
assert!(matches!(t.get("a"), Some(Tag::Int(1))));
|
|
assert!(matches!(t.get("c"), Some(Tag::String(_))));
|
|
assert!(matches!(t.get("b"), Some(Tag::List(l)) if l.len() == 2));
|
|
}
|
|
}
|