WIP: playable client — streaming world, lighting, HUD, crafting, saves, audio, items

Checkpoint of the playable client rewrite before build verification.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-07 23:24:03 +02:00
parent 8982a14485
commit 3777c9009b
40 changed files with 8029 additions and 1804 deletions
+2
View File
@@ -17,3 +17,5 @@ bytemuck = { version = "1.24", features = ["derive"] }
glam = "0.30"
png = "0.18"
serde_json = { version = "1.0.151", features = ["raw_value"] }
cpal = "0.16"
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
+12
View File
@@ -60,6 +60,8 @@ pub struct Assets {
pub model_placements: Vec<(horizon_core::position::BlockPos, BlockStateId)>,
pub model_gallery: Vec<Value>,
pub animations: Vec<crate::sprites::SpriteAnimation>,
pub sprite_layers: std::collections::BTreeMap<String, u32>,
pub translucent_layers: Vec<bool>,
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
@@ -177,6 +179,14 @@ impl Assets {
sprites.insert(root, &format!("minecraft:block/{name}"))?;
}
let models = crate::models::prepare(root, &registry, &mut sprites)?;
// Fluids are drawn by the fluid renderer, not block models; breaking
// progress uses the destroy-stage overlays.
for name in ["water_still", "water_flow", "water_overlay", "lava_still", "lava_flow"] {
sprites.insert(root, &format!("minecraft:block/{name}"))?;
}
for stage in 0..10 {
sprites.insert(root, &format!("minecraft:block/destroy_stage_{stage}"))?;
}
Ok(Self {
registry,
properties,
@@ -188,6 +198,8 @@ impl Assets {
model_placements: models.placements,
model_gallery: models.states,
animations: sprites.animations,
sprite_layers: sprites.layers,
translucent_layers: sprites.translucent,
})
}
}
+247
View File
@@ -0,0 +1,247 @@
//! Sound playback: `sounds.json` events with weighted variants, Ogg/Vorbis
//! decoding, and a small mixer with vanilla's linear distance attenuation
//! (`SoundInstance.Attenuation.LINEAR`, default range 16 blocks) and stereo panning.
use crate::Result;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use serde_json::Value;
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
#[derive(Clone, Debug)]
struct Variant {
name: String,
volume: f32,
pitch: f32,
weight: u32,
attenuation: f32,
is_event: bool,
}
struct Voice {
samples: Arc<Vec<f32>>,
position: f64,
step: f64,
left: f32,
right: f32,
}
#[derive(Default)]
struct Mixer {
voices: Vec<Voice>,
}
pub struct Audio {
_stream: Option<cpal::Stream>,
mixer: Arc<Mutex<Mixer>>,
rate: u32,
root: PathBuf,
events: HashMap<String, Vec<Variant>>,
cache: HashMap<String, Option<(Arc<Vec<f32>>, u32)>>,
seed: u64,
pub listener: [f64; 3],
pub listener_yaw: f32,
pub master: f32,
}
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
use symphonia::core::{
audio::SampleBuffer, codecs::DecoderOptions, formats::FormatOptions, io::MediaSourceStream,
meta::MetadataOptions, probe::Hint,
};
let file = fs::File::open(path).ok()?;
let stream = MediaSourceStream::new(Box::new(file), Default::default());
let mut hint = Hint::new();
hint.with_extension("ogg");
let probed = symphonia::default::get_probe()
.format(&hint, stream, &FormatOptions::default(), &MetadataOptions::default())
.ok()?;
let mut format = probed.format;
let track = format.default_track()?;
let id = track.id;
let rate = track.codec_params.sample_rate?;
let mut decoder = symphonia::default::get_codecs()
.make(&track.codec_params, &DecoderOptions::default())
.ok()?;
let mut mono = Vec::new();
while let Ok(packet) = format.next_packet() {
if packet.track_id() != id {
continue;
}
let Ok(buffer) = decoder.decode(&packet) else { continue };
let spec = *buffer.spec();
let channels = spec.channels.count().max(1);
let mut samples = SampleBuffer::<f32>::new(buffer.capacity() as u64, spec);
samples.copy_interleaved_ref(buffer);
for frame in samples.samples().chunks(channels) {
mono.push(frame.iter().sum::<f32>() / channels as f32);
}
}
Some((mono, rate))
}
impl Audio {
pub fn new(root: &Path) -> Self {
let mut events = HashMap::new();
if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json"))
&& let Ok(Value::Object(map)) = serde_json::from_slice::<Value>(&text)
{
for (name, def) in map {
let variants = def["sounds"]
.as_array()
.into_iter()
.flatten()
.map(|s| match s {
Value::String(n) => Variant {
name: n.clone(),
volume: 1.0,
pitch: 1.0,
weight: 1,
attenuation: 16.0,
is_event: false,
},
_ => Variant {
name: s["name"].as_str().unwrap_or("").to_owned(),
volume: s["volume"].as_f64().unwrap_or(1.0) as f32,
pitch: s["pitch"].as_f64().unwrap_or(1.0) as f32,
weight: s["weight"].as_u64().unwrap_or(1) as u32,
attenuation: s["attenuation_distance"].as_f64().unwrap_or(16.0) as f32,
is_event: s["type"].as_str() == Some("event"),
},
})
.collect::<Vec<_>>();
events.insert(format!("minecraft:{name}"), variants);
}
}
let mixer = Arc::new(Mutex::new(Mixer::default()));
let (stream, rate) = match Self::open(mixer.clone()) {
Ok(v) => (Some(v.0), v.1),
Err(e) => {
eprintln!("Horizon: audio unavailable: {e}");
(None, 48_000)
}
};
Self {
_stream: stream,
mixer,
rate,
root: root.to_owned(),
events,
cache: HashMap::new(),
seed: 0x5DEE_CE66,
listener: [0.0; 3],
listener_yaw: 0.0,
master: 1.0,
}
}
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<(cpal::Stream, u32)> {
let host = cpal::default_host();
let device = host.default_output_device().ok_or("no audio output device")?;
let config = device.default_output_config()?;
let rate = config.sample_rate().0;
let channels = config.channels() as usize;
let stream = device.build_output_stream(
&config.into(),
move |data: &mut [f32], _| {
data.fill(0.0);
let Ok(mut mixer) = mixer.lock() else { return };
for frame in data.chunks_mut(channels) {
let (mut l, mut r) = (0.0f32, 0.0f32);
for v in mixer.voices.iter_mut() {
let i = v.position as usize;
if i + 1 >= v.samples.len() {
continue;
}
let t = (v.position - i as f64) as f32;
let s = v.samples[i] * (1.0 - t) + v.samples[i + 1] * t;
l += s * v.left;
r += s * v.right;
v.position += v.step;
}
if channels >= 2 {
frame[0] = l.clamp(-1.0, 1.0);
frame[1] = r.clamp(-1.0, 1.0);
} else {
frame[0] = ((l + r) / 2.0).clamp(-1.0, 1.0);
}
}
mixer.voices.retain(|v| (v.position as usize) + 1 < v.samples.len());
},
|e| eprintln!("Horizon: audio stream error: {e}"),
None,
)?;
stream.play()?;
Ok((stream, rate))
}
fn random(&mut self) -> u64 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
self.seed
}
fn resolve(&mut self, event: &str, depth: u32) -> Option<Variant> {
let variants = self.events.get(event)?.clone();
let total: u32 = variants.iter().map(|v| v.weight).sum();
if total == 0 {
return None;
}
let mut pick = (self.random() % u64::from(total)) as u32;
let chosen = variants.into_iter().find(|v| {
if pick < v.weight {
true
} else {
pick -= v.weight;
false
}
})?;
if chosen.is_event && depth < 4 {
let name = if chosen.name.contains(':') { chosen.name.clone() } else { format!("minecraft:{}", chosen.name) };
let mut inner = self.resolve(&name, depth + 1)?;
inner.volume *= chosen.volume;
inner.pitch *= chosen.pitch;
return Some(inner);
}
Some(chosen)
}
/// Play a sound event at a world position (None = non-positional UI sound).
pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) {
if self._stream.is_none() {
return;
}
let Some(variant) = self.resolve(event, 0) else { return };
let file = variant.name.trim_start_matches("minecraft:").to_owned();
let entry = self.cache.entry(file.clone()).or_insert_with(|| {
decode(&self.root.join(format!("assets/minecraft/sounds/{file}.ogg"))).map(|(s, r)| (Arc::new(s), r))
});
let Some((samples, rate)) = entry.clone() else { return };
let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master;
let pitch = (pitch * variant.pitch).clamp(0.5, 2.0);
let (mut left, mut right) = (volume, volume);
if let Some(p) = at {
let d = [p[0] - self.listener[0], p[1] - self.listener[1], p[2] - self.listener[2]];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let range = variant.attenuation * volume.max(1.0);
let gain = (1.0 - distance / range).clamp(0.0, 1.0);
if gain <= 0.0 {
return;
}
let yaw = self.listener_yaw.to_radians();
// Right vector of a Minecraft yaw.
let side = (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001);
let pan = side.clamp(-1.0, 1.0);
left = volume * gain * (1.0 - pan.max(0.0) * 0.6);
right = volume * gain * (1.0 + pan.min(0.0) * 0.6);
}
let step = f64::from(rate) / f64::from(self.rate) * f64::from(pitch);
if let Ok(mut m) = self.mixer.lock() {
if m.voices.len() > 64 {
m.voices.remove(0);
}
m.voices.push(Voice {
samples,
position: 0.0,
step,
left,
right,
});
}
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Biome colours from the pinned biome definitions and colormaps
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
use crate::Result;
use horizon_core::{noise::SimplexNoise, random::LegacyRandom};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrassModifier {
None,
DarkForest,
Swamp,
}
#[derive(Clone, Debug)]
pub struct BiomeInfo {
pub name: String,
pub temperature: f32,
pub downfall: f32,
pub precipitation: bool,
pub grass: u32,
pub modifier: GrassModifier,
pub foliage: u32,
pub dry_foliage: u32,
pub water: u32,
pub sky: u32,
pub fog: u32,
pub water_fog: u32,
}
pub struct Biomes {
pub list: Vec<BiomeInfo>,
pub index: HashMap<String, u16>,
info_noise: SimplexNoise,
}
fn color(v: &Value) -> Option<u32> {
match v {
Value::String(s) => u32::from_str_radix(s.trim_start_matches('#'), 16)
.ok()
.map(|c| c & 0xFF_FFFF),
Value::Number(n) => n.as_i64().map(|c| c as u32 & 0xFF_FFFF),
_ => None,
}
}
fn colormap(root: &Path, name: &str) -> Result<Vec<u32>> {
let path = root.join(format!("assets/minecraft/textures/colormap/{name}.png"));
let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info()?;
let mut bytes = vec![0; reader.output_buffer_size().ok_or("colormap too large")?];
let info = reader.next_frame(&mut bytes)?;
let channels = info.color_type.samples();
Ok(bytes[..info.buffer_size()]
.chunks_exact(channels)
.map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2]))
.collect())
}
/// `GrassColor.get`/`FoliageColor.get`: temperature and downfall index a 256x256 map.
fn sample(map: &[u32], temperature: f32, downfall: f32, fallback: u32) -> u32 {
let temperature = f64::from(temperature.clamp(0.0, 1.0));
let downfall = f64::from(downfall.clamp(0.0, 1.0)) * temperature;
let x = ((1.0 - temperature) * 255.0) as i32;
let y = ((1.0 - downfall) * 255.0) as i32;
let index = (y << 8 | x) as usize;
map.get(index).copied().unwrap_or(fallback)
}
impl Biomes {
pub fn load(root: &Path) -> Result<Self> {
let grass = colormap(root, "grass")?;
let foliage = colormap(root, "foliage")?;
let dry = colormap(root, "dry_foliage")?;
let dimension: Value = serde_json::from_slice(&fs::read(
root.join("data/minecraft/dimension_type/overworld.json"),
)?)?;
let default_fog = color(&dimension["attributes"]["minecraft:visual/fog_color"])
.unwrap_or(0xC0D8FF);
let default_sky = color(&dimension["attributes"]["minecraft:visual/sky_color"])
.unwrap_or(0x78A7FF);
let mut list = Vec::new();
let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
names.sort();
for path in names {
let name = format!(
"minecraft:{}",
path.file_stem().and_then(|s| s.to_str()).ok_or("bad biome")?
);
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
let effects = &v["effects"];
let attributes = &v["attributes"];
let temperature = v["temperature"].as_f64().unwrap_or(0.5) as f32;
let downfall = v["downfall"].as_f64().unwrap_or(0.5) as f32;
let modifier = match effects["grass_color_modifier"].as_str() {
Some("dark_forest") => GrassModifier::DarkForest,
Some("swamp") => GrassModifier::Swamp,
_ => GrassModifier::None,
};
list.push(BiomeInfo {
temperature,
downfall,
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
grass: color(&effects["grass_color"])
.unwrap_or_else(|| sample(&grass, temperature, downfall, 0xFF00FF)),
modifier,
foliage: color(&effects["foliage_color"])
.unwrap_or_else(|| sample(&foliage, temperature, downfall, 0x48B518)),
dry_foliage: color(&effects["dry_foliage_color"])
.unwrap_or_else(|| sample(&dry, temperature, downfall, 0x5D4930)),
water: color(&effects["water_color"]).unwrap_or(0x3F76E4),
sky: color(&attributes["minecraft:visual/sky_color"]).unwrap_or(default_sky),
fog: color(&attributes["minecraft:visual/fog_color"]).unwrap_or(default_fog),
water_fog: color(&attributes["minecraft:visual/water_fog_color"])
.unwrap_or(0x050533),
name,
});
}
let index = list
.iter()
.enumerate()
.map(|(i, b)| (b.name.clone(), i as u16))
.collect();
Ok(Self {
list,
index,
info_noise: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(2345), true),
})
}
pub fn id(&self, name: &str) -> u16 {
self.index
.get(name)
.or_else(|| self.index.get("minecraft:plains"))
.copied()
.unwrap_or(0)
}
pub fn get(&self, id: u16) -> &BiomeInfo {
&self.list[usize::from(id).min(self.list.len() - 1)]
}
pub fn grass(&self, id: u16, x: f64, z: f64) -> u32 {
let b = self.get(id);
match b.modifier {
GrassModifier::None => b.grass,
GrassModifier::DarkForest => ((b.grass & 0xFE_FEFE) + 0x28_340A) >> 1,
GrassModifier::Swamp => {
if f64::from(self.info_noise.get2(x * 0.0225, z * 0.0225)) < -0.1 {
0x4C_763C
} else {
0x6A_7039
}
}
}
}
}
+164
View File
@@ -0,0 +1,164 @@
//! Per-state gameplay facts exported from vanilla's own block-state accessors
//! (`gameplay-facts.json`), indexed by registry state ID.
use crate::Result;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{collections::HashMap, fs::File, io::BufReader, path::Path, sync::Arc};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderShape {
Model,
Invisible,
Animated,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fluid {
None,
Water,
Lava,
}
#[derive(Clone, Debug)]
pub struct Sounds {
pub volume: f32,
pub pitch: f32,
pub break_sound: Arc<str>,
pub step: Arc<str>,
pub place: Arc<str>,
pub hit: Arc<str>,
pub fall: Arc<str>,
}
#[derive(Clone, Debug)]
pub struct StateFacts {
pub name: Arc<str>,
pub emission: u8,
pub dampening: u8,
pub skylight_down: bool,
pub shape_occlusion: bool,
pub can_occlude: bool,
pub solid_render: bool,
pub hardness: f32,
pub requires_tool: bool,
pub replaceable: bool,
pub random_ticks: bool,
pub block_entity: bool,
pub render_shape: RenderShape,
pub full_collision: bool,
pub friction: f32,
pub explosion_resistance: f32,
pub item: Arc<str>,
pub sounds: Sounds,
pub fluid: Fluid,
/// Fluid amount 1..=8 (8 = source/falling surface), 0 when there is no fluid.
pub fluid_level: u8,
pub fluid_falling: bool,
pub waterlogged: bool,
}
pub struct BlockFacts {
pub states: Vec<StateFacts>,
pub air: BlockStateId,
}
impl BlockFacts {
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let raw: Value =
serde_json::from_reader(BufReader::new(File::open(root.join("gameplay-facts.json"))?))?;
let entries = raw["states"]
.as_array()
.ok_or("missing gameplay state facts")?;
if entries.len() != registry.len() {
return Err("gameplay facts do not match the block registry".into());
}
let mut names: HashMap<String, Arc<str>> = HashMap::new();
let mut intern = |s: &str| -> Arc<str> {
names
.entry(s.to_owned())
.or_insert_with(|| Arc::from(s))
.clone()
};
let mut states = Vec::with_capacity(entries.len());
for (index, entry) in entries.iter().enumerate() {
let id = BlockStateId(index as u32);
if entry["id"].as_u64() != Some(index as u64) {
return Err("gameplay facts are not in registry order".into());
}
let state = registry.state(id).ok_or("missing registry state")?;
let num = |k: &str| entry[k].as_f64().unwrap_or(0.0);
let flag = |k: &str| entry[k].as_bool().unwrap_or(false);
let sound = &entry["sound"];
let sound_id = |k: &str| sound[k]["id"].as_str().unwrap_or("").to_owned();
let prop = |k: &str| state.properties.get(k).map(String::as_str);
let (fluid, fluid_level, fluid_falling) = match state.name.as_str() {
"minecraft:water" | "minecraft:lava" => {
let level: u8 = prop("level").and_then(|v| v.parse().ok()).unwrap_or(0);
let kind = if state.name == "minecraft:water" {
Fluid::Water
} else {
Fluid::Lava
};
// LiquidBlock: level 0 is the source; 1..7 flowing; >=8 falling.
if level == 0 {
(kind, 8, false)
} else if level >= 8 {
(kind, 8, true)
} else {
(kind, 8 - level, false)
}
}
"minecraft:bubble_column" | "minecraft:kelp" | "minecraft:kelp_plant"
| "minecraft:seagrass" | "minecraft:tall_seagrass" => (Fluid::Water, 8, false),
_ if prop("waterlogged") == Some("true") => (Fluid::Water, 8, false),
_ => (Fluid::None, 0, false),
};
states.push(StateFacts {
name: intern(&state.name),
emission: num("emission") as u8,
dampening: num("dampening") as u8,
skylight_down: flag("skylight_down"),
shape_occlusion: flag("shape_occlusion"),
can_occlude: flag("can_occlude"),
solid_render: flag("solid_render"),
hardness: num("hardness") as f32,
requires_tool: flag("requires_tool"),
replaceable: flag("replaceable"),
random_ticks: flag("random_ticks"),
block_entity: flag("block_entity"),
render_shape: match entry["render_shape"].as_str() {
Some("INVISIBLE") => RenderShape::Invisible,
Some("ENTITYBLOCK_ANIMATED") => RenderShape::Animated,
_ => RenderShape::Model,
},
full_collision: flag("full_collision"),
friction: num("friction") as f32,
explosion_resistance: num("explosion_resistance") as f32,
item: intern(entry["item"].as_str().unwrap_or("minecraft:air")),
sounds: Sounds {
volume: sound["volume"].as_f64().unwrap_or(1.0) as f32,
pitch: sound["pitch"].as_f64().unwrap_or(1.0) as f32,
break_sound: intern(&sound_id("break")),
step: intern(&sound_id("step")),
place: intern(&sound_id("place")),
hit: intern(&sound_id("hit")),
fall: intern(&sound_id("fall")),
},
fluid,
fluid_level,
fluid_falling,
waterlogged: prop("waterlogged") == Some("true"),
});
}
Ok(Self {
states,
air: registry
.default_state("minecraft:air")
.ok_or("missing air")?,
})
}
pub fn get(&self, id: BlockStateId) -> &StateFacts {
&self.states[id.0 as usize]
}
pub fn is_air(&self, id: BlockStateId) -> bool {
matches!(
&*self.states[id.0 as usize].name,
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
)
}
}
-77
View File
@@ -1,77 +0,0 @@
//! Free inspection camera, deliberately separate from future player simulation.
use glam::{DVec3, Mat4, Vec3};
use std::collections::HashSet;
use winit::keyboard::KeyCode;
pub struct Camera {
pub position: DVec3,
pub yaw: f64,
pub pitch: f64,
}
impl Default for Camera {
fn default() -> Self {
Self {
position: DVec3::new(25.0, 18.0, 25.0),
yaw: -135_f64.to_radians(),
pitch: -22_f64.to_radians(),
}
}
}
impl Camera {
/// A standing-sized inspection volume, not a simulated player entity.
pub fn collision_bounds(&self) -> horizon_core::geometry::Aabb {
use horizon_core::geometry::{Aabb, Vec3};
let half_width = f64::from(0.6_f32 / 2.0);
let feet = self.position.y - f64::from(1.62_f32);
Aabb::new(
Vec3::new(
self.position.x - half_width,
feet,
self.position.z - half_width,
),
Vec3::new(
self.position.x + half_width,
feet + f64::from(1.8_f32),
self.position.z + half_width,
),
)
}
pub fn look(&mut self, x: f64, y: f64) {
self.yaw -= x * 0.002;
self.pitch = (self.pitch - y * 0.002).clamp(-1.55, 1.55);
}
pub fn update(&mut self, keys: &HashSet<KeyCode>, seconds: f64) {
self.turn(keys, seconds);
let held = |key| f64::from(u8::from(keys.contains(&key)));
let forward = DVec3::new(self.yaw.sin(), 0.0, self.yaw.cos());
let right = DVec3::new(-self.yaw.cos(), 0.0, self.yaw.sin());
let movement = forward * (held(KeyCode::KeyW) - held(KeyCode::KeyS))
+ right * (held(KeyCode::KeyD) - held(KeyCode::KeyA))
+ DVec3::Y
* (held(KeyCode::Space) - held(KeyCode::ShiftLeft) - held(KeyCode::ShiftRight));
if movement.length_squared() > 0.0 {
self.position += movement.normalize()
* seconds
* if keys.contains(&KeyCode::ControlLeft) || keys.contains(&KeyCode::ControlRight) {
40.0
} else {
12.0
};
}
}
pub fn turn(&mut self, keys: &HashSet<KeyCode>, seconds: f64) {
let held = |key| f64::from(u8::from(keys.contains(&key)));
self.yaw += (held(KeyCode::ArrowLeft) - held(KeyCode::ArrowRight)) * seconds * 1.5;
self.pitch = (self.pitch
+ (held(KeyCode::ArrowUp) - held(KeyCode::ArrowDown)) * seconds * 1.5)
.clamp(-1.55, 1.55);
}
pub fn matrix(&self, aspect: f32) -> Mat4 {
let forward = Vec3::new(
(self.yaw.sin() * self.pitch.cos()) as f32,
self.pitch.sin() as f32,
(self.yaw.cos() * self.pitch.cos()) as f32,
);
Mat4::perspective_rh(70_f32.to_radians(), aspect, 0.05, 1024.0)
* Mat4::look_to_rh(self.position.as_vec3(), forward, Vec3::Y)
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Resident client chunk storage. Sections are reference-counted so worker
//! threads can mesh and light immutable snapshots while the game thread edits
//! (copy-on-write through `Arc::make_mut`).
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
pub const MIN_Y: i32 = -64;
pub const HEIGHT: i32 = 384;
pub const SECTIONS: usize = (HEIGHT / 16) as usize;
#[derive(Clone)]
pub enum Blocks {
Uniform(u16),
Full(Box<[u16; 4096]>),
}
/// Packed light per block: sky light in the high nibble, block light in the low one.
#[derive(Clone)]
pub enum Light {
Uniform(u8),
Full(Box<[u8; 4096]>),
}
#[inline]
pub fn index(x: i32, y: i32, z: i32) -> usize {
((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize
}
#[derive(Clone)]
pub struct Section {
pub blocks: Blocks,
pub light: Light,
}
impl Default for Section {
fn default() -> Self {
Self {
blocks: Blocks::Uniform(0),
light: Light::Uniform(0xF0),
}
}
}
impl Section {
#[inline]
pub fn get(&self, i: usize) -> u16 {
match &self.blocks {
Blocks::Uniform(v) => *v,
Blocks::Full(a) => a[i],
}
}
pub fn set(&mut self, i: usize, v: u16) -> u16 {
match &mut self.blocks {
Blocks::Uniform(u) if *u == v => v,
Blocks::Uniform(u) => {
let old = *u;
let mut a = Box::new([old; 4096]);
a[i] = v;
self.blocks = Blocks::Full(a);
old
}
Blocks::Full(a) => std::mem::replace(&mut a[i], v),
}
}
#[inline]
pub fn light(&self, i: usize) -> u8 {
match &self.light {
Light::Uniform(v) => *v,
Light::Full(a) => a[i],
}
}
pub fn is_uniform(&self, v: u16) -> bool {
match &self.blocks {
Blocks::Uniform(u) => *u == v,
Blocks::Full(a) => a.iter().all(|&b| b == v),
}
}
/// Collapse storage that became uniform.
pub fn compact(&mut self) {
if let Blocks::Full(a) = &self.blocks
&& a.iter().all(|&b| b == a[0])
{
self.blocks = Blocks::Uniform(a[0]);
}
if let Light::Full(a) = &self.light
&& a.iter().all(|&b| b == a[0])
{
self.light = Light::Uniform(a[0]);
}
}
}
#[derive(Clone)]
pub struct Chunk {
pub x: i32,
pub z: i32,
pub sections: Vec<Arc<Section>>,
/// Biome index per 4x4x4 cell (x,z in 0..4, y in 0..96) into `Biomes`.
pub biomes: Arc<Vec<u16>>,
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
pub lit: bool,
}
impl Chunk {
pub fn empty(x: i32, z: i32) -> Self {
Self {
x,
z,
sections: (0..SECTIONS).map(|_| Arc::new(Section::default())).collect(),
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
heights: Arc::new([MIN_Y as i16; 256]),
lit: false,
}
}
#[inline]
pub fn get(&self, x: i32, y: i32, z: i32) -> u16 {
let s = (y - MIN_Y) >> 4;
if !(0..SECTIONS as i32).contains(&s) {
return 0;
}
self.sections[s as usize].get(index(x, y, z))
}
#[inline]
pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
BlockStateId(u32::from(self.get(x, y, z)))
}
pub fn set(&mut self, x: i32, y: i32, z: i32, v: u16) -> u16 {
let s = (y - MIN_Y) >> 4;
if !(0..SECTIONS as i32).contains(&s) {
return v;
}
Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v)
}
#[inline]
pub fn light(&self, x: i32, y: i32, z: i32) -> u8 {
let s = (y - MIN_Y) >> 4;
if s < 0 {
return 0;
}
if s >= SECTIONS as i32 {
return 0xF0;
}
self.sections[s as usize].light(index(x, y, z))
}
#[inline]
pub fn biome(&self, x: i32, y: i32, z: i32) -> u16 {
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
self.biomes[(qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize]
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
//! Collision queries against the same resident chunks used by the renderer.
//! The development scene has no entities, block entities or world border.
//! Entity-dependent block rules fail explicitly until an entity runtime exists.
use crate::{Result, world::TestWorld};
use crate::{Result, world::World};
use horizon_core::{
geometry::{Aabb, Vec3, VoxelShape},
position::{BlockPos, ChunkPos},
@@ -40,7 +40,7 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisi
}
pub struct SceneCollisions<'w, 'r> {
pub world: &'w TestWorld<'r>,
pub world: &'w World,
pub binding: &'w BlockCollisionRegistry<'r>,
}
impl SceneCollisions<'_, '_> {
+203
View File
@@ -0,0 +1,203 @@
//! Crafting and cooking recipes from the pinned data pack: shaped patterns
//! (placed anywhere in the grid, optionally mirrored as in
//! `ShapedRecipePattern.matches`), shapeless ingredient sets, and furnace-type
//! cooking lookups.
use crate::{Result, items::{ItemStack, Items}};
use serde_json::Value;
use std::{collections::HashSet, fs, path::Path, sync::Arc};
/// A set of accepted items (expanded from an item, list or tag).
#[derive(Clone, Debug)]
pub struct Ingredient(pub HashSet<String>);
impl Ingredient {
fn parse(v: &Value, items: &Items) -> Option<Self> {
let mut set = HashSet::new();
let mut add = |s: &str| {
if let Some(tag) = s.strip_prefix('#') {
set.extend(items.item_tags.get(tag).into_iter().flatten().cloned());
} else {
set.insert(s.to_owned());
}
};
match v {
Value::String(s) => add(s),
Value::Array(a) => a.iter().filter_map(Value::as_str).for_each(&mut add),
Value::Object(o) => {
if let Some(s) = o.get("item").and_then(Value::as_str) {
add(s);
}
if let Some(t) = o.get("tag").and_then(Value::as_str) {
add(&format!("#{t}"));
}
}
_ => return None,
}
(!set.is_empty()).then_some(Self(set))
}
pub fn test(&self, stack: &ItemStack) -> bool {
self.0.contains(&*stack.item)
}
}
#[derive(Clone, Debug)]
pub enum Recipe {
Shaped {
width: usize,
height: usize,
cells: Vec<Option<Ingredient>>,
result: ItemStack,
},
Shapeless {
ingredients: Vec<Ingredient>,
result: ItemStack,
},
}
#[derive(Clone, Debug)]
pub struct Cooking {
pub kind: String,
pub ingredient: Ingredient,
pub result: ItemStack,
pub experience: f32,
pub time: u32,
}
pub struct Recipes {
pub crafting: Vec<(String, Recipe)>,
pub cooking: Vec<Cooking>,
}
fn result(v: &Value) -> Option<ItemStack> {
Some(ItemStack {
item: Arc::from(v["id"].as_str()?),
count: v["count"].as_u64().unwrap_or(1) as u32,
damage: 0,
})
}
impl Recipes {
pub fn load(root: &Path, items: &Items) -> Result<Self> {
let mut crafting = Vec::new();
let mut cooking = Vec::new();
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))?
.flatten()
.map(|e| e.path())
.collect();
files.sort();
for path in files {
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_owned();
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
match v["type"].as_str().unwrap_or("") {
"minecraft:crafting_shaped" => {
let pattern: Vec<Vec<char>> = v["pattern"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
.collect();
let height = pattern.len();
let width = pattern.iter().map(Vec::len).max().unwrap_or(0);
let mut cells = Vec::with_capacity(width * height);
let mut ok = true;
for row in &pattern {
for x in 0..width {
let c = row.get(x).copied().unwrap_or(' ');
if c == ' ' {
cells.push(None);
} else {
match Ingredient::parse(&v["key"][c.to_string()], items) {
Some(i) => cells.push(Some(i)),
None => ok = false,
}
}
}
}
if let (true, Some(result)) = (ok, result(&v["result"])) {
crafting.push((name, Recipe::Shaped { width, height, cells, result }));
}
}
"minecraft:crafting_shapeless" => {
let ingredients: Option<Vec<_>> = v["ingredients"]
.as_array()
.into_iter()
.flatten()
.map(|i| Ingredient::parse(i, items))
.collect();
if let (Some(ingredients), Some(result)) = (ingredients, result(&v["result"])) {
crafting.push((name, Recipe::Shapeless { ingredients, result }));
}
}
kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" | "minecraft:campfire_cooking") => {
if let (Some(ingredient), Some(result)) = (Ingredient::parse(&v["ingredient"], items), result(&v["result"])) {
cooking.push(Cooking {
kind: kind.to_owned(),
ingredient,
result,
experience: v["experience"].as_f64().unwrap_or(0.0) as f32,
time: v["cookingtime"].as_u64().unwrap_or(200) as u32,
});
}
}
_ => {}
}
}
Ok(Self { crafting, cooking })
}
/// Match a `size`x`size` grid (row-major) against the crafting recipes.
pub fn craft(&self, grid: &[Option<ItemStack>], size: usize) -> Option<ItemStack> {
// Trim to the occupied bounding box.
let occupied: Vec<(usize, usize)> = (0..size * size)
.filter(|&i| grid[i].is_some())
.map(|i| (i % size, i / size))
.collect();
if occupied.is_empty() {
return None;
}
let (x0, x1) = (occupied.iter().map(|p| p.0).min()?, occupied.iter().map(|p| p.0).max()?);
let (y0, y1) = (occupied.iter().map(|p| p.1).min()?, occupied.iter().map(|p| p.1).max()?);
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref();
for (_, recipe) in &self.crafting {
match recipe {
Recipe::Shaped { width, height, cells, result } => {
if *width != w || *height != h {
continue;
}
let matches = |mirror: bool| {
(0..h).all(|y| {
(0..w).all(|x| {
let rx = if mirror { w - 1 - x } else { x };
match (&cells[y * w + rx], cell(x, y)) {
(None, None) => true,
(Some(i), Some(s)) => i.test(s),
_ => false,
}
})
})
};
if matches(false) || matches(true) {
return Some(result.clone());
}
}
Recipe::Shapeless { ingredients, result } => {
let stacks: Vec<&ItemStack> = grid.iter().flatten().collect();
if stacks.len() != ingredients.len() {
continue;
}
// Greedy bipartite matching is sufficient for vanilla's ingredient sets.
let mut used = vec![false; stacks.len()];
let ok = ingredients.iter().all(|ingredient| {
if let Some(i) = (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) {
used[i] = true;
true
} else {
false
}
});
if ok {
return Some(result.clone());
}
}
}
}
None
}
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
self.cooking.iter().find(|c| c.kind == kind && c.ingredient.test(input))
}
}
+100
View File
@@ -0,0 +1,100 @@
//! Non-player entities simulated on the client world. Dropped items follow
//! `ItemEntity.tick`: gravity 0.04, 0.98 drag (block friction on the ground),
//! a ground bounce of -0.5, water buoyancy, pickup delay and 6000-tick despawn.
use crate::{
blocks::{BlockFacts, Fluid},
collisions::SceneCollisions,
items::ItemStack,
world::World,
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::block_collision::BlockCollisionRegistry;
#[derive(Clone, Debug)]
pub struct ItemEntity {
pub id: u32,
pub stack: ItemStack,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
pub on_ground: bool,
pub age: u32,
pub pickup_delay: u32,
pub bob_offset: f32,
}
impl ItemEntity {
pub const WIDTH: f64 = 0.25;
pub fn bounds(&self) -> Aabb {
let h = Self::WIDTH / 2.0;
Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(self.position.x + h, self.position.y + Self::WIDTH, self.position.z + h),
)
}
/// Returns false when the item should be removed.
pub fn tick(
&mut self,
world: &World,
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
) -> bool {
self.previous = self.position;
if self.pickup_delay > 0 && self.pickup_delay != u32::MAX {
self.pickup_delay -= 1;
}
let eye = world.block(
self.position.x.floor() as i32,
(self.position.y + 0.1).floor() as i32,
self.position.z.floor() as i32,
);
let in_water = facts.get(eye).fluid == Fluid::Water;
if in_water {
// ItemEntity.setUnderwaterMovement
self.velocity = Vec3::new(
self.velocity.x * 0.99,
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
self.velocity.z * 0.99,
);
} else {
self.velocity.y -= 0.04;
}
let horizontal = self.velocity.x * self.velocity.x + self.velocity.z * self.velocity.z;
if !self.on_ground || horizontal > 1.0e-5 || (self.age + self.id) % 4 == 0 {
let mut scene = SceneCollisions { world, binding: collision };
let wanted = self.velocity;
let moved = scene
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
.unwrap_or(Vec3::ZERO);
self.position = Vec3::new(
self.position.x + moved.x,
self.position.y + moved.y,
self.position.z + moved.z,
);
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
if moved.x != wanted.x {
self.velocity.x = 0.0;
}
if moved.z != wanted.z {
self.velocity.z = 0.0;
}
if moved.y != wanted.y {
self.velocity.y = 0.0;
}
let mut friction = 0.98;
if self.on_ground {
let below = world.block(
self.position.x.floor() as i32,
(self.position.y - 0.999_999).floor() as i32,
self.position.z.floor() as i32,
);
friction = f64::from(facts.get(below).friction) * 0.98;
}
self.velocity = Vec3::new(self.velocity.x * friction, self.velocity.y * 0.98, self.velocity.z * friction);
if self.on_ground && self.velocity.y < 0.0 {
self.velocity.y *= -0.5;
}
}
self.age += 1;
self.age < 6000 && self.position.y > -128.0
}
}
+52
View File
@@ -0,0 +1,52 @@
// Entities, dropped items and particles: camera-relative vertices textured
// from the shared 2D atlas, lit through the same lightmap as terrain.
struct Globals {
view_proj: mat4x4<f32>,
fog_color: vec4<f32>,
fog: vec4<f32>,
sky_color: vec4<f32>,
misc: vec4<f32>,
inverse_view: mat4x4<f32>,
sunrise: vec4<f32>,
sun: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
@group(0) @binding(3) var lightmap: texture_2d<f32>;
@group(0) @binding(4) var lightmap_sampler: sampler;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
@location(2) spherical: f32,
@location(3) cylindrical: f32,
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>) -> Out {
var out: Out;
out.clip = globals.view_proj * vec4(position, 1.0);
out.uv = uv;
let l = vec2(f32(light.y), f32(light.x));
let lm = textureSampleLevel(lightmap, lightmap_sampler,
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
var c = color * lm;
// Hurt overlay (OverlayTexture red tint).
if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
out.color = c;
out.spherical = length(position);
out.cylindrical = max(length(position.xz), abs(position.y));
return out;
}
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d <= start { return 0.0; }
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
@fragment fn fs_entity(in: Out) -> @location(0) vec4<f32> {
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
if color.a < 0.1 { discard; }
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
+263
View File
@@ -0,0 +1,263 @@
//! Data-driven environment attributes sampled from the pinned timelines
//! (`KeyframeTrackSampler`, `EasingType`): sky/fog colours, sky light factor,
//! celestial angles and star brightness for the overworld day cycle.
use crate::Result;
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
#[derive(Clone, Copy, Debug)]
enum Easing {
Linear,
Constant,
Bezier([f32; 4]),
}
impl Easing {
fn apply(self, x: f32) -> f32 {
match self {
Self::Linear => x,
Self::Constant => 0.0,
Self::Bezier([x1, y1, x2, y2]) => {
let curve = |c1: f32, c2: f32| (3.0 * c1 - 3.0 * c2 + 1.0, -6.0 * c1 + 3.0 * c2, 3.0 * c1);
let (ax, bx, cx) = curve(x1, x2);
let (ay, by, cy) = curve(y1, y2);
let sample = |(a, b, c): (f32, f32, f32), t: f32| ((a * t + b) * t + c) * t;
let gradient = |t: f32| (3.0 * ax * t + 2.0 * bx) * t + cx;
let mut t = x;
let mut solved = false;
for _ in 0..4 {
let error = sample((ax, bx, cx), t) - x;
if error.abs() < 1e-5 {
solved = true;
break;
}
let g = gradient(t);
if g < 1e-5 {
break;
}
t -= (error / g).clamp(-0.25, 0.25);
}
if !solved {
let (mut t0, mut t1) = (0.0f32, 1.0f32);
while t0 < t1 {
let error = sample((ax, bx, cx), t) - x;
if error.abs() < 1e-5 {
break;
}
if error < 0.0 {
t0 = t;
} else {
t1 = t;
}
let next = (t0 + t1) / 2.0;
if next == t {
break;
}
t = next;
}
}
sample((ay, by, cy), t)
}
}
}
}
#[derive(Clone, Debug)]
struct Track {
keyframes: Vec<(i64, [f32; 4])>,
easing: Easing,
multiply: bool,
}
fn parse_value(v: &Value) -> Option<[f32; 4]> {
match v {
Value::Number(n) => n.as_f64().map(|f| [f as f32, 0.0, 0.0, 0.0]),
Value::Bool(b) => Some([f32::from(u8::from(*b)), 0.0, 0.0, 0.0]),
Value::String(s) => {
let hex = s.trim_start_matches('#');
let c = u32::from_str_radix(hex, 16).ok()?;
let f = |shift: u32| (c >> shift & 255) as f32 / 255.0;
Some(if hex.len() == 8 {
[f(16), f(8), f(0), f(24)]
} else {
[f(16), f(8), f(0), 1.0]
})
}
_ => None,
}
}
impl Track {
fn sample(&self, ticks: i64, period: i64) -> [f32; 4] {
let k = &self.keyframes;
if k.len() == 1 {
return k[0].1;
}
let t = ticks.rem_euclid(period);
let (first, last) = (k[0], k[k.len() - 1]);
let mut segments = vec![(last.1, last.0 - period, first.1, first.0)];
for pair in k.windows(2) {
segments.push((pair[0].1, pair[0].0, pair[1].1, pair[1].0));
}
segments.push((last.1, last.0, first.1, first.0 + period));
let segment = segments
.iter()
.find(|s| t < s.3)
.copied()
.unwrap_or(segments[segments.len() - 1]);
let (from, from_t, to, to_t) = segment;
if t <= from_t {
return from;
}
if t >= to_t {
return to;
}
let alpha = self.easing.apply((t - from_t) as f32 / (to_t - from_t) as f32);
std::array::from_fn(|i| from[i] + (to[i] - from[i]) * alpha)
}
}
pub struct Environment {
period: i64,
tracks: HashMap<String, Track>,
base: HashMap<String, [f32; 4]>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Sky {
pub sky_color: [f32; 3],
pub fog_color: [f32; 3],
pub sky_light_factor: f32,
pub sky_light_color: [f32; 3],
pub block_light_tint: [f32; 3],
pub ambient_light_color: [f32; 3],
pub sun_angle: f32,
pub moon_angle: f32,
pub star_angle: f32,
pub star_brightness: f32,
pub sunrise_color: [f32; 4],
pub cloud_color: [f32; 4],
/// `gameplay/sky_light_level`, the server-side sky darkening.
pub sky_light_level: f32,
}
impl Environment {
pub fn load(root: &Path) -> Result<Self> {
let timeline: Value =
serde_json::from_slice(&fs::read(root.join("data/minecraft/timeline/day.json"))?)?;
let dimension: Value = serde_json::from_slice(&fs::read(
root.join("data/minecraft/dimension_type/overworld.json"),
)?)?;
let mut tracks = HashMap::new();
for (name, track) in timeline["tracks"].as_object().ok_or("invalid timeline")? {
let easing = match &track["ease"] {
Value::String(s) if s == "constant" => Easing::Constant,
Value::Object(o) => match o.get("cubic_bezier").and_then(Value::as_array) {
Some(a) if a.len() == 4 => Easing::Bezier(std::array::from_fn(|i| {
a[i].as_f64().unwrap_or(0.0) as f32
})),
_ => Easing::Linear,
},
_ => Easing::Linear,
};
let keyframes: Vec<_> = track["keyframes"]
.as_array()
.into_iter()
.flatten()
.filter_map(|k| Some((k["ticks"].as_i64()?, parse_value(&k["value"])?)))
.collect();
if keyframes.is_empty() {
continue;
}
tracks.insert(
name.clone(),
Track {
keyframes,
easing,
multiply: track["modifier"].as_str() == Some("multiply"),
},
);
}
let mut base: HashMap<String, [f32; 4]> = [
("minecraft:visual/block_light_tint", "#ffd88c"),
("minecraft:visual/sky_light_color", "#ffffff"),
("minecraft:visual/ambient_light_color", "#000000"),
]
.into_iter()
.filter_map(|(k, v)| Some((k.to_owned(), parse_value(&Value::String(v.into()))?)))
.collect();
base.insert("minecraft:visual/sky_light_factor".into(), [1.0, 0.0, 0.0, 0.0]);
base.insert("minecraft:gameplay/sky_light_level".into(), [1.0, 0.0, 0.0, 0.0]);
for (k, v) in dimension["attributes"].as_object().into_iter().flatten() {
if let Some(v) = parse_value(v) {
base.insert(k.clone(), v);
}
}
Ok(Self {
period: timeline["period_ticks"].as_i64().unwrap_or(24000),
tracks,
base,
})
}
fn value(&self, name: &str, base: [f32; 4], ticks: i64) -> [f32; 4] {
match self.tracks.get(name) {
Some(track) => {
let v = track.sample(ticks, self.period);
if track.multiply {
std::array::from_fn(|i| base[i] * v[i])
} else {
v
}
}
None => base,
}
}
fn base(&self, name: &str) -> [f32; 4] {
self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0])
}
/// Sky state for a time of day, with the biome's sky and fog colours as base values.
pub fn sample(&self, ticks: i64, biome_sky: u32, biome_fog: u32) -> Sky {
let rgb = |c: u32| {
[
(c >> 16 & 255) as f32 / 255.0,
(c >> 8 & 255) as f32 / 255.0,
(c & 255) as f32 / 255.0,
1.0,
]
};
let v = |name: &str, base: [f32; 4]| self.value(name, base, ticks);
let three = |a: [f32; 4]| [a[0], a[1], a[2]];
let scalar = |name: &str| {
let b = self.base(name);
let b = if self.base.contains_key(name) { b } else { [1.0, 0.0, 0.0, 0.0] };
let t = self.tracks.get(name);
match t {
Some(t) if t.multiply => b[0] * t.sample(ticks, self.period)[0],
Some(t) => t.sample(ticks, self.period)[0],
None => b[0],
}
};
let angle = |name: &str| {
self.tracks
.get(name)
.map_or(0.0, |t| t.sample(ticks, self.period)[0])
};
Sky {
sky_color: three(v("minecraft:visual/sky_color", rgb(biome_sky))),
fog_color: three(v("minecraft:visual/fog_color", rgb(biome_fog))),
sky_light_factor: scalar("minecraft:visual/sky_light_factor"),
sky_light_color: three(v(
"minecraft:visual/sky_light_color",
self.base("minecraft:visual/sky_light_color"),
)),
block_light_tint: three(self.base("minecraft:visual/block_light_tint")),
ambient_light_color: three(self.base("minecraft:visual/ambient_light_color")),
sun_angle: angle("minecraft:visual/sun_angle"),
moon_angle: angle("minecraft:visual/moon_angle"),
star_angle: angle("minecraft:visual/star_angle"),
star_brightness: angle("minecraft:visual/star_brightness"),
sunrise_color: self
.tracks
.get("minecraft:visual/sunrise_sunset_color")
.map_or([0.0; 4], |t| t.sample(ticks, self.period)),
cloud_color: v(
"minecraft:visual/cloud_color",
self.base("minecraft:visual/cloud_color"),
),
sky_light_level: scalar("minecraft:gameplay/sky_light_level"),
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+508
View File
@@ -0,0 +1,508 @@
//! 2D overlay: one atlas holding GUI sprites, the bitmap font, item and block
//! textures, and a batch of textured quads in GUI pixels (vanilla's automatic
//! GUI scale is applied when drawing).
use crate::Result;
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
use wgpu::util::DeviceExt;
#[derive(Clone, Copy, Debug)]
pub struct Rect {
pub u0: f32,
pub v0: f32,
pub u1: f32,
pub v1: f32,
pub w: u32,
pub h: u32,
}
#[derive(Clone, Copy)]
struct Glyph {
rect: Rect,
advance: f32,
}
pub struct HudAtlas {
pub pixels: Vec<u8>,
pub width: u32,
pub height: u32,
pub sprites: HashMap<String, Rect>,
glyphs: HashMap<char, Glyph>,
white: Rect,
}
fn decode(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info()?;
let mut bytes = vec![0; reader.output_buffer_size().ok_or("image too large")?];
let info = reader.next_frame(&mut bytes)?;
let channels = info.color_type.samples();
let mut rgba = Vec::with_capacity((info.width * info.height * 4) as usize);
for p in bytes[..info.buffer_size()].chunks_exact(channels) {
rgba.extend(match channels {
4 => [p[0], p[1], p[2], p[3]],
3 => [p[0], p[1], p[2], 255],
2 => [p[0], p[0], p[0], p[1]],
_ => [p[0], p[0], p[0], 255],
});
}
Ok((info.width, info.height, rgba))
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "png") {
out.push(path);
}
}
}
impl HudAtlas {
pub fn build(root: &Path) -> Result<Self> {
let textures = root.join("assets/minecraft/textures");
let mut files = Vec::new();
walk(&textures.join("gui"), &mut files);
walk(&textures.join("item"), &mut files);
walk(&textures.join("block"), &mut files);
walk(&textures.join("font"), &mut files);
walk(&textures.join("environment"), &mut files);
walk(&textures.join("misc"), &mut files);
walk(&textures.join("entity"), &mut files);
walk(&textures.join("particle"), &mut files);
files.retain(|p| {
let s = p.to_string_lossy();
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
});
let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec<u8>)> {
let name = path
.strip_prefix(&textures)
.ok()?
.with_extension("")
.to_string_lossy()
.replace('\\', "/");
let (w, mut h, pixels) = decode(path).ok()?;
let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w;
let pixels = if is_frame_strip {
h = w;
pixels[..(w * w * 4) as usize].to_vec()
} else {
pixels
};
(w <= 512 && h <= 512).then_some((name, w, h, pixels))
};
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
let chunk = files.len().div_ceil(threads).max(1);
let mut images: Vec<_> = std::thread::scope(|scope| {
let handles: Vec<_> = files
.chunks(chunk)
.map(|part| scope.spawn(move || part.iter().filter_map(decode_one).collect::<Vec<_>>()))
.collect();
handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
});
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
let width = 4096u32;
let mut placements = Vec::with_capacity(images.len());
let (mut x, mut y, mut row) = (0u32, 0u32, 0u32);
for (_, w, h, _) in &images {
if x + w + 1 > width {
x = 0;
y += row + 1;
row = 0;
}
placements.push((x, y));
x += w + 1;
row = row.max(*h);
}
let height = (y + row + 1).next_power_of_two();
let mut pixels = vec![0u8; (width * height * 4) as usize];
let mut sprites = HashMap::new();
for ((name, w, h, data), (px, py)) in images.iter().zip(placements) {
for row in 0..*h {
let src = &data[(row * w * 4) as usize..((row + 1) * w * 4) as usize];
let dst = (((py + row) * width + px) * 4) as usize;
pixels[dst..dst + (w * 4) as usize].copy_from_slice(src);
}
sprites.insert(
name.clone(),
Rect {
u0: px as f32 / width as f32,
v0: py as f32 / height as f32,
u1: (px + w) as f32 / width as f32,
v1: (py + h) as f32 / height as f32,
w: *w,
h: *h,
},
);
}
let white = sprites["horizon/white"];
let mut atlas = Self {
pixels,
width,
height,
sprites,
glyphs: HashMap::new(),
white,
};
atlas.load_font(root)?;
Ok(atlas)
}
fn load_font(&mut self, root: &Path) -> Result<()> {
let text = fs::read_to_string(root.join("assets/minecraft/font/include/default.json"))?;
let value: serde_json::Value = serde_json::from_str(&text)?;
for provider in value["providers"].as_array().into_iter().flatten() {
if provider["type"] != "bitmap" {
continue;
}
let file = provider["file"].as_str().unwrap_or("");
let name = file
.trim_start_matches("minecraft:")
.trim_end_matches(".png")
.to_owned();
let Some(rect) = self.sprites.get(&name).copied() else {
continue;
};
let rows: Vec<Vec<char>> = provider["chars"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
.collect();
if rows.is_empty() {
continue;
}
let columns = rows[0].len() as u32;
let cell_w = rect.w / columns;
let cell_h = rect.h / rows.len() as u32;
let height = provider["height"].as_f64().unwrap_or(8.0) as f32;
let scale = height / cell_h as f32;
let (ax, ay) = (
(rect.u0 * self.width as f32) as u32,
(rect.v0 * self.height as f32) as u32,
);
for (r, row) in rows.iter().enumerate() {
for (c, ch) in row.iter().enumerate() {
if *ch == '\0' || self.glyphs.contains_key(ch) {
continue;
}
let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h);
// Glyph width: rightmost column containing an opaque pixel.
let mut used = 0;
for x in (0..cell_w).rev() {
if (0..cell_h).any(|y| {
self.pixels[(((cy + y) * self.width + cx + x) * 4 + 3) as usize] != 0
}) {
used = x + 1;
break;
}
}
self.glyphs.insert(
*ch,
Glyph {
rect: Rect {
u0: cx as f32 / self.width as f32,
v0: cy as f32 / self.height as f32,
u1: (cx + cell_w) as f32 / self.width as f32,
v1: (cy + cell_h) as f32 / self.height as f32,
w: cell_w,
h: cell_h,
},
advance: (used as f32 * scale + 0.5).floor() + 1.0,
},
);
}
}
}
self.glyphs.insert(
' ',
Glyph {
rect: self.white,
advance: 4.0,
},
);
Ok(())
}
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct HudVertex {
pub pos: [f32; 2],
pub uv: [f32; 2],
pub color: u32,
}
/// One frame of overlay geometry in GUI pixels.
pub struct HudBatch {
pub vertices: Vec<HudVertex>,
pub scale: f32,
pub width: f32,
pub height: f32,
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
}
impl HudBatch {
/// Vanilla's automatic GUI scale: the largest scale keeping >= 320x240 GUI pixels.
pub fn new(window: [u32; 2]) -> Self {
let mut scale = 1;
while window[0] / (scale + 1) >= 320 && window[1] / (scale + 1) >= 240 {
scale += 1;
}
Self {
vertices: Vec::new(),
scale: scale as f32,
width: (window[0] as f32 / scale as f32).ceil(),
height: (window[1] as f32 / scale as f32).ceil(),
}
}
pub fn quad(&mut self, p: [[f32; 2]; 4], uv: [[f32; 2]; 4], color: u32) {
for i in [0, 1, 2, 0, 2, 3] {
self.vertices.push(HudVertex {
pos: p[i],
uv: uv[i],
color,
});
}
}
pub fn rect_uv(&mut self, x: f32, y: f32, w: f32, h: f32, r: Rect, color: u32) {
self.quad(
[[x, y], [x + w, y], [x + w, y + h], [x, y + h]],
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]],
color,
);
}
pub fn sprite(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32) {
if let Some(r) = atlas.sprites.get(name).copied() {
self.rect_uv(x, y, r.w as f32, r.h as f32, r, u32::MAX);
}
}
pub fn sprite_scaled(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32, w: f32, h: f32, color: u32) {
if let Some(r) = atlas.sprites.get(name).copied() {
self.rect_uv(x, y, w, h, r, color);
}
}
/// Draw part of a sprite, `fraction` of its width from the left.
pub fn sprite_part(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32, fraction: f32) {
if let Some(mut r) = atlas.sprites.get(name).copied() {
let w = r.w as f32 * fraction;
r.u1 = r.u0 + (r.u1 - r.u0) * fraction;
self.rect_uv(x, y, w, r.h as f32, r, u32::MAX);
}
}
pub fn fill(&mut self, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, color: u32) {
let mut r = atlas.white;
let (cu, cv) = ((r.u0 + r.u1) / 2.0, (r.v0 + r.v1) / 2.0);
r.u0 = cu;
r.u1 = cu;
r.v0 = cv;
r.v1 = cv;
self.rect_uv(x, y, w, h, r, color);
}
pub fn text_width(atlas: &HudAtlas, text: &str) -> f32 {
text.chars()
.map(|c| atlas.glyphs.get(&c).map_or(6.0, |g| g.advance))
.sum()
}
pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 {
if shadow {
let c = color.to_le_bytes();
let dark = rgba(c[0] / 4, c[1] / 4, c[2] / 4, c[3]);
self.text(atlas, text, x + 1.0, y + 1.0, dark, false);
}
let mut cursor = x;
for ch in text.chars() {
let Some(g) = atlas.glyphs.get(&ch).copied() else {
cursor += 6.0;
continue;
};
if ch != ' ' {
self.rect_uv(cursor, y, 8.0, 8.0, g.rect, color);
}
cursor += g.advance;
}
cursor - x
}
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct HudUniform {
size: [f32; 4],
}
pub struct HudRenderer {
pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
capacity: u64,
}
impl HudRenderer {
pub fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
view: &wgpu::TextureView,
) -> Result<Self> {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon HUD"),
source: wgpu::ShaderSource::Wgsl(include_str!("hud.wgsl").into()),
});
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("HUD"),
..Default::default()
});
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("HUD size"),
contents: bytemuck::bytes_of(&HudUniform { size: [1.0; 4] }),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HUD bindings"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("HUD resources"),
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("HUD layout"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("HUD"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<HudVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
size: capacity * std::mem::size_of::<HudVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Ok(Self {
pipeline,
group,
uniform,
buffer,
capacity,
})
}
pub fn draw(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
batch: &HudBatch,
size: [u32; 2],
) {
if batch.vertices.is_empty() {
return;
}
let count = batch.vertices.len() as u64;
if count > self.capacity {
self.capacity = count.next_power_of_two();
self.buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
size: self.capacity * std::mem::size_of::<HudVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&batch.vertices));
queue.write_buffer(
&self.uniform,
0,
bytemuck::bytes_of(&HudUniform {
size: [size[0] as f32, size[1] as f32, batch.scale, 0.0],
}),
);
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HUD"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
pass.draw(0..count as u32, 0..1);
}
}
+22
View File
@@ -0,0 +1,22 @@
struct Hud { size: vec4<f32> }
@group(0) @binding(0) var<uniform> hud: Hud;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>) -> Out {
let pixels = pos * hud.size.z;
var out: Out;
out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, 0.0, 1.0);
out.uv = uv;
out.color = color;
return out;
}
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
let c = textureSample(atlas, atlas_sampler, in.uv) * in.color;
if c.a < 0.004 { discard; }
return c;
}
+458
View File
@@ -0,0 +1,458 @@
//! Items from vanilla's default-component reports, block<->item mapping,
//! tool mining rules and block loot tables (`LootTable`/`LootPool` semantics
//! for the condition, entry and modifier types used by block drops).
use crate::{Result, blocks::BlockFacts};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap, HashSet},
fs,
path::Path,
sync::Arc,
};
#[derive(Clone, Debug)]
pub struct ToolRule {
pub blocks: Vec<String>,
pub speed: Option<f32>,
pub correct: Option<bool>,
}
#[derive(Clone, Debug)]
pub struct ItemInfo {
pub id: Arc<str>,
pub max_stack: u32,
pub max_damage: u32,
pub block: Option<BlockStateId>,
pub tool: Vec<ToolRule>,
pub tool_default_speed: f32,
pub food: Option<(u32, f32)>,
pub model: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ItemStack {
pub item: Arc<str>,
pub count: u32,
pub damage: u32,
}
pub struct Items {
pub items: HashMap<Arc<str>, ItemInfo>,
pub order: Vec<Arc<str>>,
/// Block tag name (without '#') -> member block names.
pub block_tags: HashMap<String, HashSet<String>>,
pub item_tags: HashMap<String, HashSet<String>>,
loot: HashMap<String, Value>,
}
fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
let dir = root.join(format!("data/minecraft/tags/{kind}"));
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
for entry in fs::read_dir(dir)?.flatten() {
let p = entry.path();
if p.is_dir() {
walk(&p, base, raw)?;
} else if p.extension().is_some_and(|e| e == "json") {
let name = format!(
"minecraft:{}",
p.strip_prefix(base)?.with_extension("").to_string_lossy().replace('\\', "/")
);
let v: Value = serde_json::from_slice(&fs::read(&p)?)?;
let values = v["values"]
.as_array()
.into_iter()
.flatten()
.filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned))
.collect();
raw.insert(name, values);
}
}
Ok(())
}
if dir.exists() {
walk(&dir, &dir, &mut raw)?;
}
fn resolve(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut HashSet<String>, depth: u32) {
if depth > 32 {
return;
}
for v in raw.get(name).into_iter().flatten() {
if let Some(tag) = v.strip_prefix('#') {
resolve(tag, raw, out, depth + 1);
} else {
out.insert(v.clone());
}
}
}
Ok(raw
.keys()
.map(|k| {
let mut set = HashSet::new();
resolve(k, &raw, &mut set, 0);
(k.clone(), set)
})
.collect())
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
let default = registry.default_state(&s.name);
if default == Some(BlockStateId(i as u32)) && &*s.item != "minecraft:air" {
block_for_item.entry(&s.item).or_insert(BlockStateId(i as u32));
}
}
let mut items = HashMap::new();
let mut order = Vec::new();
for (name, c) in &raw {
let id: Arc<str> = Arc::from(name.as_str());
let tool = c["minecraft:tool"]["rules"]
.as_array()
.into_iter()
.flatten()
.map(|r| ToolRule {
blocks: match &r["blocks"] {
Value::String(s) => vec![s.clone()],
Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
_ => vec![],
},
speed: r["speed"].as_f64().map(|v| v as f32),
correct: r["correct_for_drops"].as_bool(),
})
.collect();
let food = c.get("minecraft:food").map(|f| {
(
f["nutrition"].as_u64().unwrap_or(0) as u32,
f["saturation"].as_f64().unwrap_or(0.0) as f32,
)
});
items.insert(
id.clone(),
ItemInfo {
id: id.clone(),
max_stack: c["minecraft:max_stack_size"].as_u64().unwrap_or(64) as u32,
max_damage: c["minecraft:max_damage"].as_u64().unwrap_or(0) as u32,
block: block_for_item.get(name.as_str()).copied(),
tool,
tool_default_speed: c["minecraft:tool"]["default_mining_speed"]
.as_f64()
.unwrap_or(1.0) as f32,
food,
model: c["minecraft:item_model"].as_str().unwrap_or(name).to_owned(),
},
);
order.push(id);
}
let mut loot = HashMap::new();
let dir = root.join("data/minecraft/loot_table/blocks");
for entry in fs::read_dir(&dir)?.flatten() {
let p = entry.path();
if let Some(stem) = p.file_stem().and_then(|s| s.to_str()) {
loot.insert(format!("minecraft:blocks/{stem}"), serde_json::from_slice(&fs::read(&p)?)?);
}
}
Ok(Self {
items,
order,
block_tags: load_tags(root, "block")?,
item_tags: load_tags(root, "item")?,
loot,
})
}
pub fn get(&self, id: &str) -> Option<&ItemInfo> {
self.items.get(id)
}
fn block_matches(&self, spec: &str, block: &str) -> bool {
match spec.strip_prefix('#') {
Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)),
None => spec == block,
}
}
/// `Tool.getMiningSpeed` for the held item (1.0 without a tool component).
pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 {
let Some(info) = held.and_then(|s| self.get(&s.item)) else {
return 1.0;
};
for rule in &info.tool {
if let Some(speed) = rule.speed
&& rule.blocks.iter().any(|b| self.block_matches(b, block))
{
return speed;
}
}
if info.tool.is_empty() {
1.0
} else {
info.tool_default_speed
}
}
/// `Tool.isCorrectForDrops`.
pub fn correct_for_drops(&self, held: Option<&ItemStack>, block: &str) -> bool {
let Some(info) = held.and_then(|s| self.get(&s.item)) else {
return false;
};
for rule in &info.tool {
if let Some(correct) = rule.correct
&& rule.blocks.iter().any(|b| self.block_matches(b, block))
{
return correct;
}
}
false
}
/// Evaluate the block's loot table for a player break without explosions.
pub fn block_drops(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
random: &mut LegacyRandom,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
};
let name = block.name.trim_start_matches("minecraft:");
let Some(table) = self.loot.get(&format!("minecraft:blocks/{name}")) else {
return vec![];
};
let ctx = LootContext {
items: self,
block: &block.name,
properties: &block.properties,
held,
};
let mut out = Vec::new();
for pool in table["pools"].as_array().into_iter().flatten() {
if !ctx.conditions(pool, random) {
continue;
}
let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32;
for _ in 0..rolls {
let mut produced = Vec::new();
ctx.choose(pool["entries"].as_array().map_or(&[][..], Vec::as_slice), random, &mut produced);
for mut stack in produced {
ctx.modifiers(&pool["modifier"], &mut stack, random);
ctx.modifiers(&table["modifier"], &mut stack, random);
if stack.count > 0 {
out.push(stack);
}
}
}
}
out
}
}
struct LootContext<'a> {
items: &'a Items,
block: &'a str,
properties: &'a BTreeMap<String, String>,
held: Option<&'a ItemStack>,
}
impl LootContext<'_> {
fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 {
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32,
Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") {
"minecraft:constant" => o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32,
"minecraft:uniform" => {
let min = self.number(o.get("min").unwrap_or(&Value::Null), random);
let max = self.number(o.get("max").unwrap_or(&Value::Null), random);
// UniformGenerator.getFloat / getInt (Mth.nextInt) differ; use int for counts.
if max <= min {
min
} else {
min + random.next_float() * (max - min)
}
}
"minecraft:binomial" => {
let n = self.number(o.get("n").unwrap_or(&Value::Null), random) as u32;
let p = self.number(o.get("p").unwrap_or(&Value::Null), random);
(0..n).filter(|_| random.next_float() < p).count() as f32
}
_ => 1.0,
},
_ => 1.0,
}
}
fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 {
if let Value::Object(o) = v
&& o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") == "minecraft:uniform"
{
let min = self.int_number(o.get("min").unwrap_or(&Value::Null), random);
let max = self.int_number(o.get("max").unwrap_or(&Value::Null), random);
return if max <= min {
min
} else {
min + random.next_int_bound(max - min + 1).unwrap_or(0)
};
}
self.number(v, random).round() as i32
}
fn condition(&self, c: &Value, random: &mut LegacyRandom) -> bool {
let (kind, c) = match c {
Value::String(s) => (s.as_str(), &Value::Null),
Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c),
_ => return true,
};
match kind {
"minecraft:survives_explosion" => true,
"minecraft:tool/can_silk_touch" => false,
"minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"),
"minecraft:inverted" => !self.condition(&c["term"], random),
"minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, random)),
"minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, random)),
"minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random),
"minecraft:table_bonus" => {
let chance = c["chances"][0].as_f64().unwrap_or(0.0) as f32;
random.next_float() < chance
}
"minecraft:match_block" | "minecraft:block_state_property" => {
let blocks_ok = match &c["blocks"].as_str().or(c["block"].as_str()) {
Some(spec) => self.items.block_matches(spec, self.block),
None => true,
};
blocks_ok
&& c["state"].as_object().into_iter().flatten().chain(c["properties"].as_object().into_iter().flatten()).all(|(k, v)| {
let have = self.properties.get(k).map(String::as_str);
match v {
Value::String(s) => have == Some(s.as_str()),
Value::Object(r) => {
let have: i64 = have.and_then(|h| h.parse().ok()).unwrap_or(0);
r.get("min").and_then(Value::as_i64).is_none_or(|m| have >= m)
&& r.get("max").and_then(Value::as_i64).is_none_or(|m| have <= m)
}
_ => true,
}
})
}
"minecraft:match_tool" => {
let items = &c["predicate"]["items"];
match (self.held, items) {
(Some(h), Value::String(s)) => match s.strip_prefix('#') {
Some(tag) => self.items.item_tags.get(tag).is_some_and(|t| t.contains(&*h.item)),
None => **s == *h.item,
},
_ => false,
}
}
"minecraft:entity_properties" => true,
_ => true,
}
}
fn conditions(&self, o: &Value, random: &mut LegacyRandom) -> bool {
if let Some(c) = o.get("condition")
&& !self.condition(c, random)
{
return false;
}
o.get("conditions")
.and_then(Value::as_array)
.into_iter()
.flatten()
.all(|c| self.condition(c, random))
}
/// Expand entries; returns whether an entry succeeded (for alternatives).
fn expand(&self, e: &Value, random: &mut LegacyRandom, out: &mut Vec<(i32, ItemStack, Value)>) -> bool {
if !self.conditions(e, random) {
return false;
}
match e["type"].as_str().unwrap_or("") {
"minecraft:item" => {
out.push((
e["weight"].as_i64().unwrap_or(1) as i32,
ItemStack {
item: Arc::from(e["name"].as_str().unwrap_or("minecraft:air")),
count: 1,
damage: 0,
},
e["modifier"].clone(),
));
true
}
"minecraft:alternatives" => {
for child in e["children"].as_array().into_iter().flatten() {
if self.expand(child, random, out) {
return true;
}
}
false
}
"minecraft:group" => {
for child in e["children"].as_array().into_iter().flatten() {
self.expand(child, random, out);
}
true
}
"minecraft:sequence" => {
for child in e["children"].as_array().into_iter().flatten() {
if !self.expand(child, random, out) {
break;
}
}
true
}
"minecraft:empty" => {
out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0 }, Value::Null));
true
}
_ => false,
}
}
fn choose(&self, entries: &[Value], random: &mut LegacyRandom, produced: &mut Vec<ItemStack>) {
let mut candidates = Vec::new();
for e in entries {
self.expand(e, random, &mut candidates);
}
if candidates.is_empty() {
return;
}
let pick = if candidates.len() == 1 {
0
} else {
let total: i32 = candidates.iter().map(|c| c.0.max(0)).sum();
let mut r = random.next_int_bound(total.max(1)).unwrap_or(0);
let mut chosen = 0;
for (i, c) in candidates.iter().enumerate() {
r -= c.0.max(0);
if r < 0 {
chosen = i;
break;
}
}
chosen
};
let (_, mut stack, modifiers) = candidates.swap_remove(pick);
self.modifiers(&modifiers, &mut stack, random);
produced.push(stack);
}
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut LegacyRandom) {
let list: Vec<&Value> = match m {
Value::Array(a) => a.iter().collect(),
Value::Object(_) => vec![m],
_ => return,
};
for f in list {
if !self.conditions(f, random) {
continue;
}
match f["type"].as_str().or(f["function"].as_str()).unwrap_or("") {
"minecraft:set_count" => {
let n = self.int_number(&f["count"], random);
let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 };
stack.count = (base + n).max(0) as u32;
}
"minecraft:limit_count" => {
let limit = &f["limit"];
if let Some(min) = limit["min"].as_i64() {
stack.count = stack.count.max(min as u32);
}
if let Some(max) = limit["max"].as_i64() {
stack.count = stack.count.min(max as u32);
}
}
_ => {}
}
}
}
}
+18 -1
View File
@@ -1,17 +1,34 @@
//! Shared resident-scene loading and queries for the native development client.
//! Horizon native client: resources, world streaming, rendering and the
//! bindings between the validated simulation pieces and the game loop.
#![forbid(unsafe_code)]
pub mod assets;
pub mod attribute_updates;
pub mod audio;
pub mod biome;
pub mod blocks;
pub mod chunk;
pub mod clock;
pub mod crafting;
pub mod collisions;
pub mod entities;
pub mod environment;
pub mod gfx;
pub mod health;
pub mod hud;
pub mod hunger;
pub mod input;
pub mod items;
pub mod landing;
pub mod light;
pub mod mesher;
pub mod models;
pub mod motion;
pub mod particles;
pub mod pose;
pub mod save;
pub mod sprint;
pub mod sprites;
pub mod streaming;
pub mod testgen;
pub mod world;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
+184
View File
@@ -0,0 +1,184 @@
//! Sky and block light for one chunk, flood-filled over its 3x3 neighbourhood
//! with vanilla's rules: sky sources run down each column until an edge is
//! occluded (`ChunkSkyLightSources`), and light then spreads losing
//! `max(1, dampening)` per step (`LightEngine.getOpacity`). Light can travel at
//! most 15 blocks, so the 48-wide region determines the centre exactly, apart
//! from face-shape occlusion of partial blocks (slabs, stairs), which is not
//! modelled yet.
use crate::{
blocks::BlockFacts,
chunk::{Chunk, HEIGHT, Light, SECTIONS, Section, index},
};
use std::{collections::VecDeque, sync::Arc};
const W: usize = 48;
#[derive(Clone, Copy)]
struct Cell {
dampening: u8,
emission: u8,
}
pub struct LightTables {
cells: Vec<Cell>,
}
impl LightTables {
pub fn new(facts: &BlockFacts) -> Self {
Self {
cells: facts
.states
.iter()
.map(|s| Cell {
dampening: s.dampening.min(15),
emission: s.emission.min(15),
})
.collect(),
}
}
}
/// `region[dz][dx]` holds the chunks around the centre (index 1,1).
pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables) -> Vec<Arc<Section>> {
let center = region[1][1].expect("centre chunk");
// Highest occupied section in the region bounds the work.
let mut top_section = 0;
for chunk in region.iter().flatten().flatten() {
for (i, s) in chunk.sections.iter().enumerate().rev() {
if !s.is_uniform(0) {
top_section = top_section.max(i + 1);
break;
}
}
}
let h = (top_section * 16 + 1).min(HEIGHT as usize);
let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x;
let mut damp = vec![0u8; W * W * h];
let mut sky = vec![0u8; W * W * h];
let mut block = vec![0u8; W * W * h];
let mut queue = VecDeque::new();
let mut sky_queue = VecDeque::new();
for (dz, row) in region.iter().enumerate() {
for (dx, chunk) in row.iter().enumerate() {
let Some(chunk) = chunk else { continue };
for (si, section) in chunk.sections.iter().enumerate().take(top_section) {
if section.is_uniform(0) {
continue;
}
for i in 0..4096 {
let id = section.get(i) as usize;
let cell = tables.cells[id];
let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8);
let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz);
damp[p] = cell.dampening;
if cell.emission > 0 {
block[p] = cell.emission;
queue.push_back(p as u32);
}
}
}
}
}
// Columns of missing neighbour chunks contribute no light.
let present = |x: usize, z: usize| region[z / 16][x / 16].is_some();
let mut lowest = vec![h as i32; W * W];
for z in 0..W {
for x in 0..W {
if !present(x, z) {
continue;
}
let mut y = h as i32 - 1;
// The top layer (above the occupied range) is always open sky.
while y >= 0 && damp[at(x, y as usize, z)] == 0 {
sky[at(x, y as usize, z)] = 15;
y -= 1;
}
lowest[z * W + x] = y + 1;
}
}
for z in 0..W {
for x in 0..W {
if !present(x, z) {
continue;
}
let own = lowest[z * W + x];
let mut deepest = own;
for (nx, nz) in [(x.wrapping_sub(1), z), (x + 1, z), (x, z.wrapping_sub(1)), (x, z + 1)] {
if nx < W && nz < W && present(nx, nz) {
deepest = deepest.max(lowest[nz * W + nx]);
}
}
// Seed propagation from the source cells that border darker cells.
let from = own.max(0) as usize;
let to = (deepest as usize).min(h - 1);
for y in from..=to {
if sky[at(x, y, z)] == 15 {
sky_queue.push_back(at(x, y, z) as u32);
}
}
}
}
let spread = |light: &mut [u8], queue: &mut VecDeque<u32>| {
while let Some(p) = queue.pop_front() {
let p = p as usize;
let level = light[p];
if level <= 1 {
continue;
}
let x = p % W;
let z = (p / W) % W;
let y = p / (W * W);
let mut visit = |q: usize| {
let next = level.saturating_sub(damp[q].max(1));
if next > light[q] {
light[q] = next;
queue.push_back(q as u32);
}
};
if x > 0 {
visit(p - 1);
}
if x + 1 < W {
visit(p + 1);
}
if z > 0 {
visit(p - W);
}
if z + 1 < W {
visit(p + W);
}
if y > 0 {
visit(p - W * W);
}
if y + 1 < h {
visit(p + W * W);
}
}
};
spread(&mut sky, &mut sky_queue);
spread(&mut block, &mut queue);
let mut sections = Vec::with_capacity(SECTIONS);
for (si, section) in center.sections.iter().enumerate() {
let mut out = (**section).clone();
if si * 16 >= h {
out.light = Light::Uniform(0xF0);
} else {
let mut data = Box::new([0u8; 4096]);
for ly in 0..16 {
let y = si * 16 + ly;
if y >= h {
for i in 0..256 {
data[ly << 8 | i] = 0xF0;
}
continue;
}
for lz in 0..16 {
for lx in 0..16 {
let p = at(16 + lx, y, 16 + lz);
data[index(lx as i32, ly as i32, lz as i32)] = sky[p] << 4 | block[p];
}
}
}
out.light = Light::Full(data);
}
out.compact();
sections.push(Arc::new(out));
}
sections
}
+4 -644
View File
@@ -1,649 +1,9 @@
//! Native Horizon development client. The scene and free camera are rendering
//! tools; they do not replace the authoritative gameplay implementation.
//! Horizon: native Rust client for Minecraft Java Edition 26.3 gameplay.
#![forbid(unsafe_code)]
mod camera;
mod mesh;
mod render;
use assets::Assets;
use camera::Camera;
use horizon_client::{assets, collisions, models, sprites, world};
use horizon_client::{
clock::FixedStep,
motion::{MotionResources, MotionWorld, PlayerMotion},
sprint::Keys,
};
use horizon_core::geometry::Vec3;
use mesh::Mesh;
use render::Renderer;
use std::{
collections::HashSet,
fs,
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
};
use winit::{
application::ApplicationHandler,
event::{DeviceEvent, DeviceId, ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{KeyCode, PhysicalKey},
window::{CursorGrabMode, Window, WindowId},
};
use world::TestWorld;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
struct Options {
resources: PathBuf,
radius: i32,
frames: Option<u64>,
report: Option<PathBuf>,
timeout: Duration,
trace_input: bool,
}
impl Options {
fn read() -> Result<Option<Self>> {
let sibling = std::env::current_exe()?
.parent()
.ok_or("missing executable directory")?
.join("resources");
let mut options = Self {
resources: if sibling.join("horizon-resources.json").exists() {
sibling
} else {
PathBuf::from(".local/horizon-client/26.3")
},
radius: 4,
frames: None,
report: None,
timeout: Duration::from_secs(90),
trace_input: false,
};
let mut args = std::env::args().skip(1);
while let Some(argument) = args.next() {
if argument == "--trace-input" {
options.trace_input = true;
continue;
}
if argument == "--help" || argument == "-h" {
println!(
"Horizon native development client\n\n --resources PATH Prepared pinned resources\n --radius CHUNKS Controlled scene radius, 1..16 (default 4)\n --frames COUNT Exit after this many presented frames\n --smoke-report PATH Write a runtime report on exit\n --timeout-seconds N Deadline for a frame-limited run (default 90)\n --trace-input Log received keyboard, mouse-button and focus events\n\nControls: click to capture mouse; WASD move; Space/Shift rise/descend;\nCtrl boosts speed; arrow keys rotate; Esc releases mouse; Ctrl+Q quits; F3 shows diagnostics; F4 toggles camera collisions; F5 toggles walking test.\nWalking test: WASD move; Space jumps; Left Shift crouches; Left Ctrl or double-tap W starts sprinting; gravity and collisions at 20 ticks/s.\n\nThis is a controlled development scene. Walking includes landing damage, stored health, hunger and regeneration. Full death/respawn, interaction, saving and complete gameplay remain unfinished."
);
return Ok(None);
}
let value = args
.next()
.ok_or_else(|| format!("missing value after {argument}"))?;
match argument.as_str() {
"--resources" => options.resources = value.into(),
"--radius" => {
options.radius = value.parse()?;
if !(1..=16).contains(&options.radius) {
return Err("radius must be 1..16 chunks".into());
}
}
"--frames" => {
let frames = value.parse()?;
if frames == 0 {
return Err("frame count must be positive".into());
}
options.frames = Some(frames);
}
"--smoke-report" => options.report = Some(value.into()),
"--timeout-seconds" => {
let seconds: u64 = value.parse()?;
if seconds == 0 {
return Err("timeout must be positive".into());
}
options.timeout = Duration::from_secs(seconds);
}
_ => return Err(format!("unknown option {argument}").into()),
}
}
Ok(Some(options))
}
}
struct App<'a> {
assets: &'a Assets,
world: TestWorld<'a>,
collision_binding: &'a horizon_world::block_collision::BlockCollisionRegistry<'a>,
collision_camera: bool,
motion_resources: &'a MotionResources,
player: Option<PlayerMotion>,
motion_clock: FixedStep,
previous_player_position: Vec3,
eye_height: f32,
previous_eye_height: f32,
crouch_ticks: u64,
crouch_distance_cm: u64,
movement_ticks: u64,
sprint_ticks: u64,
sprint_distance_cm: u64,
walk_distance_cm: u64,
fall_damage_requests: u64,
last_requested_fall_damage: Option<f32>,
visibility: horizon_world::block_render::FaceVisibility,
mesh_revision: u64,
mesh: Mesh,
options: Options,
window: Option<Arc<Window>>,
renderer: Option<Renderer>,
camera: Camera,
keys: HashSet<KeyCode>,
captured: bool,
focused: bool,
diagnostics: bool,
started: Instant,
previous: Instant,
next_redraw: Instant,
title_at: Instant,
title_frames: u64,
frames: u64,
error: Option<String>,
}
impl App<'_> {
fn toggle_walking(&mut self) -> Result<()> {
if self.player.is_some() {
self.player = None;
} else {
let mut collision = collisions::SceneCollisions {
world: &self.world,
binding: self.collision_binding,
};
if !collision.unobstructed(self.camera.collision_bounds())? {
eprintln!(
"Horizon: move the inspection camera to an unobstructed position before walking."
);
return Ok(());
}
let p = self.camera.position;
let feet = Vec3::new(p.x, p.y - f64::from(1.62_f32), p.z);
self.player = Some(PlayerMotion::new(self.motion_resources, feet)?);
self.previous_player_position = feet;
self.eye_height = 1.62;
self.previous_eye_height = self.eye_height;
self.collision_camera = false;
}
self.motion_clock.reset();
self.previous = Instant::now();
eprintln!("Horizon walking test: {}", self.player.is_some());
Ok(())
}
fn move_player(&mut self, elapsed: Duration) -> Result<()> {
let player = self.player.as_mut().ok_or("missing movement actor")?;
let keys = Keys {
forward: self.keys.contains(&KeyCode::KeyW),
backward: self.keys.contains(&KeyCode::KeyS),
left: self.keys.contains(&KeyCode::KeyA),
right: self.keys.contains(&KeyCode::KeyD),
jump: self.keys.contains(&KeyCode::Space),
shift: self.keys.contains(&KeyCode::ShiftLeft),
sprint: self.keys.contains(&KeyCode::ControlLeft),
};
for _ in 0..self.motion_clock.advance(elapsed) {
self.previous_player_position = player.position;
player.yaw = (-self.camera.yaw.to_degrees()) as f32;
MotionWorld {
player,
scene: &mut self.world,
assets: self.assets,
collision_binding: self.collision_binding,
resources: self.motion_resources,
}
.controlled_simulation_tick(keys)?;
// Health is already updated synchronously during landing. These
// counters expose incoming requests; delivery consumers remain pending.
for event in player.events.drain(..) {
match event {
horizon_client::motion::MotionEvent::Fall(
horizon_client::landing::FallEvent::Damage { amount, .. },
) => {
self.fall_damage_requests += 1;
self.last_requested_fall_damage = Some(amount);
}
horizon_client::motion::MotionEvent::Health(
horizon_client::health::HealthEvent::Statistic { name, amount },
) => match name {
"sprint_one_cm" => self.sprint_distance_cm += amount as u64,
"walk_one_cm" => self.walk_distance_cm += amount as u64,
"crouch_one_cm" => self.crouch_distance_cm += amount as u64,
_ => {}
},
_ => {}
}
}
// Camera.tick keeps float eye-height smoothing separate from physics.
self.previous_eye_height = self.eye_height;
self.eye_height += (player.dimensions.eye_height - self.eye_height) * 0.5;
self.crouch_ticks += u64::from(player.pose == horizon_client::pose::Pose::Crouching);
self.movement_ticks += 1;
self.sprint_ticks += u64::from(player.sprinting);
}
let from = self.previous_player_position;
let to = player.position;
let alpha = self.motion_clock.fraction();
let eye = self.previous_eye_height
+ (alpha as f32) * (self.eye_height - self.previous_eye_height);
self.camera.position = glam::DVec3::new(
from.x + (to.x - from.x) * alpha,
from.y + (to.y - from.y) * alpha + f64::from(eye),
from.z + (to.z - from.z) * alpha,
);
if self.mesh_revision != self.world.revision {
let mesh = mesh::build(&self.world, self.assets, &mut self.visibility)?;
self.renderer
.as_mut()
.ok_or("missing renderer")?
.replace_mesh(&mesh.cubes, &mesh.models)?;
self.mesh = mesh;
self.mesh_revision = self.world.revision;
}
Ok(())
}
fn fail(&mut self, event_loop: &ActiveEventLoop, error: impl ToString) {
self.error = Some(error.to_string());
event_loop.exit();
}
fn capture(&mut self, capture: bool) {
let Some(window) = &self.window else {
return;
};
if capture {
self.captured = window
.set_cursor_grab(CursorGrabMode::Locked)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
.is_ok();
} else {
let _ = window.set_cursor_grab(CursorGrabMode::None);
self.captured = false;
}
window.set_cursor_visible(!self.captured);
}
fn write_report(&self) -> Result<()> {
let Some(path) = &self.options.report else {
return Ok(());
};
let renderer = self.renderer.as_ref();
let adapter = renderer.map(|r| {
serde_json::json!({
"name": r.info.name,
"backend": format!("{:?}", r.info.backend),
"device_type": format!("{:?}", r.info.device_type),
"vendor": r.info.vendor,
"device": r.info.device,
})
});
let size = self.window.as_ref().map(|window| {
let size = window.inner_size();
[size.width, size.height]
});
let mut report = serde_json::json!({
"schema": 1,
"project": "Horizon",
"scope": "Native resident-scene renderer with inspection camera and optional fixed-rate dry walking test; full gameplay remains unfinished",
"os": std::env::consts::OS,
"arch": std::env::consts::ARCH,
"adapter": adapter,
"window_size": size,
"presented_frames": self.frames,
"elapsed_seconds": self.started.elapsed().as_secs_f64(),
"resident_chunks": self.world.chunks.len(),
"merged_quads": self.mesh.cubes.len(),
"model_quads": self.mesh.models.len(),
"visible_model_faces": self.mesh.visible_faces,
"culled_model_faces": self.mesh.culled_faces,
"model_blocks": self.mesh.model_blocks,
"model_gallery": self.assets.model_gallery,
"sprite_layers": self.assets.texture_layers,
"animated_sprites": self.assets.animations.len(),
"animation_uploads": self.renderer.as_ref().map_or(0, |r| r.animation_uploads),
"camera_position": self.camera.position.to_array(),
"camera_yaw": self.camera.yaw,
"camera_pitch": self.camera.pitch,
"collision_camera": self.collision_camera,
"walking": self.player.is_some(),
"movement_ticks": self.movement_ticks,
"player_position": self.player.as_ref().map(|p| [p.position.x,p.position.y,p.position.z]),
"player_velocity": self.player.as_ref().map(|p| [p.velocity.x,p.velocity.y,p.velocity.z]),
"player_on_ground": self.player.as_ref().map(|p| p.ground.on_ground),
"player_health": self.player.as_ref().map(|p| p.health.health()),
"player_absorption": self.player.as_ref().map(|p| p.health.absorption()),
"player_dead": self.player.as_ref().map(|p| p.health.dead),
"player_hurt_cooldown": self.player.as_ref().map(|p| p.health.hurt.cooldown),
"player_fall_distance": self.player.as_ref().map(|p| p.fall_distance),
"fall_damage_requests": self.fall_damage_requests,
"last_requested_fall_damage": self.last_requested_fall_damage,
"world_revision": self.world.revision,
"mesh_revision": self.mesh_revision,
"error": self.error,
});
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
report["player_food"] = serde_json::json!(self.player.as_ref().map(|p| p.health.food.food));
report["player_saturation"] =
serde_json::json!(self.player.as_ref().map(|p| p.health.food.saturation));
report["player_exhaustion"] =
serde_json::json!(self.player.as_ref().map(|p| p.health.food.exhaustion));
report["player_food_timer"] =
serde_json::json!(self.player.as_ref().map(|p| p.health.food.timer));
report["player_sprinting"] = serde_json::json!(self.player.as_ref().map(|p| p.sprinting));
report["player_sprint_trigger"] =
serde_json::json!(self.player.as_ref().map(|p| p.sprint_input.trigger_time));
report["player_pose"] = serde_json::json!(self.player.as_ref().map(|p| p.pose.name()));
report["player_local_crouching"] =
serde_json::json!(self.player.as_ref().map(|p| p.local_crouching));
report["player_shift"] = serde_json::json!(self.player.as_ref().map(|p| p.shift_key_down));
report["player_dimensions"] = serde_json::json!(self.player.as_ref().map(|p| [
p.dimensions.width,
p.dimensions.height,
p.dimensions.eye_height
]));
report["camera_eye_height"] = serde_json::json!(self.eye_height);
report["crouch_ticks"] = serde_json::json!(self.crouch_ticks);
report["crouch_distance_cm"] = serde_json::json!(self.crouch_distance_cm);
report["sprint_ticks"] = serde_json::json!(self.sprint_ticks);
report["sprint_distance_cm"] = serde_json::json!(self.sprint_distance_cm);
report["walk_distance_cm"] = serde_json::json!(self.walk_distance_cm);
fs::write(path, serde_json::to_vec_pretty(&report)?)?;
Ok(())
}
}
impl ApplicationHandler for App<'_> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let window = match event_loop.create_window(
Window::default_attributes()
.with_title("Horizon — Development Client")
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 800.0)),
) {
Ok(window) => Arc::new(window),
Err(error) => {
self.fail(event_loop, error);
return;
}
};
match pollster::block_on(Renderer::new(
window.clone(),
self.assets,
&self.mesh.cubes,
&self.mesh.models,
((self.options.radius + 1) * 16) as f32,
)) {
Ok(renderer) => self.renderer = Some(renderer),
Err(error) => {
self.fail(event_loop, error);
return;
}
}
self.window = Some(window);
self.previous = Instant::now();
self.next_redraw = self.previous;
self.title_at = self.previous;
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
if self.options.trace_input
&& matches!(
event,
WindowEvent::Focused(_)
| WindowEvent::KeyboardInput { .. }
| WindowEvent::MouseInput { .. }
)
{
eprintln!("Horizon input: {event:?}");
}
if self.window.as_ref().is_none_or(|window| window.id() != id) {
return;
}
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => {
if let Some(renderer) = &mut self.renderer {
renderer.resize(size.width, size.height);
}
self.next_redraw = Instant::now();
}
WindowEvent::Focused(focused) => {
self.focused = focused;
if !focused {
self.keys.clear();
self.capture(false);
}
self.previous = Instant::now();
self.motion_clock.reset();
}
WindowEvent::MouseInput {
state: ElementState::Pressed,
button: MouseButton::Left,
..
} => self.capture(true),
WindowEvent::KeyboardInput { event, .. } => {
if let PhysicalKey::Code(key) = event.physical_key {
if event.state == ElementState::Pressed {
self.keys.insert(key);
if key == KeyCode::Escape {
self.capture(false);
}
if key == KeyCode::F5
&& !event.repeat
&& let Err(error) = self.toggle_walking()
{
self.fail(event_loop, error);
}
if key == KeyCode::F4 && !event.repeat && self.player.is_none() {
if self.collision_camera {
self.collision_camera = false;
} else {
let mut collision = collisions::SceneCollisions {
world: &self.world,
binding: self.collision_binding,
};
match collision.unobstructed(self.camera.collision_bounds()) {
Ok(clear) => self.collision_camera = clear,
Err(error) => self.fail(event_loop, error),
}
}
eprintln!(
"Horizon inspection camera collisions: {}",
self.collision_camera
);
}
if key == KeyCode::F3 && !event.repeat {
self.diagnostics = !self.diagnostics;
if !self.diagnostics {
self.window
.as_ref()
.unwrap()
.set_title("Horizon — Development Client");
}
}
if key == KeyCode::KeyQ
&& (self.keys.contains(&KeyCode::ControlLeft)
|| self.keys.contains(&KeyCode::ControlRight))
{
event_loop.exit();
}
} else {
self.keys.remove(&key);
}
}
}
WindowEvent::RedrawRequested => {
let now = Instant::now();
let elapsed = now.duration_since(self.previous);
let seconds = elapsed.as_secs_f64().min(0.1);
self.previous = now;
if self.focused && self.player.is_some() {
self.camera.turn(&self.keys, seconds);
if let Err(error) = self.move_player(elapsed) {
self.fail(event_loop, error);
return;
}
} else if self.focused {
let from = self.camera.position;
let bounds = self.camera.collision_bounds();
self.camera.update(&self.keys, seconds);
if self.collision_camera {
let delta = self.camera.position - from;
let mut collision = collisions::SceneCollisions {
world: &self.world,
binding: self.collision_binding,
};
match collision.resolve(
bounds,
horizon_core::geometry::Vec3::new(delta.x, delta.y, delta.z),
0.0,
false,
) {
Ok(movement) => {
self.camera.position =
from + glam::DVec3::new(movement.x, movement.y, movement.z)
}
Err(error) => {
self.fail(event_loop, error);
return;
}
}
}
}
let result = self.renderer.as_mut().unwrap().render(&self.camera);
match result {
Ok(true) => {
self.frames += 1;
self.next_redraw = Instant::now();
if self
.options
.frames
.is_some_and(|target| self.frames >= target)
{
event_loop.exit();
}
if self.diagnostics && self.title_at.elapsed() >= Duration::from_secs(1) {
let fps = (self.frames - self.title_frames) as f64
/ self.title_at.elapsed().as_secs_f64();
let health = self.player.as_ref().map_or_else(String::new, |p| {
format!(
" | Health {} | Food {} | Sprint {} | Pose {}{}",
p.health.health(),
p.health.food.food,
p.sprinting,
p.pose.name(),
if p.health.dead_or_dying() {
" (dead)"
} else {
""
}
)
});
self.window.as_ref().unwrap().set_title(&format!(
"Horizon — Development | {fps:.0} FPS | {} chunks | {} quads{health}",
self.world.chunks.len(),
self.mesh.cubes.len()
));
self.title_at = Instant::now();
self.title_frames = self.frames;
}
}
Ok(false) => self.next_redraw = Instant::now() + Duration::from_millis(100),
Err(error) => self.fail(event_loop, error),
}
}
_ => {}
}
}
fn device_event(&mut self, _: &ActiveEventLoop, _: DeviceId, event: DeviceEvent) {
if self.captured
&& self.focused
&& let DeviceEvent::MouseMotion { delta: (x, y) } = event
{
self.camera.look(x, y);
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout {
self.fail(event_loop, "frame-limited client run timed out");
return;
}
if Instant::now() >= self.next_redraw {
if let Some(window) = &self.window {
window.request_redraw();
}
event_loop.set_control_flow(if self.options.frames.is_some() {
ControlFlow::WaitUntil(self.started + self.options.timeout)
} else {
ControlFlow::Wait
});
} else {
event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_redraw));
}
}
}
fn run() -> Result<()> {
let Some(options) = Options::read()? else {
return Ok(());
};
let assets = Assets::load(&options.resources).map_err(|error| {
format!("{error}\nPrepare pinned resources with: python3 tools/prepare_native_client.py")
})?;
let world = TestWorld::new(&assets, options.radius)?;
let collision_binding = collisions::load(&options.resources, &assets.registry)?;
let motion_resources = MotionResources::load(&options.resources, &assets)?;
let mut visibility = models::load_visibility(&options.resources, &assets.registry)?;
let mesh = mesh::build(&world, &assets, &mut visibility)?;
eprintln!(
"Horizon development scene: {} resident chunks, {} merged cube faces, {} baked model faces.\nClick to capture mouse; WASD/Space/Shift move; arrows rotate; F4 toggles camera collisions; F5 toggles walking test; Esc releases; Ctrl+Q quits.",
world.chunks.len(),
mesh.cubes.len(),
mesh.models.len()
);
let now = Instant::now();
let mut app = App {
assets: &assets,
world,
collision_binding: &collision_binding,
collision_camera: false,
motion_resources: &motion_resources,
player: None,
motion_clock: FixedStep::default(),
previous_player_position: Vec3::ZERO,
eye_height: 1.62,
previous_eye_height: 1.62,
crouch_ticks: 0,
crouch_distance_cm: 0,
movement_ticks: 0,
sprint_ticks: 0,
sprint_distance_cm: 0,
walk_distance_cm: 0,
fall_damage_requests: 0,
last_requested_fall_damage: None,
visibility,
mesh_revision: 0,
mesh,
options,
window: None,
renderer: None,
camera: Camera::default(),
keys: HashSet::new(),
captured: false,
focused: true,
diagnostics: false,
started: now,
previous: now,
next_redraw: now,
title_at: now,
title_frames: 0,
frames: 0,
error: None,
};
EventLoop::new()?.run_app(&mut app)?;
app.write_report()?;
if let Some(error) = app.error {
return Err(error.into());
}
Ok(())
}
mod game;
fn main() {
if let Err(error) = run() {
if let Err(error) = game::run() {
eprintln!("Horizon: {error}");
std::process::exit(1);
}
-377
View File
@@ -1,377 +0,0 @@
//! Resident blockstate model meshing. Greedy rectangles preserve the texture
//! and signed UV basis of eligible unit-cube faces; other geometry stays baked.
use crate::{
Result,
assets::Assets,
models::{self, CubeStyle, ModelInstance},
world::TestWorld,
};
use horizon_core::{geometry::Direction, position::BlockPos};
use horizon_world::block_render::FaceVisibility;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Quad {
pub origin: [f32; 3],
pub extent: [f32; 2],
pub face: u32,
pub layer: u32,
pub uv_origin: [f32; 2],
pub uv_u: [f32; 2],
pub uv_v: [f32; 2],
pub shade: f32,
}
pub struct Mesh {
pub cubes: Vec<Quad>,
pub models: Vec<ModelInstance>,
pub visible_faces: usize,
pub culled_faces: usize,
pub model_blocks: usize,
}
fn position(face: usize, plane: usize, u: usize, v: usize) -> [usize; 3] {
match face {
0 | 1 => [u, plane, v],
2 | 3 => [u, v, plane],
_ => [plane, v, u],
}
}
pub fn build(
world: &TestWorld<'_>,
assets: &Assets,
visibility: &mut FaceVisibility,
) -> Result<Mesh> {
let mut mesh = Mesh {
cubes: Vec::new(),
models: Vec::new(),
visible_faces: 0,
culled_faces: 0,
model_blocks: 0,
};
for &(cx, cz) in world.chunks.keys() {
let mut masks = vec![[None; 256]; 6 * 16];
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let pos = BlockPos::new(cx * 16 + x, y, cz * 16 + z);
let state = world.block(pos.x, pos.y, pos.z);
if world.is_air(state) {
continue;
}
mesh.model_blocks += 1;
let selected = assets.model_catalog.collect(state, pos)?;
let mut visible = [false; 6];
for direction in Direction::ALL {
let [dx, dy, dz] = direction.normal();
let neighbor = world.block(pos.x + dx, pos.y + dy, pos.z + dz);
visible[direction as usize] =
visibility.should_render_face(state, neighbor, direction, true)?;
}
if selected.len() == 1
&& let Some(styles) = selected[0].1.cube
{
for (face, style) in styles.into_iter().enumerate() {
if !visible[face] {
mesh.culled_faces += 1;
continue;
}
mesh.visible_faces += 1;
let (plane, u, v) = match face {
0 | 1 => (y, x, z),
2 | 3 => (z, x, y),
_ => (x, z, y),
};
masks[face * 16 + plane as usize][(u + 16 * v) as usize] = Some(style);
}
} else {
for (_, model) in selected {
for face in &model.faces {
if face.quad.cull.is_some_and(|d| !visible[d as usize]) {
mesh.culled_faces += 1;
continue;
}
mesh.visible_faces += 1;
mesh.models.push(models::instance(face, pos));
}
}
}
}
}
}
for (index, mask) in masks.iter_mut().enumerate() {
merge(mask, index / 16, index % 16, cx, cz, &mut mesh.cubes);
}
}
Ok(mesh)
}
fn merge(
mask: &mut [Option<CubeStyle>; 256],
face: usize,
plane: usize,
cx: i32,
cz: i32,
quads: &mut Vec<Quad>,
) {
for v in 0..16 {
let mut u = 0;
while u < 16 {
let Some(style) = mask[u + v * 16] else {
u += 1;
continue;
};
let mut width = 1;
while u + width < 16 && mask[u + width + v * 16] == Some(style) {
width += 1;
}
let mut height = 1;
while v + height < 16
&& (u..u + width).all(|x| mask[x + (v + height) * 16] == Some(style))
{
height += 1;
}
for y in v..v + height {
for x in u..u + width {
mask[x + y * 16] = None;
}
}
let p = position(face, plane + usize::from(face % 2 == 1), u, v);
let [a, b, c, d, e, f] = style.uv.map(f32::from);
quads.push(Quad {
origin: [
(cx * 16 + p[0] as i32) as f32,
p[1] as f32,
(cz * 16 + p[2] as i32) as f32,
],
extent: [width as f32, height as f32],
face: face as u32,
layer: style.layer,
uv_origin: [a, b],
uv_u: [c, d],
uv_v: [e, f],
shade: f32::from_bits(style.shade_bits),
});
u += width;
}
}
}
#[cfg(test)]
fn index(x: usize, y: usize, z: usize) -> usize {
x + 18 * (z + 18 * y)
}
#[cfg(test)]
fn mesh_chunk(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32, quads: &mut Vec<Quad>) {
for face in 0..6 {
for plane in 0..16 {
let mut mask = [None; 256];
for v in 0..16 {
for u in 0..16 {
let p = position(face, plane + 1, u + 1, v + 1);
let mut adjacent = p;
let axis = match face {
0 | 1 => 1,
2 | 3 => 2,
_ => 0,
};
if face % 2 == 0 {
adjacent[axis] -= 1;
} else {
adjacent[axis] += 1;
}
let layer = cells[index(p[0], p[1], p[2])];
if layer >= 0 && cells[index(adjacent[0], adjacent[1], adjacent[2])] < 0 {
mask[u + 16 * v] = Some(CubeStyle {
layer: layer as u32,
uv: [0, 1, 1, 0, 0, -1],
shade_bits: 1f32.to_bits(),
});
}
}
}
merge(&mut mask, face, plane, cx, cz, quads);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
// Compare rectangles expanded to unit faces against direct voxel adjacency.
// The reference does not use the mesher's plane masks or coordinate helper.
fn verify(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32) -> Vec<Quad> {
let mut expected = BTreeSet::new();
let directions = [
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
[-1, 0, 0],
[1, 0, 0],
];
for y in 1..=16 {
for z in 1..=16 {
for x in 1..=16 {
let layer = cells[index(x, y, z)];
if layer < 0 {
continue;
}
for (face, [dx, dy, dz]) in directions.iter().enumerate() {
let neighbor = [
(x as i32 + dx) as usize,
(y as i32 + dy) as usize,
(z as i32 + dz) as usize,
];
if cells[index(neighbor[0], neighbor[1], neighbor[2])] < 0 {
expected.insert((
x as i32 - 1 + cx * 16,
y as i32 - 1,
z as i32 - 1 + cz * 16,
face as u32,
layer as u32,
));
}
}
}
}
}
let mut quads = Vec::new();
mesh_chunk(cells, cx, cz, &mut quads);
let mut actual = BTreeSet::new();
for quad in &quads {
assert!(
quad.extent
.iter()
.all(|&e| (1.0..=16.0).contains(&e) && e.fract() == 0.0)
);
for v in 0..quad.extent[1] as i32 {
for u in 0..quad.extent[0] as i32 {
let [x, y, z] = quad.origin.map(|n| n as i32);
let (x, y, z) = match quad.face {
0 => (x + u, y, z + v),
1 => (x + u, y - 1, z + v),
2 => (x + u, y + v, z),
3 => (x + u, y + v, z - 1),
4 => (x, y + v, z + u),
5 => (x - 1, y + v, z + u),
_ => panic!("invalid face"),
};
assert!(
actual.insert((x, y, z, quad.face, quad.layer)),
"overlapping faces"
);
}
}
}
assert_eq!(actual, expected);
quads
}
#[test]
fn merging_preserves_rotation_mirroring_shade_and_texture() {
let bases = [
[0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, -1, 0],
[1, 1, -1, 0, 0, -1],
[0, 1, 0, -1, 1, 0],
[1, 0, -1, 0, 0, 1],
[0, 1, 1, 0, 0, -1],
[0, 0, 0, 1, 1, 0],
[1, 1, 0, -1, -1, 0],
];
let original: [Option<CubeStyle>; 256] = std::array::from_fn(|i| {
(i % 17 != 0).then_some(CubeStyle {
layer: (i / 64) as u32,
uv: bases[(i / 4) % 8],
shade_bits: if i % 5 == 0 { 0.5f32 } else { 1f32 }.to_bits(),
})
});
for face in 0..6 {
let mut mask = original;
let mut quads = Vec::new();
merge(&mut mask, face, 4, -2, 3, &mut quads);
let mut covered = [false; 256];
for q in quads {
let p = [q.origin[0] + 32.0, q.origin[1], q.origin[2] - 48.0];
let (u0, v0) = match face {
0 | 1 => (p[0] as usize, p[2] as usize),
2 | 3 => (p[0] as usize, p[1] as usize),
_ => (p[2] as usize, p[1] as usize),
};
for dv in 0..q.extent[1] as usize {
for du in 0..q.extent[0] as usize {
let index = u0 + du + 16 * (v0 + dv);
assert!(!covered[index]);
covered[index] = true;
let style = original[index].unwrap();
assert_eq!(q.layer, style.layer);
assert_eq!(q.shade.to_bits(), style.shade_bits);
let [a, b, c, d, e, f] = style.uv.map(f32::from);
let local = [a + c * 0.25 + e * 0.75, b + d * 0.25 + f * 0.75];
let merged: [f32; 2] = std::array::from_fn(|axis| {
q.uv_origin[axis]
+ q.uv_u[axis] * (du as f32 + 0.25)
+ q.uv_v[axis] * (dv as f32 + 0.75)
});
assert_eq!(
local.map(|v| v.rem_euclid(1.0)),
merged.map(|v| v.rem_euclid(1.0))
);
}
}
}
assert_eq!(covered, original.map(|v| v.is_some()));
}
}
#[test]
fn empty_solid_and_neighbor_seams() {
let mut cells = [-1; 18 * 18 * 18];
assert!(verify(&cells, 0, 0).is_empty());
for y in 1..=16 {
for z in 1..=16 {
for x in 1..=16 {
cells[index(x, y, z)] = 3;
}
}
}
assert_eq!(verify(&cells, -3, 2).len(), 6);
// A solid neighbor removes only the shared boundary, including corners.
for y in 1..=16 {
for z in 1..=16 {
cells[index(17, y, z)] = 4;
}
}
assert_eq!(verify(&cells, -3, 2).len(), 5);
cells.fill(3);
assert!(verify(&cells, 1, -2).is_empty());
}
#[test]
fn cavities_material_boundaries_and_random_neighbors() {
let mut state = 0x183d_994e_058b_9432_u64;
for pattern in 0..12 {
let mut cells = [-1; 18 * 18 * 18];
for y in 0..18 {
for z in 0..18 {
for x in 0..18 {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
cells[index(x, y, z)] = match pattern {
0 => {
if x == 8 && y == 8 && z == 8 {
-1
} else {
0
}
}
1 => ((x + y + z) % 3) as i32,
_ => (state % 7) as i32 - 1,
};
}
}
}
verify(&cells, pattern - 6, 3 - pattern);
}
}
}
+671
View File
@@ -0,0 +1,671 @@
//! Section meshing on worker threads. Faces follow the baked blockstate models
//! with vanilla's neighbour culling; vertex lighting follows
//! `ModelBlockRenderer`'s smooth-lighting blend (four samples per corner, zero
//! samples replaced by the centre) and ambient-occlusion shade brightness.
//! Fluids follow `FluidRenderer` (corner heights, still/flowing sprites).
use crate::{
assets::Assets,
biome::Biomes,
blocks::{BlockFacts, Fluid, RenderShape},
chunk::{Chunk, MIN_Y},
models::catalog::BakedFace,
};
use horizon_core::{geometry::Direction, position::BlockPos};
use horizon_world::{block_render::FaceVisibility, registry::BlockStateId};
use std::sync::Arc;
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
/// Section-relative position.
pub pos: [f32; 3],
pub uv: [f32; 2],
pub layer: u32,
/// RGBA8: tint multiplied by directional shade and ambient occlusion.
pub color: u32,
/// Smooth light, 16x fixed point: sky in bits 0..8, block in bits 8..16.
pub light: u32,
}
#[derive(Default)]
pub struct SectionMesh {
pub solid: Vec<Vertex>,
pub translucent: Vec<Vertex>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tint {
None,
Grass,
TallGrassUpper,
Foliage,
DryFoliage,
Water,
Constant(u32),
Redstone(u8),
Stem(u8),
}
/// Per-state data the mesher needs on every block, flattened for speed.
#[derive(Clone, Copy)]
struct Info {
solid: bool,
/// `isCollisionShapeFullBlock` drives the 0.2 AO shade brightness.
full: bool,
/// Side blocks that are transparent let the AO corner sample through.
translucent: bool,
emission: u8,
fluid: Fluid,
level: u8,
model: bool,
tints: [Tint; 2],
}
pub struct MeshTables {
info: Vec<Info>,
pub visibility: FaceVisibility,
water_still: u32,
water_flow: u32,
lava_still: u32,
lava_flow: u32,
}
fn redstone_color(power: u8) -> u32 {
// RedstoneWireBlock.COLORS
let f = f32::from(power) / 15.0;
let r = f * 0.6 + if f > 0.0 { 0.4 } else { 0.3 };
let g = (f * f * 0.7 - 0.5).clamp(0.0, 1.0);
let b = (f * f * 0.6 - 0.7).clamp(0.0, 1.0);
((r * 255.0) as u32) << 16 | ((g * 255.0) as u32) << 8 | (b * 255.0) as u32
}
impl MeshTables {
pub fn new(
assets: &Assets,
facts: &BlockFacts,
visibility: FaceVisibility,
) -> crate::Result<Self> {
let layer = |name: &str| -> crate::Result<u32> {
assets
.sprite_layers
.get(name)
.copied()
.ok_or_else(|| format!("missing fluid sprite {name}").into())
};
let info = facts
.states
.iter()
.enumerate()
.map(|(id, s)| {
let props = assets
.registry
.state(BlockStateId(id as u32))
.map(|s| &s.properties);
let prop = |k: &str| -> u8 {
props
.and_then(|p| p.get(k))
.and_then(|v| v.parse().ok())
.unwrap_or(0)
};
let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name);
let tints = match name {
"large_fern" | "tall_grass" => {
if props.and_then(|p| p.get("half")).map(String::as_str) == Some("upper") {
[Tint::TallGrassUpper; 2]
} else {
[Tint::Grass; 2]
}
}
"fern" | "short_grass" | "potted_fern" | "bush" | "grass_block"
| "sugar_cane" => [Tint::Grass; 2],
"pink_petals" | "wildflowers" => [Tint::None, Tint::Grass],
"spruce_leaves" => [Tint::Constant(0x61_9961); 2],
"birch_leaves" => [Tint::Constant(0x80_A755); 2],
"oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves"
| "vine" | "mangrove_leaves" => [Tint::Foliage; 2],
"leaf_litter" => [Tint::DryFoliage; 2],
"water_cauldron" | "water" | "bubble_column" => [Tint::Water; 2],
"redstone_wire" => [Tint::Redstone(prop("power")); 2],
"attached_melon_stem" | "attached_pumpkin_stem" => {
[Tint::Constant(0xE0_C71C); 2]
}
"melon_stem" | "pumpkin_stem" => [Tint::Stem(prop("age")); 2],
"lily_pad" => [Tint::Constant(0x20_8030); 2],
_ => [Tint::None; 2],
};
Info {
solid: s.solid_render,
full: s.full_collision,
translucent: !s.solid_render || s.dampening == 0,
emission: s.emission,
fluid: s.fluid,
level: s.fluid_level,
model: s.render_shape == RenderShape::Model,
tints,
}
})
.collect();
Ok(Self {
info,
visibility,
water_still: layer("minecraft:block/water_still")?,
water_flow: layer("minecraft:block/water_flow")?,
lava_still: layer("minecraft:block/lava_still")?,
lava_flow: layer("minecraft:block/lava_flow")?,
})
}
}
const P: usize = 18;
#[inline]
fn pi(x: i32, y: i32, z: i32) -> usize {
((y + 1) as usize * P + (z + 1) as usize) * P + (x + 1) as usize
}
/// Blocks and light of one section plus a one-block border.
struct Padded {
blocks: Vec<u16>,
light: Vec<u8>,
}
impl Padded {
fn new(region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> Self {
let mut blocks = vec![0u16; P * P * P];
let mut light = vec![0u8; P * P * P];
let base_y = MIN_Y + sy * 16;
for y in -1..17 {
let wy = base_y + y;
for z in -1..17i32 {
for x in -1..17i32 {
let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize];
let i = pi(x, y, z);
if let Some(c) = chunk {
blocks[i] = c.get(x & 15, wy, z & 15);
light[i] = c.light(x & 15, wy, z & 15);
} else {
light[i] = 0xF0;
}
}
}
}
Self { blocks, light }
}
}
#[derive(Clone, Copy)]
struct Colors {
grass: [u32; 256],
tall_upper: [u32; 256],
foliage: [u32; 256],
dry: [u32; 256],
water: [u32; 256],
}
fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y: i32) -> Colors {
// Vanilla blends over a (2r+1)^2 area; r = 2 is the default option.
const R: i32 = 2;
let biome_at = |x: i32, z: i32| -> u16 {
region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]
.map_or(0, |c| c.biome(x & 15, y, z & 15))
};
let mut colors = Colors {
grass: [0; 256],
tall_upper: [0; 256],
foliage: [0; 256],
dry: [0; 256],
water: [0; 256],
};
let avg = |f: &dyn Fn(u16, i32, i32) -> u32, x: i32, z: i32| -> u32 {
let (mut r, mut g, mut b) = (0, 0, 0);
for dz in -R..=R {
for dx in -R..=R {
let c = f(biome_at(x + dx, z + dz), x + dx, z + dz);
r += c >> 16 & 255;
g += c >> 8 & 255;
b += c & 255;
}
}
let n = ((2 * R + 1) * (2 * R + 1)) as u32;
(r / n) << 16 | (g / n) << 8 | b / n
};
for z in 0..16 {
for x in 0..16 {
let i = (z * 16 + x) as usize;
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
colors.grass[i] = avg(
&|b, dx, dz| biomes.grass(b, f64::from(wx + dx - x), f64::from(wz + dz - z)),
x,
z,
);
colors.tall_upper[i] = colors.grass[i];
colors.foliage[i] = avg(&|b, _, _| biomes.get(b).foliage, x, z);
colors.dry[i] = avg(&|b, _, _| biomes.get(b).dry_foliage, x, z);
colors.water[i] = avg(&|b, _, _| biomes.get(b).water, x, z);
}
}
colors
}
fn shade(direction: horizon_assets::model::Direction) -> f32 {
use horizon_assets::model::Direction as D;
match direction {
D::Down => 0.5,
D::Up => 1.0,
D::North | D::South => 0.8,
D::West | D::East => 0.6,
}
}
fn pack_color(rgb: u32, brightness: f32) -> u32 {
let r = ((rgb >> 16 & 255) as f32 * brightness) as u32;
let g = ((rgb >> 8 & 255) as f32 * brightness) as u32;
let b = ((rgb & 255) as f32 * brightness) as u32;
0xFF00_0000 | b << 16 | g << 8 | r
}
fn pack_light(sky: f32, block: f32) -> u32 {
(sky * 16.0).clamp(0.0, 255.0) as u32 | ((block * 16.0).clamp(0.0, 255.0) as u32) << 8
}
pub struct Mesher<'a> {
pub assets: &'a Assets,
pub tables: &'a MeshTables,
pub biomes: &'a Biomes,
pub visibility: FaceVisibility,
}
impl Mesher<'_> {
/// `region[dz][dx]` are the chunks around the meshed column (centre 1,1).
pub fn mesh(&mut self, region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> SectionMesh {
let mut out = SectionMesh::default();
let center = region[1][1].expect("centre chunk");
let section = &center.sections[sy as usize];
if section.is_uniform(0) {
return out;
}
let pad = Padded::new(region, sy);
let base_y = MIN_Y + sy * 16;
let colors = blend(region, self.biomes, center.x, center.z, base_y + 8);
let info = &self.tables.info;
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let id = pad.blocks[pi(x, y, z)];
if id == 0 {
continue;
}
let state = info[id as usize];
if state.solid
&& Direction::ALL.iter().all(|d| {
let [dx, dy, dz] = d.normal();
info[pad.blocks[pi(x + dx, y + dy, z + dz)] as usize].solid
})
{
continue;
}
if state.fluid != Fluid::None {
self.fluid(&pad, &colors, &mut out, x, y, z, id);
}
if !state.model {
continue;
}
let world = BlockPos::new(center.x * 16 + x, base_y + y, center.z * 16 + z);
let Ok(models) = self.assets.model_catalog.collect(BlockStateId(id.into()), world)
else {
continue;
};
let mut visible = [false; 6];
for d in Direction::ALL {
let [dx, dy, dz] = d.normal();
let neighbor = pad.blocks[pi(x + dx, y + dy, z + dz)];
visible[d as usize] = self
.visibility
.should_render_face(
BlockStateId(id.into()),
BlockStateId(neighbor.into()),
d,
true,
)
.unwrap_or(true);
}
for (_, model) in models {
for face in &model.faces {
if face.quad.cull.is_some_and(|d| !visible[d as usize]) {
continue;
}
self.face(
&pad,
&colors,
&mut out,
[x, y, z],
face,
model.ambient_occlusion,
state,
);
}
}
}
}
}
out
}
fn tint(state: Info, index: i32, colors: &Colors, x: i32, z: i32) -> u32 {
if index < 0 {
return 0xFF_FFFF;
}
let column = (z * 16 + x) as usize;
match state.tints[(index as usize).min(1)] {
Tint::None => 0xFF_FFFF,
Tint::Grass => colors.grass[column],
Tint::TallGrassUpper => colors.tall_upper[column],
Tint::Foliage => colors.foliage[column],
Tint::DryFoliage => colors.dry[column],
Tint::Water => colors.water[column],
Tint::Constant(c) => c,
Tint::Redstone(p) => redstone_color(p),
Tint::Stem(age) => {
let a = u32::from(age);
(a * 32) << 16 | (255 - a * 8) << 8 | a * 4
}
}
}
#[allow(clippy::too_many_arguments)]
fn face(
&self,
pad: &Padded,
colors: &Colors,
out: &mut SectionMesh,
[x, y, z]: [i32; 3],
face: &BakedFace,
ao: bool,
state: Info,
) {
let q = &face.quad;
let facing = q.facing;
let normal = Direction::ALL[facing as usize].normal();
let axis = normal.iter().position(|&n| n != 0).unwrap_or(1);
let positive = normal[axis] > 0;
let on_boundary = q.positions.iter().all(|p| {
if positive {
p[axis] >= 1.0 - 1e-4
} else {
p[axis] <= 1e-4
}
});
let base = if on_boundary {
[x + normal[0], y + normal[1], z + normal[2]]
} else {
[x, y, z]
};
let tint = Self::tint(state, q.tint_index, colors, x, z);
let directional = match q.shade_direction_override {
Some(d) => shade(d),
None => shade(facing),
};
let info = &self.tables.info;
let light_at = |p: [i32; 3]| -> u32 {
let i = pi(p[0], p[1], p[2]);
let packed = pad.light[i];
let s = info[pad.blocks[i] as usize];
let block = (packed & 15).max(s.emission);
u32::from(packed >> 4) << 16 | u32::from(block)
};
let shade_at = |p: [i32; 3]| -> f32 {
if info[pad.blocks[pi(p[0], p[1], p[2])] as usize].full {
0.2
} else {
1.0
}
};
let open_at = |p: [i32; 3]| -> bool { info[pad.blocks[pi(p[0], p[1], p[2])] as usize].translucent };
// Tangent axes of the face plane.
let (ua, va) = match axis {
0 => (2, 1),
1 => (0, 2),
_ => (0, 1),
};
let center_light = light_at(base);
let center_shade = shade_at(base);
// Corner values for (su, sv) in {0,1}^2 -> (sky, block, ao).
let mut corners = [[0f32; 3]; 4];
for (ci, corner) in corners.iter_mut().enumerate() {
let su = if ci & 1 == 0 { -1 } else { 1 };
let sv = if ci & 2 == 0 { -1 } else { 1 };
let mut p1 = base;
p1[ua] += su;
let mut p2 = base;
p2[va] += sv;
let mut pc = base;
pc[ua] += su;
pc[va] += sv;
let (l1, l2) = (light_at(p1), light_at(p2));
let (lc, ac) = if open_at(p1) || open_at(p2) {
(light_at(pc), shade_at(pc))
} else {
(l1, shade_at(p1))
};
// ModelBlockRenderer.blend: zero samples take the centre value.
let fix = |v: u32| if v == 0 { center_light } else { v };
let sum = fix(l1) + fix(l2) + fix(lc) + center_light;
corner[0] = (sum >> 16) as f32 / 4.0;
corner[1] = (sum & 0xFFFF) as f32 / 4.0;
corner[2] = (shade_at(p1) + shade_at(p2) + ac + center_shade) / 4.0;
}
let flat_sky = (center_light >> 16) as f32;
let flat_block = (center_light & 0xFFFF) as f32;
let target = if face.translucent {
&mut out.translucent
} else {
&mut out.solid
};
for (p, uv) in q.positions.iter().zip(q.uv) {
let (sky, block, occlusion) = if ao {
let u = p[ua].clamp(0.0, 1.0);
let v = p[va].clamp(0.0, 1.0);
let lerp = |k: usize| {
let a = corners[0][k] * (1.0 - u) + corners[1][k] * u;
let b = corners[2][k] * (1.0 - u) + corners[3][k] * u;
a * (1.0 - v) + b * v
};
(lerp(0), lerp(1), lerp(2))
} else {
(flat_sky, flat_block, 1.0)
};
target.push(Vertex {
pos: [p[0] + x as f32, p[1] + y as f32, p[2] + z as f32],
uv,
layer: face.layer,
color: pack_color(tint, directional * occlusion),
light: pack_light(sky, block),
});
}
}
#[allow(clippy::too_many_arguments)]
fn fluid(&self, pad: &Padded, colors: &Colors, out: &mut SectionMesh, x: i32, y: i32, z: i32, id: u16) {
let info = &self.tables.info;
let me = info[id as usize];
let water = me.fluid == Fluid::Water;
let same = |p: [i32; 3]| info[pad.blocks[pi(p[0], p[1], p[2])] as usize].fluid == me.fluid;
let solid = |p: [i32; 3]| {
let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize];
s.solid || s.full
};
let height = |p: [i32; 3]| -> f32 {
let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize];
if s.fluid == me.fluid {
if same([p[0], p[1] + 1, p[2]]) {
1.0
} else {
f32::from(s.level) / 9.0
}
} else if !(s.solid || s.full) {
0.0
} else {
-1.0
}
};
let own = height([x, y, z]);
let corner = |a: f32, b: f32, c: [i32; 3]| -> f32 {
if a >= 1.0 || b >= 1.0 {
return 1.0;
}
let mut sum = [0.0f32; 2];
let mut add = |h: f32| {
if h >= 0.8 {
sum[0] += h * 10.0;
sum[1] += 10.0;
} else if h >= 0.0 {
sum[0] += h;
sum[1] += 1.0;
}
};
if a > 0.0 || b > 0.0 {
let hc = height(c);
if hc >= 1.0 {
return 1.0;
}
add(hc);
}
add(own);
add(a);
add(b);
sum[0] / sum[1]
};
let (nw, sw, se, ne) = if own >= 1.0 {
(1.0, 1.0, 1.0, 1.0)
} else {
let n = height([x, y, z - 1]);
let s = height([x, y, z + 1]);
let e = height([x + 1, y, z]);
let w = height([x - 1, y, z]);
(
corner(n, w, [x - 1, y, z - 1]),
corner(s, w, [x - 1, y, z + 1]),
corner(s, e, [x + 1, y, z + 1]),
corner(n, e, [x + 1, y, z - 1]),
)
};
let tint = if water {
colors.water[(z * 16 + x) as usize]
} else {
0xFF_FFFF
};
let (still, flow) = if water {
(self.tables.water_still, self.tables.water_flow)
} else {
(self.tables.lava_still, self.tables.lava_flow)
};
let light = |p: [i32; 3]| {
let packed = pad.light[pi(p[0], p[1], p[2])];
let emission = if water { 0 } else { 15 };
pack_light(f32::from(packed >> 4), f32::from((packed & 15).max(emission)))
};
let target = if water {
&mut out.translucent
} else {
&mut out.solid
};
let (fx, fy, fz) = (x as f32, y as f32, z as f32);
let quad = |target: &mut Vec<Vertex>, v: [([f32; 3], [f32; 2]); 4], layer: u32, b: f32, l: u32, back: bool| {
for (p, uv) in v {
target.push(Vertex {
pos: p,
uv,
layer,
color: pack_color(tint, b),
light: l,
});
}
if back {
for i in [0, 3, 2, 1] {
let (p, uv) = v[i];
target.push(Vertex {
pos: p,
uv,
layer,
color: pack_color(tint, b),
light: l,
});
}
}
};
let above_same = same([x, y + 1, z]);
if !above_same && !solid([x, y + 1, z]) || !above_same && own < 1.0 {
let o = 0.001;
let (h0, h1, h2, h3) = (nw - o, sw - o, se - o, ne - o);
// Flow direction from neighbour height differences.
let mut fxv = 0.0f32;
let mut fzv = 0.0f32;
if own < 1.0 && me.level < 8 || own < 0.88 {
for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
let h = height([x + dx, y, z + dz]);
if h >= 0.0 {
let d = own - h.max(0.0);
fxv += dx as f32 * d;
fzv += dz as f32 * d;
}
}
}
let (layer, uvs) = if fxv.abs() < 1e-4 && fzv.abs() < 1e-4 {
(still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]])
} else {
let angle = fzv.atan2(fxv) - std::f32::consts::FRAC_PI_2;
let (s, c) = (angle.sin() * 0.25, angle.cos() * 0.25);
// Flowing sprites are sampled over their top-left quarter-scaled region (getU(0.5+..) of 16 units).
(
flow,
[
[0.5 + (-c - s), 0.5 + (-c + s)],
[0.5 + (-c + s), 0.5 + (c + s)],
[0.5 + (c + s), 0.5 + (c - s)],
[0.5 + (c - s), 0.5 + (-c - s)],
],
)
};
quad(
target,
[
([fx, fy + h0, fz], uvs[0]),
([fx, fy + h1, fz + 1.0], uvs[1]),
([fx + 1.0, fy + h2, fz + 1.0], uvs[2]),
([fx + 1.0, fy + h3, fz], uvs[3]),
],
layer,
1.0,
light([x, y, z]),
water && !solid([x, y + 1, z]),
);
}
if !same([x, y - 1, z]) && !solid([x, y - 1, z]) {
quad(
target,
[
([fx, fy + 0.001, fz], [0.0, 0.0]),
([fx + 1.0, fy + 0.001, fz], [1.0, 0.0]),
([fx + 1.0, fy + 0.001, fz + 1.0], [1.0, 1.0]),
([fx, fy + 0.001, fz + 1.0], [0.0, 1.0]),
],
still,
0.5,
light([x, y - 1, z]),
false,
);
}
let o = 0.001;
for (dx, dz, h0, h1, p0, p1, sh) in [
(0, -1, nw, ne, [fx, fz + o], [fx + 1.0, fz + o], 0.8),
(0, 1, se, sw, [fx + 1.0, fz + 1.0 - o], [fx, fz + 1.0 - o], 0.8),
(-1, 0, sw, nw, [fx + o, fz + 1.0], [fx + o, fz], 0.6),
(1, 0, ne, se, [fx + 1.0 - o, fz], [fx + 1.0 - o, fz + 1.0], 0.6),
] {
let n = [x + dx, y, z + dz];
if same(n) || solid(n) {
continue;
}
let v0 = (1.0 - h0) * 0.5;
let v1 = (1.0 - h1) * 0.5;
quad(
target,
[
([p0[0], fy + h0, p0[1]], [0.0, v0]),
([p1[0], fy + h1, p1[1]], [0.5, v1]),
([p1[0], fy, p1[1]], [0.5, 0.5]),
([p0[0], fy, p0[1]], [0.0, 0.5]),
],
flow,
sh,
light([x, y, z]),
water,
);
}
}
}
/// Snapshot of the 3x3 chunk neighbourhood used by a worker job.
pub type Region = [[Option<Arc<Chunk>>; 3]; 3];
pub fn borrow(region: &Region) -> [[Option<&Chunk>; 3]; 3] {
std::array::from_fn(|z| std::array::from_fn(|x| region[z][x].as_deref()))
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! A blockstate-driven inspection gallery, separate from gameplay simulation.
mod catalog;
pub mod catalog;
mod cube;
use crate::{Result, sprites::Sprites};
pub use catalog::StateModels;
+23 -7
View File
@@ -35,6 +35,7 @@ pub struct BakedFace {
pub translucent: bool,
}
pub struct BakedModel {
pub ambient_occlusion: bool,
pub faces: Vec<BakedFace>,
pub cube: Option<[super::cube::CubeStyle; 6]>,
}
@@ -59,6 +60,14 @@ impl StateModels {
let mut choices = Vec::new();
let mut states = BTreeMap::new();
let mut variants = BTreeSet::new();
let mut by_name: std::collections::HashMap<&str, Vec<BlockStateId>> =
std::collections::HashMap::new();
for i in 0..registry.len() {
let id = BlockStateId(i as u32);
if let Some(state) = registry.state(id) {
by_name.entry(state.name.as_str()).or_default().push(id);
}
}
for block in blocks.iter().copied().collect::<BTreeSet<_>>() {
let name = format!("minecraft:{block}");
let facts = facts.get(&name).ok_or("missing block model state schema")?;
@@ -103,12 +112,12 @@ impl StateModels {
)?;
let definition = BlockStateDefinition::from_json(&resource)?;
let bound = definition.bind(&schema, &possible)?;
let native_order: Vec<_> = (0..registry.len())
.filter_map(|i| {
let id = BlockStateId(i as u32);
let state = registry.state(id)?;
(state.name == name).then_some((id, &state.properties))
})
let native_order: Vec<_> = by_name
.get(name.as_str())
.map(Vec::as_slice)
.unwrap_or_default()
.iter()
.map(|&id| (id, &registry.state(id).expect("indexed state").properties))
.collect();
if native_order.len() != possible.len()
|| native_order
@@ -181,7 +190,14 @@ impl StateModels {
})
.collect::<Result<_>>()?;
let cube = super::cube::cube_styles(&faces);
baked.insert((name, turns, lock), BakedModel { faces, cube });
baked.insert(
(name, turns, lock),
BakedModel {
ambient_occlusion: model.ambient_occlusion,
faces,
cube,
},
);
}
Ok(Self {
choices,
+2 -2
View File
@@ -1,7 +1,7 @@
//! Stored movement state for the resident scene. This binds the validated air,
//! jump, collision, support, restitution and stored health bindings. Entity lifecycle,
//! block-inside effects and audiovisual event consumers remain separate work.
use crate::{Result, assets::Assets, collisions::SceneCollisions, world::TestWorld};
use crate::{Result, assets::Assets, collisions::SceneCollisions, world::World};
use horizon_core::{
geometry::{Aabb, Vec3, VoxelShape, traverse_blocks},
position::BlockPos,
@@ -300,7 +300,7 @@ impl PlayerMotion {
pub struct MotionWorld<'p, 'w, 'r> {
pub player: &'p mut PlayerMotion,
pub scene: &'w mut TestWorld<'r>,
pub scene: &'w mut World,
pub assets: &'r Assets,
pub collision_binding: &'w BlockCollisionRegistry<'r>,
pub resources: &'w MotionResources,
+87
View File
@@ -0,0 +1,87 @@
//! Block particles (`TerrainParticle`): destroy bursts and mining crumbs that
//! sample a random quarter of the block's texture, fall with gravity and
//! expire after a randomized lifetime.
use crate::world::World;
use horizon_core::random::{LegacyRandom, RandomSource};
#[derive(Clone, Debug)]
pub struct Particle {
pub position: [f64; 3],
pub previous: [f64; 3],
pub velocity: [f64; 3],
pub age: u32,
pub lifetime: u32,
pub size: f32,
pub sprite: String,
/// Sub-rectangle of the sprite in 0..1 (u0, v0, u1, v1).
pub uv: [f32; 4],
pub tint: u32,
pub gravity: f64,
pub on_ground: bool,
}
impl Particle {
/// TerrainParticle(level, x, y, z, xa, ya, za, state)
pub fn terrain(random: &mut LegacyRandom, position: [f64; 3], velocity: [f64; 3], sprite: String, tint: u32) -> Self {
// Particle constructor: random jitter of velocity, normalized speed.
let mut v = [
velocity[0] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4,
velocity[1] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4,
velocity[2] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4,
];
let speed = f64::from(random.next_float() + random.next_float() + 1.0) * 0.15;
let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-9);
for (i, c) in v.iter_mut().enumerate() {
*c = *c / length * speed * 0.4;
if i == 1 {
*c += 0.1;
}
}
let u = random.next_float() * 3.0 / 4.0;
let w = random.next_float() * 3.0 / 4.0;
// SingleQuadParticle quadSize: 0.1 * (rand*0.5+0.5) * 2, halved for terrain.
let size = 0.1 * (random.next_float() * 0.5 + 0.5);
let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as u32;
Self {
position,
previous: position,
velocity: v,
age: 0,
lifetime,
size,
sprite,
uv: [u, w, u + 0.25, w + 0.25],
tint,
gravity: 1.0,
on_ground: false,
}
}
pub fn tick(&mut self, world: &World, solid: impl Fn(u16) -> bool) -> bool {
self.previous = self.position;
self.age += 1;
if self.age >= self.lifetime {
return false;
}
self.velocity[1] -= 0.04 * self.gravity;
for axis in 0..3 {
let mut next = self.position;
next[axis] += self.velocity[axis];
let block = world.block(next[0].floor() as i32, next[1].floor() as i32, next[2].floor() as i32);
if solid(block.0 as u16) {
if axis == 1 && self.velocity[1] < 0.0 {
self.on_ground = true;
}
self.velocity[axis] = 0.0;
} else {
self.position = next;
}
}
for c in &mut self.velocity {
*c *= 0.98;
}
if self.on_ground {
self.velocity[0] *= 0.7;
self.velocity[2] *= 0.7;
}
true
}
}
-442
View File
@@ -1,442 +0,0 @@
use crate::{Result, assets::Assets, camera::Camera, mesh::Quad, models::ModelInstance};
use std::{sync::Arc, time::Instant};
use wgpu::util::DeviceExt;
use winit::window::Window;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniforms {
matrix: [[f32; 4]; 4],
position: [f32; 4],
fog: [f32; 4],
}
pub struct Renderer {
instance: wgpu::Instance,
surface: wgpu::Surface<'static>,
window: Arc<Window>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
pipeline: wgpu::RenderPipeline,
model_pipeline: wgpu::RenderPipeline,
model_quads: wgpu::Buffer,
model_quad_count: u32,
sprite_texture: wgpu::Texture,
sprite_size: u32,
animations: Vec<(crate::sprites::SpriteAnimation, usize)>,
animation_started: Instant,
pub animation_uploads: u64,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
quads: wgpu::Buffer,
depth: wgpu::TextureView,
pub quad_count: u32,
pub info: wgpu::AdapterInfo,
pub suspended: bool,
fog_distance: f32,
}
impl Renderer {
pub fn replace_mesh(&mut self, quads: &[Quad], model_faces: &[ModelInstance]) -> Result<()> {
let quad_count = u32::try_from(quads.len())?;
let model_quad_count = u32::try_from(model_faces.len())?;
self.quads = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Updated resident cube faces"),
contents: bytemuck::cast_slice(quads),
usage: wgpu::BufferUsages::VERTEX,
});
self.model_quads = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Updated resident model faces"),
contents: bytemuck::cast_slice(model_faces),
usage: wgpu::BufferUsages::VERTEX,
});
self.quad_count = quad_count;
self.model_quad_count = model_quad_count;
Ok(())
}
pub async fn new(
window: Arc<Window>,
assets: &Assets,
quads: &[Quad],
model_faces: &[ModelInstance],
fog_distance: f32,
) -> Result<Self> {
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
let surface = instance.create_surface(window.clone())?;
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
..Default::default()
})
.await?;
let info = adapter.get_info();
eprintln!(
"Horizon renderer: {} ({:?}, {:?})",
info.name, info.backend, info.device_type
);
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
..Default::default()
})
.await?;
let size = window.inner_size();
let mut config = surface
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
.ok_or("surface has no supported configuration")?;
let caps = surface.get_capabilities(&adapter);
config.format = caps
.formats
.iter()
.copied()
.find(wgpu::TextureFormat::is_srgb)
.unwrap_or(config.format);
config.present_mode = wgpu::PresentMode::Fifo;
surface.configure(&device, &config);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon cube renderer"),
source: wgpu::ShaderSource::Wgsl(include_str!("world.wgsl").into()),
});
let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon world bindings"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon world layout"),
bind_group_layouts: &[Some(&bindings)],
..Default::default()
});
let create_pipeline =
|label: &str, vertex: &str, fragment: &str, buffer: wgpu::VertexBufferLayout<'_>| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(vertex),
compilation_options: Default::default(),
buffers: &[Some(buffer)],
},
primitive: wgpu::PrimitiveState {
cull_mode: Some(wgpu::Face::Back),
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Less),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(fragment),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Uint32,4=>Float32x2,5=>Float32x2,6=>Float32x2,7=>Float32];
let pipeline = create_pipeline(
"Horizon opaque cubes",
"vs_main",
"fs_main",
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Quad>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &attributes,
},
);
let model_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3,2=>Float32x3,3=>Float32x3,4=>Float32x2,5=>Float32x2,6=>Float32x2,7=>Float32x2,8=>Uint32,9=>Float32];
let model_pipeline = create_pipeline(
"Horizon model geometry",
"vs_model",
"fs_model",
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<ModelInstance>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &model_attributes,
},
);
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon camera"),
size: std::mem::size_of::<Uniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let texture = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some("Pinned block sprites"),
size: wgpu::Extent3d {
width: assets.sprite_size,
height: assets.sprite_size,
depth_or_array_layers: assets.texture_layers,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&assets.pixels,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Repeating nearest cube sprites"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon world resources"),
layout: &bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let quad_count = u32::try_from(quads.len())?;
let quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Greedy cube faces"),
contents: bytemuck::cast_slice(quads),
usage: wgpu::BufferUsages::VERTEX,
});
let model_quad_count = u32::try_from(model_faces.len())?;
let model_quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Baked vanilla model faces"),
contents: bytemuck::cast_slice(model_faces),
usage: wgpu::BufferUsages::VERTEX,
});
let depth = Self::depth(&device, &config);
Ok(Self {
instance,
surface,
window,
device,
queue,
config,
pipeline,
model_pipeline,
model_quads,
model_quad_count,
sprite_texture: texture,
sprite_size: assets.sprite_size,
animations: assets
.animations
.iter()
.map(|a| (a.clone(), a.frame(0)))
.collect(),
animation_started: Instant::now(),
animation_uploads: 0,
group,
uniform,
quads,
depth,
quad_count,
info,
suspended: size.width == 0 || size.height == 0,
fog_distance,
})
}
fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon depth"),
size: wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
.create_view(&Default::default())
}
pub fn resize(&mut self, width: u32, height: u32) {
self.suspended = width == 0 || height == 0;
if self.suspended {
return;
}
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.device, &self.config);
self.depth = Self::depth(&self.device, &self.config);
}
pub fn render(&mut self, camera: &Camera) -> Result<bool> {
if self.suspended {
return Ok(false);
}
let (frame, reconfigure) = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(frame) => (frame, false),
wgpu::CurrentSurfaceTexture::Suboptimal(frame) => (frame, true),
wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
return Ok(false);
}
wgpu::CurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.device, &self.config);
return Ok(false);
}
wgpu::CurrentSurfaceTexture::Lost => {
self.surface = self.instance.create_surface(self.window.clone())?;
self.surface.configure(&self.device, &self.config);
return Ok(false);
}
wgpu::CurrentSurfaceTexture::Validation => {
return Err("surface acquisition failed validation".into());
}
};
// Inspection textures advance at 20 ticks/s independently of presentation.
let tick = self.animation_started.elapsed().as_millis() / 50;
for (animation, previous) in &mut self.animations {
let frame = animation.frame(tick as u64);
if frame != *previous {
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.sprite_texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
y: 0,
z: animation.layer,
},
aspect: wgpu::TextureAspect::All,
},
animation.pixels(frame),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(self.sprite_size * 4),
rows_per_image: Some(self.sprite_size),
},
wgpu::Extent3d {
width: self.sprite_size,
height: self.sprite_size,
depth_or_array_layers: 1,
},
);
*previous = frame;
self.animation_uploads += 1;
}
}
let fog = [0.35, 0.55, 0.80, 1.0];
let p = camera.position.as_vec3();
let uniforms = Uniforms {
matrix: camera
.matrix(self.config.width as f32 / self.config.height as f32)
.to_cols_array_2d(),
position: [p.x, p.y, p.z, self.fog_distance],
fog,
};
self.queue
.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniforms));
let view = frame.texture.create_view(&Default::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Horizon frame"),
});
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: f64::from(fog[0]),
g: f64::from(fog[1]),
b: f64::from(fog[2]),
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.quads.slice(..));
pass.draw(0..6, 0..self.quad_count);
pass.set_pipeline(&self.model_pipeline);
pass.set_vertex_buffer(0, self.model_quads.slice(..));
pass.draw(0..6, 0..self.model_quad_count);
}
self.queue.submit([encoder.finish()]);
self.window.pre_present_notify();
self.queue.present(frame);
if reconfigure {
self.surface.configure(&self.device, &self.config);
}
Ok(true)
}
}
+421
View File
@@ -0,0 +1,421 @@
//! World persistence in vanilla's Anvil layout: `region/r.X.Z.mca` files with
//! zlib-compressed chunk NBT (paletted `block_states`/`biomes` per section) and
//! a gzip `level.dat`. Light is not stored (`isLightOn: 0`), so both Horizon and
//! vanilla relight saved chunks on load.
use crate::{
Result,
biome::Biomes,
chunk::{Blocks, Chunk, MIN_Y, SECTIONS},
streaming::ChunkGenerator,
};
use horizon_core::position::ChunkPos;
use horizon_world::{
DATA_VERSION,
chunk::BlockState,
compression::Compression,
nbt::{self, Limits, NamedTag, Tag},
region::{ChunkRecord, RegionFile, RegionWriter},
registry::{BlockRegistry, BlockStateId},
};
use std::{
collections::{BTreeMap, HashMap},
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
fn pack(indices: &[u16], bits: u32) -> Vec<i64> {
let per_long = (64 / bits) as usize;
let mut longs = vec![0i64; indices.len().div_ceil(per_long)];
for (i, &v) in indices.iter().enumerate() {
longs[i / per_long] |= (i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits);
}
longs
}
fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec<u16> {
let per_long = (64 / bits) as usize;
let mask = (1u64 << bits) - 1;
(0..count)
.map(|i| {
longs
.get(i / per_long)
.map_or(0, |&l| ((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16)
})
.collect()
}
fn bits_for(len: usize, min: u32) -> u32 {
(usize::BITS - (len.max(1) - 1).leading_zeros()).max(min)
}
fn string(s: &str) -> Tag {
Tag::String(s.into())
}
pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> NamedTag {
let mut sections = Vec::new();
for (si, section) in chunk.sections.iter().enumerate() {
let y = (MIN_Y >> 4) + si as i32;
let ids: Vec<u16> = match &section.blocks {
Blocks::Uniform(v) => vec![*v],
Blocks::Full(a) => a.to_vec(),
};
let mut palette: Vec<u16> = Vec::new();
let mut lookup: HashMap<u16, u16> = HashMap::new();
let indices: Vec<u16> = ids
.iter()
.map(|id| {
*lookup.entry(*id).or_insert_with(|| {
palette.push(*id);
(palette.len() - 1) as u16
})
})
.collect();
let mut states = vec![(
"palette",
Tag::List(
palette
.iter()
.map(|id| {
registry
.state(BlockStateId(u32::from(*id)))
.map_or_else(|| Tag::compound([("Name", string("minecraft:air"))]), BlockState::to_nbt)
})
.collect(),
),
)];
if palette.len() > 1 {
states.push(("data", Tag::LongArray(pack(&indices, bits_for(palette.len(), 4)))));
}
let quart: Vec<u16> = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect();
let mut biome_palette: Vec<u16> = Vec::new();
let biome_indices: Vec<u16> = quart
.iter()
.map(|b| match biome_palette.iter().position(|p| p == b) {
Some(i) => i as u16,
None => {
biome_palette.push(*b);
(biome_palette.len() - 1) as u16
}
})
.collect();
let mut biome_tag = vec![(
"palette",
Tag::List(biome_palette.iter().map(|b| string(&biomes.get(*b).name)).collect()),
)];
if biome_palette.len() > 1 {
biome_tag.push(("data", Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0)))));
}
sections.push(Tag::compound([
("Y", Tag::Byte(y as i8)),
("block_states", Tag::compound(states)),
("biomes", Tag::compound(biome_tag)),
]));
}
NamedTag {
name: "".into(),
tag: Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("xPos", Tag::Int(chunk.x)),
("zPos", Tag::Int(chunk.z)),
("yPos", Tag::Int(MIN_Y >> 4)),
("Status", string("minecraft:full")),
("LastUpdate", Tag::Long(0)),
("InhabitedTime", Tag::Long(0)),
("isLightOn", Tag::Byte(0)),
("sections", Tag::List(sections)),
("block_entities", Tag::List(vec![])),
]),
}
}
pub fn decode(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes) -> Option<Chunk> {
let tag = &root.tag;
let Tag::Int(x) = tag.get("xPos")? else { return None };
let Tag::Int(z) = tag.get("zPos")? else { return None };
let mut chunk = Chunk::empty(*x, *z);
let air = registry.default_state("minecraft:air")?.0 as u16;
let mut cache: HashMap<String, u16> = HashMap::new();
let mut biome_data = (*chunk.biomes).clone();
let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk) };
for section in sections {
let Some(Tag::Byte(y)) = section.get("Y") else { continue };
let si = i32::from(*y) - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&si) {
continue;
}
if let Some(states) = section.get("block_states")
&& let Some(Tag::List(palette)) = states.get("palette")
{
let ids: Vec<u16> = palette
.iter()
.map(|p| {
let state = BlockState::from_nbt(p).ok();
let key = state.as_ref().map(|s| format!("{}{:?}", s.name, s.properties)).unwrap_or_default();
*cache.entry(key).or_insert_with(|| {
state
.and_then(|s| registry.id(&s).or_else(|| registry.default_state(&s.name)))
.map_or(air, |id| id.0 as u16)
})
})
.collect();
let target = Arc::make_mut(&mut chunk.sections[si as usize]);
if ids.len() <= 1 {
target.blocks = Blocks::Uniform(ids.first().copied().unwrap_or(air));
} else if let Some(Tag::LongArray(data)) = states.get("data") {
let indices = unpack(data, bits_for(ids.len(), 4), 4096);
let mut full = Box::new([air; 4096]);
for (i, idx) in indices.iter().enumerate() {
full[i] = ids.get(*idx as usize).copied().unwrap_or(air);
}
target.blocks = Blocks::Full(full);
}
}
if let Some(b) = section.get("biomes")
&& let Some(Tag::List(palette)) = b.get("palette")
{
let ids: Vec<u16> = palette
.iter()
.map(|p| match p {
Tag::String(s) => biomes.id(&s.to_string_lossy()),
_ => 0,
})
.collect();
let indices = match b.get("data") {
Some(Tag::LongArray(data)) if ids.len() > 1 => unpack(data, bits_for(ids.len(), 0), 64),
_ => vec![0; 64],
};
for (i, idx) in indices.iter().enumerate() {
biome_data[si as usize * 64 + i] = ids.get(*idx as usize).copied().unwrap_or(0);
}
}
}
chunk.biomes = Arc::new(biome_data);
Some(chunk)
}
/// The world folder. Region files are read lazily by worker threads.
pub struct SaveDir {
pub root: PathBuf,
regions: Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>,
}
impl SaveDir {
pub fn new(root: PathBuf) -> Self {
Self {
root,
regions: Mutex::new(HashMap::new()),
}
}
fn region_path(&self, rx: i32, rz: i32) -> PathBuf {
self.root.join(format!("region/r.{rx}.{rz}.mca"))
}
pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option<Chunk> {
let key = (x >> 5, z >> 5);
let region = {
let mut regions = self.regions.lock().ok()?;
regions
.entry(key)
.or_insert_with(|| RegionFile::open(self.region_path(key.0, key.1)).ok().map(|r| Arc::new(Mutex::new(r))))
.clone()?
};
let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??;
let root = record.nbt(Limits::default()).ok()?;
decode(&root, registry, biomes)
}
/// Rewrite every region touched by `chunks`, keeping their other chunks.
pub fn save(&self, chunks: &[Arc<Chunk>], registry: &BlockRegistry, biomes: &Biomes) -> Result<usize> {
let mut by_region: BTreeMap<(i32, i32), Vec<&Arc<Chunk>>> = BTreeMap::new();
for c in chunks {
by_region.entry((c.x >> 5, c.z >> 5)).or_default().push(c);
}
let staging = self.root.join("region/.staging");
fs::create_dir_all(&staging)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as u32);
for ((rx, rz), list) in by_region {
let path = self.region_path(rx, rz);
let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new();
if let Ok(mut existing) = RegionFile::open(&path) {
let positions: Vec<ChunkPos> = existing.chunks().map(|(p, _)| p).collect();
for p in positions {
if let Ok(Some(r)) = existing.read(p) {
records.insert((p.x, p.z), r);
}
}
}
for c in list {
let record = ChunkRecord::from_nbt(&encode(c, registry, biomes), Compression::Zlib, timestamp, Limits::default())?;
records.insert((c.x, c.z), record);
}
let temporary = staging.join(format!("r.{rx}.{rz}.mca"));
let _ = fs::remove_file(&temporary);
let mut writer = RegionWriter::create(&temporary)?;
for ((x, z), r) in &records {
writer.write(ChunkPos::new(*x, *z), r)?;
}
writer.finish()?;
fs::rename(&temporary, &path)?;
self.regions.lock().map_err(|_| "region cache poisoned")?.remove(&(rx, rz));
}
Ok(chunks.len())
}
}
/// Player and world state stored in `level.dat`.
#[derive(Clone, Debug, Default)]
pub struct Level {
pub name: String,
pub seed: i64,
pub creative: bool,
pub time: i64,
pub day_time: i64,
pub spawn: Option<[f64; 3]>,
pub position: Option<[f64; 3]>,
pub rotation: [f32; 2],
pub health: f32,
pub food: i32,
pub saturation: f32,
pub inventory: Vec<(u8, String, u32, u32)>,
}
impl Level {
pub fn read(dir: &Path) -> Option<Self> {
let bytes = fs::read(dir.join("level.dat")).ok()?;
let raw = Compression::Gzip.decode(&bytes, 64 << 20).ok()?;
let (root, _) = nbt::read_named(&raw, Limits::default()).ok()?;
let data = root.tag.get("Data")?;
let long = |t: Option<&Tag>| match t {
Some(Tag::Long(v)) => *v,
Some(Tag::Int(v)) => i64::from(*v),
_ => 0,
};
let doubles = |t: Option<&Tag>| match t {
Some(Tag::List(l)) if l.len() == 3 => {
let v: Vec<f64> = l.iter().map(|d| if let Tag::Double(b) = d { f64::from_bits(*b) } else { 0.0 }).collect();
Some([v[0], v[1], v[2]])
}
_ => None,
};
let player = data.get("Player");
let float = |t: Option<&Tag>| if let Some(Tag::Float(b)) = t { f32::from_bits(*b) } else { 0.0 };
let mut inventory = Vec::new();
if let Some(Tag::List(items)) = player.and_then(|p| p.get("Inventory")) {
for it in items {
let slot = if let Some(Tag::Byte(s)) = it.get("Slot") { *s as u8 } else { continue };
let id = if let Some(Tag::String(s)) = it.get("id") { s.to_string_lossy() } else { continue };
let count = long(it.get("count")).max(1) as u32;
let damage = it
.get("components")
.and_then(|c| c.get("minecraft:damage"))
.map_or(0, |d| long(Some(d)) as u32);
inventory.push((slot, id, count, damage));
}
}
let rotation = match player.and_then(|p| p.get("Rotation")) {
Some(Tag::List(r)) if r.len() == 2 => [float(r.first()), float(r.get(1))],
_ => [0.0; 2],
};
Some(Self {
name: match data.get("LevelName") {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => "World".into(),
},
seed: long(data.get("WorldGenSettings").and_then(|w| w.get("seed"))),
creative: long(data.get("GameType")) == 1,
time: long(data.get("Time")),
day_time: long(data.get("DayTime")),
spawn: Some([long(data.get("SpawnX")) as f64, long(data.get("SpawnY")) as f64, long(data.get("SpawnZ")) as f64]),
position: doubles(player.and_then(|p| p.get("Pos"))),
rotation,
health: player.map_or(20.0, |p| float(p.get("Health"))),
food: player.map_or(20, |p| long(p.get("foodLevel")) as i32),
saturation: player.map_or(5.0, |p| float(p.get("foodSaturationLevel"))),
inventory,
})
}
pub fn write(&self, dir: &Path) -> Result<()> {
fs::create_dir_all(dir)?;
let spawn = self.spawn.unwrap_or([0.0, 64.0, 0.0]);
let mut player = vec![
("Health", Tag::Float(self.health.to_bits())),
("foodLevel", Tag::Int(self.food)),
("foodSaturationLevel", Tag::Float(self.saturation.to_bits())),
("playerGameType", Tag::Int(i32::from(self.creative))),
(
"Rotation",
Tag::List(vec![Tag::Float(self.rotation[0].to_bits()), Tag::Float(self.rotation[1].to_bits())]),
),
(
"Inventory",
Tag::List(
self.inventory
.iter()
.map(|(slot, id, count, damage)| {
let mut entries = vec![
("Slot", Tag::Byte(*slot as i8)),
("id", string(id)),
("count", Tag::Int(*count as i32)),
];
if *damage > 0 {
entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(*damage as i32))])));
}
Tag::compound(entries)
})
.collect(),
),
),
("Dimension", string("minecraft:overworld")),
];
if let Some(p) = self.position {
player.push(("Pos", Tag::List(p.iter().map(|v| Tag::Double(v.to_bits())).collect())));
}
let root = NamedTag {
name: "".into(),
tag: Tag::compound([(
"Data",
Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("version", Tag::Int(19133)),
("LevelName", string(&self.name)),
("GameType", Tag::Int(i32::from(self.creative))),
("Time", Tag::Long(self.time)),
("DayTime", Tag::Long(self.day_time)),
("SpawnX", Tag::Int(spawn[0].floor() as i32)),
("SpawnY", Tag::Int(spawn[1].floor() as i32)),
("SpawnZ", Tag::Int(spawn[2].floor() as i32)),
("initialized", Tag::Byte(1)),
("allowCommands", Tag::Byte(0)),
("hardcore", Tag::Byte(0)),
("Difficulty", Tag::Byte(2)),
("WorldGenSettings", Tag::compound([("seed", Tag::Long(self.seed)), ("generate_features", Tag::Byte(1)), ("bonus_chest", Tag::Byte(0))])),
("Player", Tag::compound(player)),
]),
)]),
};
let bytes = nbt::write_named(&root, Limits::default()).map_err(|e| e.to_string())?;
let compressed = Compression::Gzip.encode(&bytes)?;
let temporary = dir.join("level.dat_new");
fs::write(&temporary, compressed)?;
if dir.join("level.dat").exists() {
let _ = fs::rename(dir.join("level.dat"), dir.join("level.dat_old"));
}
fs::rename(temporary, dir.join("level.dat"))?;
Ok(())
}
}
/// Loads saved chunks before falling back to generation.
pub struct Persistent<G> {
pub inner: Arc<G>,
pub save: Arc<SaveDir>,
pub registry: Arc<crate::assets::Assets>,
pub biomes: Arc<Biomes>,
}
impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
type Worker = G::Worker;
fn worker(&self) -> G::Worker {
self.inner.worker()
}
fn generate(&self, worker: &mut G::Worker, x: i32, z: i32) -> Chunk {
if let Some(mut chunk) = self.save.load(x, z, &self.registry.registry, &self.biomes) {
for s in &mut chunk.sections {
Arc::make_mut(s).compact();
}
return chunk;
}
self.inner.generate(worker, x, z)
}
}
+338
View File
@@ -0,0 +1,338 @@
//! Chunk streaming: a worker pool generates, lights and meshes chunk columns
//! around the player, closest first. The game thread owns the world and only
//! hands immutable `Arc` snapshots to workers; results carry a sequence number
//! so stale work is dropped.
use crate::{
chunk::{Chunk, SECTIONS},
light::{LightTables, light_chunk},
mesher::{MeshTables, Mesher, Region, SectionMesh, borrow},
world::World,
};
use std::{
collections::{BinaryHeap, HashMap, HashSet},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, Ordering},
mpsc,
},
thread,
};
/// Produces fully generated chunk columns. Implementations must be thread-safe;
/// each worker thread owns one `Worker` for per-thread caches.
pub trait ChunkGenerator: Send + Sync + 'static {
type Worker: Send + 'static;
fn worker(&self) -> Self::Worker;
fn generate(&self, worker: &mut Self::Worker, x: i32, z: i32) -> Chunk;
}
enum Job {
Generate(i32, i32),
Light(i32, i32, Box<Region>, u64),
Mesh(i32, i32, i32, Box<Region>, u64),
}
pub enum Done {
Generated(Chunk),
Lit(i32, i32, Vec<Arc<crate::chunk::Section>>, u64),
Meshed(i32, i32, i32, SectionMesh, u64),
}
struct Queued {
priority: i64,
order: u64,
job: Job,
}
impl PartialEq for Queued {
fn eq(&self, o: &Self) -> bool {
self.priority == o.priority && self.order == o.order
}
}
impl Eq for Queued {}
impl PartialOrd for Queued {
fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(o))
}
}
impl Ord for Queued {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
// BinaryHeap is a max-heap: lower priority value = more urgent.
o.priority
.cmp(&self.priority)
.then(o.order.cmp(&self.order))
}
}
struct Shared {
queue: Mutex<BinaryHeap<Queued>>,
ready: Condvar,
stop: AtomicBool,
}
pub struct Streaming {
shared: Arc<Shared>,
results: mpsc::Receiver<Done>,
threads: Vec<thread::JoinHandle<()>>,
order: u64,
generating: HashSet<(i32, i32)>,
lighting: HashMap<(i32, i32), u64>,
meshing: HashMap<(i32, i32, i32), u64>,
/// Chunks whose light is current.
lit: HashSet<(i32, i32)>,
/// Columns whose sections have been meshed at least once.
meshed: HashSet<(i32, i32)>,
sequence: u64,
pub center: (i32, i32),
pub radius: i32,
pub generated_total: u64,
pub meshed_total: u64,
}
pub struct WorkerContext {
pub assets: Arc<crate::assets::Assets>,
pub tables: Arc<MeshTables>,
pub biomes: Arc<crate::biome::Biomes>,
pub light: Arc<LightTables>,
}
impl Streaming {
pub fn new<G: ChunkGenerator>(generator: Arc<G>, context: Arc<WorkerContext>, threads: usize) -> Self {
let shared = Arc::new(Shared {
queue: Mutex::new(BinaryHeap::new()),
ready: Condvar::new(),
stop: AtomicBool::new(false),
});
let (send, results) = mpsc::channel();
let threads = (0..threads.max(1))
.map(|i| {
let shared = shared.clone();
let send = send.clone();
let generator = generator.clone();
let context = context.clone();
thread::Builder::new()
.name(format!("horizon-worker-{i}"))
.spawn(move || {
let mut worker = generator.worker();
let mut mesher = Mesher {
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
visibility: context.tables.visibility.clone(),
};
loop {
let job = {
let mut queue = shared.queue.lock().unwrap();
loop {
if shared.stop.load(Ordering::Relaxed) {
return;
}
if let Some(job) = queue.pop() {
break job.job;
}
queue = shared.ready.wait(queue).unwrap();
}
};
let done = match job {
Job::Generate(x, z) => {
Done::Generated(generator.generate(&mut worker, x, z))
}
Job::Light(x, z, region, seq) => {
Done::Lit(x, z, light_chunk(&borrow(&region), &context.light), seq)
}
Job::Mesh(x, sy, z, region, seq) => {
Done::Meshed(x, sy, z, mesher.mesh(&borrow(&region), sy), seq)
}
};
if send.send(done).is_err() {
return;
}
}
})
.expect("spawn worker")
})
.collect();
Self {
shared,
results,
threads,
order: 0,
generating: HashSet::new(),
lighting: HashMap::new(),
meshing: HashMap::new(),
lit: HashSet::new(),
meshed: HashSet::new(),
sequence: 0,
center: (0, 0),
radius: 8,
generated_total: 0,
meshed_total: 0,
}
}
fn submit(&mut self, priority: i64, job: Job) {
self.order += 1;
self.shared.queue.lock().unwrap().push(Queued {
priority,
order: self.order,
job,
});
self.shared.ready.notify_one();
}
fn distance(&self, x: i32, z: i32) -> i64 {
let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1));
dx * dx + dz * dz
}
fn region(world: &World, x: i32, z: i32) -> Option<Box<Region>> {
let mut region: Region = Default::default();
for dz in 0..3 {
for dx in 0..3 {
region[dz][dx] = Some(world.chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))?.clone());
}
}
Some(Box::new(region))
}
pub fn is_lit(&self, x: i32, z: i32) -> bool {
self.lit.contains(&(x, z))
}
pub fn pending(&self) -> usize {
self.shared.queue.lock().unwrap().len()
}
/// Advance streaming: collect finished work, then schedule more.
/// Returns meshes ready for upload and columns that were unloaded.
pub fn update(&mut self, world: &mut World) -> (Vec<((i32, i32, i32), SectionMesh)>, Vec<Arc<Chunk>>) {
let mut uploads = Vec::new();
while let Ok(done) = self.results.try_recv() {
match done {
Done::Generated(chunk) => {
let key = (chunk.x, chunk.z);
self.generating.remove(&key);
if self.in_range(key.0, key.1, 2) {
self.generated_total += 1;
world.chunks.insert(key, Arc::new(chunk));
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
}
}
}
}
Done::Lit(x, z, sections, seq) => {
if self.lighting.get(&(x, z)) != Some(&seq) {
continue;
}
self.lighting.remove(&(x, z));
if let Some(chunk) = world.chunks.get_mut(&(x, z)) {
let chunk = Arc::make_mut(chunk);
// Keep blocks edited since the snapshot; take only light.
for (target, lit) in chunk.sections.iter_mut().zip(sections) {
let mut section = (**target).clone();
section.light = lit.light.clone();
*target = Arc::new(section);
}
chunk.lit = true;
self.lit.insert((x, z));
for dz in -1..=1 {
for dx in -1..=1 {
for sy in 0..SECTIONS as i32 {
world.dirty_sections.insert((x + dx, sy, z + dz));
}
}
}
}
}
Done::Meshed(x, sy, z, mesh, seq) => {
if self.meshing.get(&(x, sy, z)) != Some(&seq) {
continue;
}
self.meshing.remove(&(x, sy, z));
self.meshed_total += 1;
uploads.push(((x, sy, z), mesh));
}
}
}
// Unload far columns.
let far: Vec<_> = world
.chunks
.keys()
.copied()
.filter(|&(x, z)| !self.in_range(x, z, 3))
.collect();
let mut removed = Vec::with_capacity(far.len());
for key in &far {
if let Some(chunk) = world.chunks.remove(key) {
removed.push(chunk);
}
self.lit.remove(key);
self.meshed.remove(key);
}
// Generation, closest first, bounded in flight.
let workers = self.threads.len();
if self.generating.len() < workers * 3 {
let r = self.radius + 1;
let mut wanted = Vec::new();
for dz in -r..=r {
for dx in -r..=r {
let (x, z) = (self.center.0 + dx, self.center.1 + dz);
if !self.in_range(x, z, 1)
|| world.chunks.contains_key(&(x, z))
|| self.generating.contains(&(x, z))
{
continue;
}
wanted.push((self.distance(x, z), x, z));
}
}
wanted.sort_unstable();
for (d, x, z) in wanted.into_iter().take(workers * 3 - self.generating.len()) {
self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z));
}
}
// Lighting once all neighbours exist.
let light: Vec<_> = world.dirty_light.iter().copied().collect();
for (x, z) in light {
if !world.chunks.contains_key(&(x, z)) {
world.dirty_light.remove(&(x, z));
continue;
}
let Some(region) = Self::region(world, x, z) else {
continue;
};
world.dirty_light.remove(&(x, z));
self.sequence += 1;
self.lighting.insert((x, z), self.sequence);
self.submit(self.distance(x, z) * 4 + 1, Job::Light(x, z, region, self.sequence));
}
// Meshing once the column and its neighbours are lit.
let dirty: Vec<_> = world.dirty_sections.iter().copied().collect();
let mut columns: HashMap<(i32, i32), Option<Box<Region>>> = HashMap::new();
for (x, sy, z) in dirty {
if !world.chunks.contains_key(&(x, z)) || !self.in_range(x, z, 0) {
world.dirty_sections.remove(&(x, sy, z));
continue;
}
let ready = (-1..=1).all(|dz| (-1..=1).all(|dx| self.lit.contains(&(x + dx, z + dz))));
if !ready || self.lighting.contains_key(&(x, z)) {
continue;
}
let region = columns
.entry((x, z))
.or_insert_with(|| Self::region(world, x, z));
let Some(region) = region.clone() else { continue };
world.dirty_sections.remove(&(x, sy, z));
let first = self.meshed.insert((x, z));
self.sequence += 1;
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Job::Mesh(x, sy, z, region, self.sequence),
);
}
(uploads, removed)
}
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
let r = i64::from(self.radius + margin);
self.distance(x, z) <= r * r
}
}
impl Drop for Streaming {
fn drop(&mut self) {
self.shared.stop.store(true, Ordering::Relaxed);
self.shared.ready.notify_all();
for t in self.threads.drain(..) {
let _ = t.join();
}
}
}
+115
View File
@@ -0,0 +1,115 @@
// Terrain, sky and outline shaders, ported from the pinned vanilla
// terrain.vsh/fsh, fog.glsl and sample_lightmap.glsl.
struct Globals {
view_proj: mat4x4<f32>,
fog_color: vec4<f32>,
// environmental start/end, render-distance start/end
fog: vec4<f32>,
sky_color: vec4<f32>,
// x: sky darkening, y: game time, z: aspect, w: tan(fov/2)
misc: vec4<f32>,
inverse_view: mat4x4<f32>,
sunrise: vec4<f32>,
// xyz: sun direction, w: star brightness
sun: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
@group(0) @binding(2) var sprite_sampler: sampler;
@group(0) @binding(3) var lightmap: texture_2d<f32>;
@group(0) @binding(4) var lightmap_sampler: sampler;
struct TerrainOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) @interpolate(flat) layer: u32,
@location(2) color: vec4<f32>,
@location(3) spherical: f32,
@location(4) cylindrical: f32,
}
fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
let uv = vec2(block, sky) * 16.0;
return textureSampleLevel(lightmap, lightmap_sampler,
clamp(uv / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
}
@vertex fn vs_terrain(
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>,
@location(5) origin: vec4<f32>) -> TerrainOut {
let pos = position + origin.xyz;
var out: TerrainOut;
out.clip = globals.view_proj * vec4(pos, 1.0);
out.uv = uv;
out.layer = layer;
out.color = color * sample_lightmap(f32(light.x) / 16.0, f32(light.y) / 16.0);
out.spherical = length(pos);
out.cylindrical = max(length(pos.xz), abs(pos.y));
return out;
}
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d <= start { return 0.0; }
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
let f = max(linear_fog(spherical, globals.fog.x, globals.fog.y),
linear_fog(cylindrical, globals.fog.z, globals.fog.w));
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
@fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4<f32> {
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
if color.a < 0.5 { discard; }
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
}
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
if color.a < 0.01 { discard; }
return apply_fog(color, in.spherical, in.cylindrical);
}
// Sky: vanilla draws a sky disc in the sky colour and blends towards the fog
// colour at the horizon; sunrise/sunset tints the horizon facing the sun.
struct SkyOut {
@builtin(position) clip: vec4<f32>,
@location(0) ndc: vec2<f32>,
}
@vertex fn vs_sky(@builtin(vertex_index) i: u32) -> SkyOut {
let p = vec2(f32(i32(i & 1u) * 4 - 1), f32(i32(i >> 1u) * 4 - 1));
var out: SkyOut;
out.clip = vec4(p, 0.0, 1.0);
out.ndc = p;
return out;
}
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
let view = normalize((globals.inverse_view * vec4(in.ndc.x * globals.misc.z * globals.misc.w,
in.ndc.y * globals.misc.w, -1.0, 0.0)).xyz);
let up = clamp(view.y, -1.0, 1.0);
// Fog band towards the horizon (vanilla sky end distance blending).
let horizon = 1.0 - smoothstep(0.0, 0.35, up);
var color = mix(globals.sky_color.rgb, globals.fog_color.rgb, horizon);
let toward_sun = max(dot(normalize(vec3(view.x, 0.0, view.z) + vec3(0.0001)), normalize(vec3(globals.sun.x, 0.0, globals.sun.z) + vec3(0.0001))), 0.0);
let band = (1.0 - smoothstep(-0.1, 0.4, abs(up))) * pow(toward_sun, 3.0);
color = mix(color, globals.sunrise.rgb, band * globals.sunrise.a);
if up < 0.0 {
// Void below the horizon.
color = mix(color, globals.sky_color.rgb * 0.2, smoothstep(0.0, -0.3, up) * (1.0 - globals.misc.x));
}
// Sun disc.
let sun_dot = dot(view, normalize(globals.sun.xyz));
if sun_dot > 0.9985 { color = mix(color, vec3(1.0, 1.0, 0.85), 0.95); }
let moon_dot = dot(view, -normalize(globals.sun.xyz));
if moon_dot > 0.9993 { color = mix(color, vec3(0.85, 0.87, 0.95), 0.9); }
// Stars.
let cell = floor(view * 300.0);
let h = fract(sin(dot(cell, vec3(12.9898, 78.233, 37.719))) * 43758.5453);
if h > 0.9985 && up > 0.0 { color += vec3(globals.sun.w * 2.0); }
return vec4(color, 1.0);
}
struct LineOut { @builtin(position) clip: vec4<f32> }
@vertex fn vs_line(@location(0) position: vec3<f32>) -> LineOut {
var out: LineOut;
out.clip = globals.view_proj * vec4(position, 1.0);
return out;
}
@fragment fn fs_line() -> @location(0) vec4<f32> { return vec4(0.0, 0.0, 0.0, 0.4); }
+123
View File
@@ -0,0 +1,123 @@
//! Simple rolling terrain used only until the vanilla overworld generator is
//! bound (`--test-terrain`). Not vanilla generation.
use crate::{chunk::Chunk, streaming::ChunkGenerator};
use horizon_world::registry::BlockRegistry;
pub struct TestTerrain {
stone: u16,
dirt: u16,
grass: u16,
water: u16,
sand: u16,
bedrock: u16,
log: u16,
leaves: u16,
short_grass: u16,
plains: u16,
}
impl TestTerrain {
pub fn new(registry: &BlockRegistry, biomes: &crate::biome::Biomes) -> crate::Result<Self> {
let id = |name: &str| -> crate::Result<u16> {
Ok(registry
.default_state(name)
.ok_or_else(|| format!("missing {name}"))?
.0 as u16)
};
Ok(Self {
stone: id("minecraft:stone")?,
dirt: id("minecraft:dirt")?,
grass: id("minecraft:grass_block")?,
water: id("minecraft:water")?,
sand: id("minecraft:sand")?,
bedrock: id("minecraft:bedrock")?,
log: id("minecraft:oak_log")?,
leaves: registry
.resolve(&horizon_world::chunk::BlockState {
name: "minecraft:oak_leaves".into(),
properties: [
("distance".to_owned(), "1".to_owned()),
("persistent".to_owned(), "false".to_owned()),
("waterlogged".to_owned(), "false".to_owned()),
]
.into(),
})?
.0 as u16,
short_grass: id("minecraft:short_grass")?,
plains: biomes.id("minecraft:plains"),
})
}
fn height(x: i32, z: i32) -> i32 {
let (x, z) = (f64::from(x), f64::from(z));
let h = 68.0
+ 10.0 * (x / 47.0).sin() * (z / 61.0).cos()
+ 5.0 * ((x + z) / 23.0).sin()
+ 3.0 * (x / 11.0).cos() * (z / 13.0).sin();
h as i32
}
}
fn hash(x: i32, z: i32) -> u32 {
let mut h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (z as u32).wrapping_mul(0x85EB_CA77);
h ^= h >> 15;
h = h.wrapping_mul(0x2C1B_3C6D);
h ^ (h >> 12)
}
impl ChunkGenerator for TestTerrain {
type Worker = ();
fn worker(&self) {}
fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk {
let mut chunk = Chunk::empty(cx, cz);
chunk.biomes = std::sync::Arc::new(vec![self.plains; chunk.biomes.len()]);
for z in 0..16 {
for x in 0..16 {
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
let h = Self::height(wx, wz);
for y in -64..=h.max(62) {
let b = if y == -64 {
self.bedrock
} else if y > h {
self.water
} else if y < h - 3 {
self.stone
} else if h <= 63 {
self.sand
} else if y == h {
self.grass
} else {
self.dirt
};
chunk.set(x, y, z, b);
}
if h > 63 && hash(wx, wz) % 13 == 0 {
chunk.set(x, h + 1, z, self.short_grass);
}
}
}
// Trees fully inside the chunk.
for z in 2..14 {
for x in 2..14 {
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
let h = Self::height(wx, wz);
if h <= 64 || hash(wx, wz) % 97 != 0 {
continue;
}
for y in h + 1..h + 6 {
chunk.set(x, y, z, self.log);
}
for dy in 3..7 {
let r = if dy >= 5 { 1 } else { 2 };
for dz in -r..=r {
for dx in -r..=r {
if chunk.get(x + dx, h + dy, z + dz) == 0 {
chunk.set(x + dx, h + dy, z + dz, self.leaves);
}
}
}
}
}
}
for s in &mut chunk.sections {
std::sync::Arc::make_mut(s).compact();
}
chunk
}
}
+69 -86
View File
@@ -1,110 +1,93 @@
//! A controlled blockstate scene for exercising the native renderer. This is
//! not the vanilla world generator or an authoritative gameplay simulation.
use crate::{
Result,
assets::{Assets, Properties},
//! Resident client world: streamed chunk columns plus the bookkeeping the game
//! loop needs to relight and remesh after edits.
use crate::chunk::{Chunk, MIN_Y, SECTIONS};
use horizon_core::random::LegacyRandom;
use horizon_world::registry::BlockStateId;
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use horizon_core::{position::ChunkPos, random::LegacyRandom};
use horizon_world::{registry::BlockStateId, worldgen::terrain::TerrainChunk};
use std::collections::BTreeMap;
pub struct TestWorld<'a> {
pub chunks: BTreeMap<(i32, i32), TerrainChunk<'a, Properties>>,
pub struct World {
pub chunks: HashMap<(i32, i32), Arc<Chunk>>,
pub random: LegacyRandom,
pub revision: u64,
pub health_rules: crate::health::HealthRules,
air: BlockStateId,
pub air: BlockStateId,
/// Sections whose geometry changed and need remeshing.
pub dirty_sections: HashSet<(i32, i32, i32)>,
/// Chunks whose light must be recomputed.
pub dirty_light: HashSet<(i32, i32)>,
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub game_time: i64,
pub day_time: i64,
}
impl<'a> TestWorld<'a> {
pub fn new(assets: &'a Assets, radius: i32) -> Result<Self> {
let air = assets
.registry
.default_state("minecraft:air")
.ok_or("missing air state")?;
let mut world = Self {
chunks: BTreeMap::new(),
random: LegacyRandom::new(0),
impl World {
pub fn new(air: BlockStateId, seed: i64) -> Self {
Self {
chunks: HashMap::new(),
random: LegacyRandom::new(seed),
revision: 0,
health_rules: crate::health::HealthRules::default(),
air,
};
for cz in -radius..=radius {
for cx in -radius..=radius {
let mut chunk = TerrainChunk::new(
ChunkPos::new(cx, cz),
0,
16,
&assets.registry,
assets.properties.clone(),
)?;
for z in 0..16 {
for x in 0..16 {
for y in 0..4 {
let layer = match y {
0 => 0,
1 | 2 => 1,
_ => {
if (cx + cz) & 1 == 0 {
2
} else {
3
}
}
};
chunk.set_block_worldgen(
cx * 16 + x,
y,
cz * 16 + z,
assets.material_states[layer],
)?;
}
}
}
world.chunks.insert((cx, cz), chunk);
}
dirty_sections: HashSet::new(),
dirty_light: HashSet::new(),
modified: HashSet::new(),
game_time: 0,
day_time: 1000,
}
for y in 4..11 {
for z in -10_i32..=10 {
for x in -10_i32..=10 {
if x.abs().max(z.abs()) <= 10 - (y - 4) {
world.set(
x,
y,
z,
assets.material_states[if y & 1 == 0 { 4 } else { 5 }],
)?;
}
}
}
}
for (position, state) in &assets.model_placements {
world.set(position.x, position.y, position.z, *state)?;
}
world.revision = 0;
Ok(world)
}
/// Resident storage write. Neighbor updates, drops and block-entity
/// lifecycle must be dispatched by the owning gameplay runtime.
pub fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> Result<()> {
let chunk = self
.chunks
.get_mut(&(x >> 4, z >> 4))
.ok_or("test scene exceeds resident chunks")?;
if y < chunk.min_y() || y >= chunk.min_y() + chunk.height() {
return Err("test scene write exceeds resident height".into());
/// Resident storage write; marks the touched sections (and neighbours on
/// section borders) for remeshing and the surrounding chunks for relighting.
/// Neighbour updates, drops and block entities belong to the gameplay layer.
pub fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> crate::Result<()> {
let Some(chunk) = self.chunks.get_mut(&(x >> 4, z >> 4)) else {
return Err("write outside resident chunks".into());
};
if y < MIN_Y || y >= MIN_Y + (SECTIONS as i32) * 16 {
return Err("write outside world height".into());
}
let previous = chunk.set_block_worldgen(x, y, z, state)?;
if previous != state {
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16);
if u32::from(previous) != state.0 {
self.revision = self.revision.wrapping_add(1);
self.modified.insert((x >> 4, z >> 4));
let sy = (y - MIN_Y) >> 4;
for dz in -1..=1 {
for dy in -1..=1 {
for dx in -1..=1 {
let (bx, by, bz) = (x + dx, y + dy, z + dz);
let s = (by - MIN_Y) >> 4;
if !(0..SECTIONS as i32).contains(&s) {
continue;
}
self.dirty_sections.insert((bx >> 4, s, bz >> 4));
}
}
}
let _ = sy;
for dz in -1..=1 {
for dx in -1..=1 {
self.dirty_light.insert(((x >> 4) + dx, (z >> 4) + dz));
}
}
}
Ok(())
}
pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
self.chunks
.get(&(x >> 4, z >> 4))
.map_or(self.air, |chunk| chunk.block(x, y, z))
.map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15))
}
pub fn light(&self, x: i32, y: i32, z: i32) -> u8 {
self.chunks
.get(&(x >> 4, z >> 4))
.map_or(0xF0, |chunk| chunk.light(x & 15, y, z & 15))
}
pub fn is_air(&self, state: BlockStateId) -> bool {
state == self.air
}
pub fn loaded(&self, x: i32, z: i32) -> bool {
self.chunks.contains_key(&(x >> 4, z >> 4))
}
}
-71
View File
@@ -1,71 +0,0 @@
struct Camera {
view_projection: mat4x4<f32>,
position: vec4<f32>,
fog: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: Camera;
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
@group(0) @binding(2) var sprite_sampler: sampler;
struct VertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) @interpolate(flat) layer: u32,
@location(2) shade: f32,
@location(3) world_position: vec3<f32>,
}
@vertex fn vs_main(@builtin(vertex_index) vertex: u32,
@location(0) origin: vec3<f32>, @location(1) extent: vec2<f32>,
@location(2) face: u32, @location(3) layer: u32,
@location(4) uv_origin: vec2<f32>, @location(5) uv_u: vec2<f32>,
@location(6) uv_v: vec2<f32>, @location(7) shade: f32) -> VertexOut {
let corners = array<vec2<f32>,4>(vec2(0.0,0.0),vec2(1.0,0.0),vec2(1.0,1.0),vec2(0.0,1.0));
let normal_order = array<u32,6>(0u,1u,2u,0u,2u,3u);
let reversed_order = array<u32,6>(0u,2u,1u,0u,3u,2u);
let flipped = face==1u || face==2u || face==5u;
let corner = corners[select(normal_order[vertex],reversed_order[vertex],flipped)];
let offset = corner*extent;
var position = origin;
if face<2u { position+=vec3(offset.x,0.0,offset.y); }
else if face<4u { position+=vec3(offset.x,offset.y,0.0); }
else { position+=vec3(0.0,offset.y,offset.x); }
var output: VertexOut;
output.clip=camera.view_projection*vec4(position,1.0);
output.uv=uv_origin+uv_u*offset.x+uv_v*offset.y;
output.layer=layer;
output.shade=shade;
output.world_position=position;
return output;
}
@fragment fn fs_main(input:VertexOut)->@location(0) vec4<f32> {
let color=textureSample(sprites,sprite_sampler,input.uv,i32(input.layer));
let distance=length(input.world_position-camera.position.xyz);
let fog_amount=smoothstep(camera.position.w*0.65,camera.position.w,distance);
return vec4(mix(color.rgb*input.shade,camera.fog.rgb,fog_amount),1.0);
}
@vertex fn vs_model(@builtin(vertex_index) vertex: u32,
@location(0) p0: vec3<f32>, @location(1) p1: vec3<f32>,
@location(2) p2: vec3<f32>, @location(3) p3: vec3<f32>,
@location(4) uv0: vec2<f32>, @location(5) uv1: vec2<f32>,
@location(6) uv2: vec2<f32>, @location(7) uv3: vec2<f32>,
@location(8) layer: u32, @location(9) shade: f32) -> VertexOut {
let order=array<u32,6>(0u,1u,2u,0u,2u,3u);
let positions=array<vec3<f32>,4>(p0,p1,p2,p3);
let uvs=array<vec2<f32>,4>(uv0,uv1,uv2,uv3);
let corner=order[vertex];
var output: VertexOut;
output.clip=camera.view_projection*vec4(positions[corner],1.0);
output.uv=uvs[corner];
output.layer=layer;
output.shade=shade;
output.world_position=positions[corner];
return output;
}
@fragment fn fs_model(input:VertexOut)->@location(0) vec4<f32> {
let color=textureSample(sprites,sprite_sampler,input.uv,i32(input.layer));
// Inspection sprites are validated to contain only zero or full alpha.
if color.a<0.5 { discard; }
let distance=length(input.world_position-camera.position.xyz);
let fog_amount=smoothstep(camera.position.w*0.65,camera.position.w,distance);
return vec4(mix(color.rgb*input.shade,camera.fog.rgb,fog_amount),1.0);
}
+13
View File
@@ -39,6 +39,7 @@ struct State {
}
/// Prepared face geometry and a bounded cache shared across state pairs. Geometry
/// is deduplicated by the imported immutable shape, not copied for every state.
#[derive(Clone)]
pub struct FaceVisibility {
states: Vec<State>,
faces: Vec<VoxelShape>,
@@ -156,6 +157,18 @@ impl FaceVisibility {
}
}
}
/// Whether the state's occlusion face toward `direction` is the full square.
pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool {
self.states
.get(state.0 as usize)
.is_some_and(|s| s.faces[direction as usize] == 1)
}
/// Whether the state's occlusion face toward `direction` is empty.
pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool {
self.states
.get(state.0 as usize)
.is_none_or(|s| s.faces[direction as usize] == 0)
}
pub fn skip_rendering(
&self,
state: BlockStateId,