635acffda9
The client now resolves stacks with horizon-assets' ItemModelResolver into an ItemStackRenderState equivalent (item_render): baked cuboid layers with their display and local transforms, tints and foil, and the special model renderers (chests, shulker boxes, banners, heads, shields, tridents, decorated pots, conduits, bells, books, copper golem statues) posed from the entity model layers. GUI icons are submitted under the GuiItemAtlas pose with ITEMS_3D/ITEMS_FLAT lighting, back faces culled and clipped to the slot; dropped items follow ItemEntityRenderer (bounding box hover, spin and seeded cluster copies); item frames, first-person and mob, player and armour stand hands, worn skulls and head items submit the same state in the world. The client atlas also runs the atlas sprite sources (directory, single, filter, unstitch, paletted_permutations), so armour trim sprites exist. The ad-hoc icon, held-banner, shield, potion-layer and glint paths are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
816 lines
29 KiB
Rust
816 lines
29 KiB
Rust
//! Item rendering through the resolved item model pipeline: the
|
|
//! `ItemModelResolver` of `horizon-assets` fills an [`ItemRenderState`]
|
|
//! (`ItemStackRenderState`: layers of baked quads or special renderers, each
|
|
//! with its display transform, local transform, tints and foil), and
|
|
//! [`ItemRenderState::submit`] turns it into the quads `ItemFeatureRenderer`
|
|
//! and the special model renderers submit, in pose space. A sink then draws
|
|
//! them: [`gui`] into the HUD batch with the GUI item lighting, [`WorldSink`]
|
|
//! into entity vertices with the level's lighting.
|
|
pub mod gui;
|
|
mod special;
|
|
|
|
use crate::{
|
|
block_entity_render::{ModelPart, diffuse},
|
|
hud::Rect,
|
|
mesher::Vertex,
|
|
};
|
|
use glam::{Mat3, Mat4, Vec3};
|
|
use horizon_assets::{
|
|
animation::AnimationMetadata,
|
|
item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model},
|
|
item_model::{
|
|
ClientItem, Components, Context, DisplayContext, FoilType, ItemEnv, ItemModels,
|
|
LayerContent, LevelState, OwnerState, SpecialModel, StackView,
|
|
},
|
|
model::{CuboidModel, Direction},
|
|
palette::PalettedPermutations,
|
|
resolve::{MISSING_MODEL, ModelLibrary},
|
|
};
|
|
use horizon_world::nbt::Tag;
|
|
use serde_json::Value;
|
|
use std::{
|
|
collections::{BTreeMap, HashMap},
|
|
fs,
|
|
path::{Path, PathBuf},
|
|
sync::{Arc, Mutex},
|
|
};
|
|
|
|
/// One quad as submitted for drawing: pose-space corners, atlas UVs, the
|
|
/// transformed unit normal, ARGB colour (tint, `-1` white) and its glint.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct ItemQuad {
|
|
pub pos: [Vec3; 4],
|
|
pub uv: [[f32; 2]; 4],
|
|
pub normal: Vec3,
|
|
pub color: u32,
|
|
pub foil: Foil,
|
|
/// `MaterialInfo.lightEmission` (block light floor).
|
|
pub light_emission: u8,
|
|
}
|
|
/// Which glint render type a quad uses.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Foil {
|
|
None,
|
|
/// `GLINT_TEXTURING` over the sprite's UVs (`itemGlintRenderType`,
|
|
/// `entitySolidGlint`).
|
|
Standard,
|
|
/// `itemGlintSpecialRenderType`: compasses and clocks, a sheeted decal.
|
|
Special,
|
|
}
|
|
/// Where submitted quads go.
|
|
pub trait ItemSink {
|
|
fn quad(&mut self, quad: ItemQuad);
|
|
}
|
|
impl ItemSink for Vec<ItemQuad> {
|
|
fn quad(&mut self, quad: ItemQuad) {
|
|
self.push(quad);
|
|
}
|
|
}
|
|
|
|
/// Data special renderers read from the game (registries, skins).
|
|
pub trait SpecialHost {
|
|
/// The banner atlas texture of a banner pattern (`entity/banner/<asset>`).
|
|
fn banner_texture(&self, pattern: &str) -> Option<String>;
|
|
/// The shield atlas texture of a banner pattern (`entity/shield/<asset>`).
|
|
fn shield_texture(&self, pattern: &str) -> Option<String>;
|
|
/// The skin texture of a `minecraft:profile` component, if loaded.
|
|
fn player_skin(&self, _profile: &Value) -> Option<String> {
|
|
None
|
|
}
|
|
}
|
|
/// A host with no registries: patterns and skins fall back to defaults.
|
|
pub struct NoHost;
|
|
impl SpecialHost for NoHost {
|
|
fn banner_texture(&self, _: &str) -> Option<String> {
|
|
None
|
|
}
|
|
fn shield_texture(&self, _: &str) -> Option<String> {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// The geometry of one layer.
|
|
#[derive(Clone, Debug)]
|
|
pub enum LayerGeometry {
|
|
Quads(Arc<BakedItemModel>),
|
|
Special {
|
|
model: SpecialModel,
|
|
argument: Value,
|
|
},
|
|
}
|
|
/// `ItemStackRenderState.LayerRenderState`.
|
|
#[derive(Clone, Debug)]
|
|
pub struct LayerRender {
|
|
pub geometry: LayerGeometry,
|
|
pub tints: Vec<i32>,
|
|
pub foil: FoilType,
|
|
/// `applyTransform`: the display transform, then the local transform.
|
|
pub matrix: Mat4,
|
|
/// `particleMaterial` (atlas sprite name).
|
|
pub particle: String,
|
|
pub uses_block_light: bool,
|
|
/// Untransformed extents (quad corners or the special model's parts).
|
|
pub extents: Arc<Vec<Vec3>>,
|
|
}
|
|
/// `ItemStackRenderState`.
|
|
#[derive(Clone, Debug)]
|
|
pub struct ItemRenderState {
|
|
pub display: DisplayContext,
|
|
pub layers: Vec<LayerRender>,
|
|
pub oversized_in_gui: bool,
|
|
pub animated: bool,
|
|
}
|
|
impl ItemRenderState {
|
|
pub fn is_empty(&self) -> bool {
|
|
self.layers.is_empty()
|
|
}
|
|
/// `pickParticleMaterial`: a random layer's particle sprite.
|
|
pub fn pick_particle(
|
|
&self,
|
|
random: &mut impl horizon_core::random::RandomSource,
|
|
) -> Option<String> {
|
|
if self.layers.is_empty() {
|
|
return None;
|
|
}
|
|
let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize;
|
|
self.layers.get(i).map(|l| l.particle.clone())
|
|
}
|
|
/// `usesBlockLight` of the first layer (GUI lighting choice).
|
|
pub fn uses_block_light(&self) -> bool {
|
|
self.layers.first().is_some_and(|l| l.uses_block_light)
|
|
}
|
|
/// `getModelBoundingBox`: the transformed extents of every layer, as
|
|
/// (min, max); a zero box at the origin when there are none.
|
|
pub fn bounding_box(&self) -> (Vec3, Vec3) {
|
|
let mut lo = Vec3::splat(f32::INFINITY);
|
|
let mut hi = Vec3::splat(f32::NEG_INFINITY);
|
|
for layer in &self.layers {
|
|
for p in layer.extents.iter() {
|
|
let q = layer.matrix.transform_point3(*p);
|
|
lo = lo.min(q);
|
|
hi = hi.max(q);
|
|
}
|
|
}
|
|
if lo.x > hi.x {
|
|
(Vec3::ZERO, Vec3::ZERO)
|
|
} else {
|
|
(lo, hi)
|
|
}
|
|
}
|
|
/// `ItemStackRenderState.submit` under `pose`.
|
|
pub fn submit(
|
|
&self,
|
|
renderer: &ItemRenderer,
|
|
sprites: &HashMap<String, Rect>,
|
|
host: &dyn SpecialHost,
|
|
pose: Mat4,
|
|
sink: &mut dyn ItemSink,
|
|
) {
|
|
for layer in &self.layers {
|
|
let m = pose * layer.matrix;
|
|
match &layer.geometry {
|
|
LayerGeometry::Quads(baked) => {
|
|
submit_quads(baked, layer, self.display, m, sprites, sink);
|
|
}
|
|
LayerGeometry::Special { model, argument } => special::submit(
|
|
renderer,
|
|
model,
|
|
argument,
|
|
layer.foil != FoilType::None,
|
|
m,
|
|
sprites,
|
|
host,
|
|
sink,
|
|
),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The atlas name of a sprite identifier (`minecraft:item/apple` -> `item/apple`).
|
|
pub fn sprite_name(sprite: &str) -> &str {
|
|
sprite.strip_prefix("minecraft:").unwrap_or(sprite)
|
|
}
|
|
/// `Direction.getUnitVec3f`.
|
|
pub fn direction_vector(d: Direction) -> Vec3 {
|
|
match d {
|
|
Direction::Down => Vec3::NEG_Y,
|
|
Direction::Up => Vec3::Y,
|
|
Direction::North => Vec3::NEG_Z,
|
|
Direction::South => Vec3::Z,
|
|
Direction::West => Vec3::NEG_X,
|
|
Direction::East => Vec3::X,
|
|
}
|
|
}
|
|
/// `PoseStack.Pose.transformNormal`: the normal matrix, renormalized.
|
|
pub fn transform_normal(m: Mat4, n: Vec3) -> Vec3 {
|
|
let normal = Mat3::from_mat4(m).inverse().transpose();
|
|
(normal * n).normalize_or_zero()
|
|
}
|
|
/// An `ARGB` int as the `u32` colour of an [`ItemQuad`].
|
|
pub fn argb(color: i32) -> u32 {
|
|
color as u32
|
|
}
|
|
|
|
/// `ItemFeatureRenderer.prepareMainSubmit` for one cuboid layer.
|
|
fn submit_quads(
|
|
baked: &BakedItemModel,
|
|
layer: &LayerRender,
|
|
display: DisplayContext,
|
|
m: Mat4,
|
|
sprites: &HashMap<String, Rect>,
|
|
sink: &mut dyn ItemSink,
|
|
) {
|
|
let foil = match layer.foil {
|
|
FoilType::None => Foil::None,
|
|
FoilType::Standard => Foil::Standard,
|
|
FoilType::Special => Foil::Special,
|
|
};
|
|
let _ = display;
|
|
for q in &baked.quads {
|
|
let Some(r) = sprites
|
|
.get(sprite_name(&q.material.sprite))
|
|
.or_else(|| sprites.get("misc/missingno"))
|
|
.or_else(|| sprites.get("horizon/missingno"))
|
|
.copied()
|
|
else {
|
|
continue;
|
|
};
|
|
// `getLayerColorSafe`: an untinted quad, or a tint index past the
|
|
// tints, draws white.
|
|
let color = if q.tint_index >= 0 {
|
|
layer
|
|
.tints
|
|
.get(q.tint_index as usize)
|
|
.copied()
|
|
.unwrap_or(-1)
|
|
} else {
|
|
-1
|
|
};
|
|
let pos = q.positions.map(|p| m.transform_point3(Vec3::from(p)));
|
|
let uv =
|
|
q.uv.map(|[u, v]| [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v]);
|
|
sink.quad(ItemQuad {
|
|
pos,
|
|
uv,
|
|
normal: transform_normal(m, direction_vector(q.facing)),
|
|
color: argb(color),
|
|
foil,
|
|
light_emission: q.light_emission,
|
|
});
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Sprites for baking
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// The alpha masks of item and block sprites, read from the texture files
|
|
/// (every unique animation frame) and the items atlas's palette sprites.
|
|
struct FileSprites {
|
|
root: PathBuf,
|
|
permutations: Vec<PalettedPermutations>,
|
|
cache: Mutex<HashMap<String, Option<SpriteMask>>>,
|
|
}
|
|
impl SpriteLookup for FileSprites {
|
|
fn mask(&self, sprite: &str) -> Option<SpriteMask> {
|
|
if let Ok(cache) = self.cache.lock()
|
|
&& let Some(hit) = cache.get(sprite)
|
|
{
|
|
return hit.clone();
|
|
}
|
|
let mask = self.load(sprite);
|
|
if let Ok(mut cache) = self.cache.lock() {
|
|
cache.insert(sprite.to_owned(), mask.clone());
|
|
}
|
|
mask
|
|
}
|
|
}
|
|
fn argb_pixels(rgba: &[u8]) -> Vec<u32> {
|
|
rgba.as_chunks::<4>()
|
|
.0
|
|
.iter()
|
|
.map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]]))
|
|
.collect()
|
|
}
|
|
impl FileSprites {
|
|
fn png(&self, sprite: &str, directory: &str) -> PathBuf {
|
|
crate::atlas_sources::texture_path(&self.root, sprite, directory)
|
|
}
|
|
fn image(&self, sprite: &str, directory: &str) -> Option<(usize, usize, Vec<u32>)> {
|
|
let (w, h, rgba) = crate::hud::decode(&self.png(sprite, directory)).ok()?;
|
|
Some((w as usize, h as usize, argb_pixels(&rgba)))
|
|
}
|
|
fn load(&self, sprite: &str) -> Option<SpriteMask> {
|
|
let png = self.png(sprite, "textures");
|
|
let (iw, ih, argb) = match self.image(sprite, "textures") {
|
|
Some(image) => image,
|
|
None => {
|
|
let p = self.permutations.iter().find_map(|s| s.find(sprite))?;
|
|
let (w, h, mut pixels) = self.image(p.base, "textures")?;
|
|
let (_, _, key) = self.image(p.palette_key, "textures/palettes")?;
|
|
let (_, _, target) = self.image(p.palette, "textures/palettes")?;
|
|
horizon_assets::palette::apply_palette(&mut pixels, &key, &target)?;
|
|
(w, h, pixels)
|
|
}
|
|
};
|
|
let alpha: Vec<u8> = argb.iter().map(|p| (p >> 24) as u8).collect();
|
|
let animation = fs::read_to_string(png.with_extension("png.mcmeta"))
|
|
.ok()
|
|
.and_then(|m| serde_json::from_str::<Value>(&m).ok())
|
|
.and_then(|m| m.get("animation").map(Value::to_string))
|
|
.and_then(|a| AnimationMetadata::from_json(&a).ok());
|
|
let (w, h) = match &animation {
|
|
Some(a) => {
|
|
let [w, h] = a.frame_size(iw as i32, ih as i32);
|
|
(w as usize, h as usize)
|
|
}
|
|
None => (iw, ih),
|
|
};
|
|
if w == 0 || h == 0 {
|
|
return None;
|
|
}
|
|
let columns = iw / w;
|
|
let total = columns * (ih / h);
|
|
let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten());
|
|
let frames: Vec<usize> = match clip {
|
|
Some(clip) => {
|
|
let mut unique = Vec::new();
|
|
for (index, _) in clip.sequence() {
|
|
if !unique.contains(&(*index as usize)) {
|
|
unique.push(*index as usize);
|
|
}
|
|
}
|
|
unique
|
|
}
|
|
None => vec![0],
|
|
};
|
|
let frames = frames
|
|
.into_iter()
|
|
.map(|f| {
|
|
let (fx, fy) = (f % columns * w, f / columns * h);
|
|
(0..h)
|
|
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
|
.map(|(x, y)| alpha[(fy + y) * iw + fx + x] == 0)
|
|
.collect()
|
|
})
|
|
.collect();
|
|
Some(SpriteMask {
|
|
width: w,
|
|
height: h,
|
|
frames,
|
|
})
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The renderer
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// The baked item models and everything resolution needs.
|
|
pub struct ItemRenderer {
|
|
pub models: ItemModels,
|
|
library: ModelLibrary,
|
|
sprites: FileSprites,
|
|
baked: Mutex<HashMap<String, Arc<BakedItemModel>>>,
|
|
extents: Mutex<HashMap<String, Arc<Vec<Vec3>>>>,
|
|
/// Entity model layers of the special renderers.
|
|
parts: HashMap<String, ModelPart>,
|
|
/// `colormap/grass.png` as ARGB.
|
|
grass: Vec<i32>,
|
|
/// `minecraft:item` registry ids (`Item.getId`).
|
|
item_ids: HashMap<String, i32>,
|
|
}
|
|
|
|
/// Every `models/**.json` of a namespace directory, by identifier.
|
|
fn load_models(root: &Path) -> BTreeMap<String, CuboidModel> {
|
|
let mut out = BTreeMap::new();
|
|
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
|
|
return out;
|
|
};
|
|
for ns in namespaces.flatten() {
|
|
let namespace = ns.file_name().to_string_lossy().into_owned();
|
|
let base = ns.path().join("models");
|
|
let mut stack = vec![base.clone()];
|
|
while let Some(dir) = stack.pop() {
|
|
let Ok(entries) = fs::read_dir(&dir) else {
|
|
continue;
|
|
};
|
|
for e in entries.flatten() {
|
|
let path = e.path();
|
|
if path.is_dir() {
|
|
stack.push(path);
|
|
} else if path.extension().is_some_and(|x| x == "json")
|
|
&& let Ok(rel) = path.strip_prefix(&base)
|
|
&& let Ok(text) = fs::read_to_string(&path)
|
|
&& let Ok(model) = CuboidModel::from_json(&text)
|
|
{
|
|
let rel = rel.with_extension("").to_string_lossy().replace('\\', "/");
|
|
out.insert(format!("{namespace}:{rel}"), model);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
/// Every `items/*.json` client item definition, by identifier.
|
|
fn load_definitions(root: &Path) -> BTreeMap<String, ClientItem> {
|
|
let mut out = BTreeMap::new();
|
|
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
|
|
return out;
|
|
};
|
|
for ns in namespaces.flatten() {
|
|
let namespace = ns.file_name().to_string_lossy().into_owned();
|
|
let Ok(files) = fs::read_dir(ns.path().join("items")) else {
|
|
continue;
|
|
};
|
|
for f in files.flatten() {
|
|
let path = f.path();
|
|
if path.extension().is_none_or(|e| e != "json") {
|
|
continue;
|
|
}
|
|
let name = path.file_stem().unwrap_or_default().to_string_lossy();
|
|
if let Some(item) = fs::read_to_string(&path)
|
|
.ok()
|
|
.and_then(|t| ClientItem::from_json(&t).ok())
|
|
{
|
|
out.insert(format!("{namespace}:{name}"), item);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
impl ItemRenderer {
|
|
/// Load item definitions, item prototypes (`items.json`), every model,
|
|
/// the special renderers' entity models and the grass colormap.
|
|
pub fn load(root: &Path) -> crate::Result<Self> {
|
|
let prototypes: BTreeMap<String, Components> =
|
|
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
|
|
let models = ItemModels {
|
|
definitions: load_definitions(root),
|
|
prototypes,
|
|
};
|
|
let library = ModelLibrary::with_item_generator(load_models(root))
|
|
.map_err(|e| format!("item models: {e:?}"))?;
|
|
let permutations = PalettedPermutations::from_atlas(
|
|
&fs::read_to_string(root.join("assets/minecraft/atlases/items.json"))
|
|
.unwrap_or_default(),
|
|
);
|
|
let parts = special::load_parts(root);
|
|
let grass = crate::hud::decode(&root.join("assets/minecraft/textures/colormap/grass.png"))
|
|
.map(|(_, _, rgba)| argb_pixels(&rgba).into_iter().map(|p| p as i32).collect())
|
|
.unwrap_or_default();
|
|
let item_ids = horizon_protocol::registry::Builtin::find(root)
|
|
.and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok())
|
|
.and_then(|b| {
|
|
let ids = b.get("minecraft:item")?;
|
|
let mut out = HashMap::new();
|
|
for i in 0.. {
|
|
let Some(name) = ids.name(i) else { break };
|
|
out.insert(name.to_owned(), i);
|
|
}
|
|
Some(out)
|
|
})
|
|
.unwrap_or_default();
|
|
Ok(Self {
|
|
item_ids,
|
|
models,
|
|
library,
|
|
sprites: FileSprites {
|
|
root: root.to_path_buf(),
|
|
permutations,
|
|
cache: Mutex::default(),
|
|
},
|
|
baked: Mutex::default(),
|
|
extents: Mutex::default(),
|
|
parts,
|
|
grass,
|
|
})
|
|
}
|
|
/// `ModelBakery` item baking, cached per model.
|
|
pub fn bake(&self, model: &str) -> Arc<BakedItemModel> {
|
|
if let Ok(cache) = self.baked.lock()
|
|
&& let Some(hit) = cache.get(model)
|
|
{
|
|
return hit.clone();
|
|
}
|
|
let baked = bake_item_model(&self.library, &self.sprites, model)
|
|
.or_else(|_| bake_item_model(&self.library, &self.sprites, MISSING_MODEL))
|
|
.map(Arc::new)
|
|
.unwrap_or_else(|_| {
|
|
Arc::new(BakedItemModel {
|
|
quads: Vec::new(),
|
|
uses_block_light: false,
|
|
particle: horizon_assets::model::Material {
|
|
sprite: horizon_assets::item_bake::MISSING_SPRITE.to_owned(),
|
|
force_translucent: false,
|
|
},
|
|
transforms: Default::default(),
|
|
})
|
|
});
|
|
if let Ok(mut cache) = self.baked.lock() {
|
|
cache.insert(model.to_owned(), baked.clone());
|
|
}
|
|
baked
|
|
}
|
|
/// `CuboidItemModelWrapper.computeExtents`: the distinct quad corners.
|
|
fn quad_extents(&self, model: &str, baked: &BakedItemModel) -> Arc<Vec<Vec3>> {
|
|
if let Ok(cache) = self.extents.lock()
|
|
&& let Some(hit) = cache.get(model)
|
|
{
|
|
return hit.clone();
|
|
}
|
|
let mut out: Vec<Vec3> = Vec::new();
|
|
for q in &baked.quads {
|
|
for p in q.positions {
|
|
let p = Vec3::from(p);
|
|
if !out.contains(&p) {
|
|
out.push(p);
|
|
}
|
|
}
|
|
}
|
|
let out = Arc::new(out);
|
|
if let Ok(mut cache) = self.extents.lock() {
|
|
cache.insert(model.to_owned(), out.clone());
|
|
}
|
|
out
|
|
}
|
|
fn special_extents(&self, model: &SpecialModel) -> Arc<Vec<Vec3>> {
|
|
let key = model.to_json().to_string();
|
|
if let Ok(cache) = self.extents.lock()
|
|
&& let Some(hit) = cache.get(&key)
|
|
{
|
|
return hit.clone();
|
|
}
|
|
let out = Arc::new(special::extents(self, model));
|
|
if let Ok(mut cache) = self.extents.lock() {
|
|
cache.insert(key, out.clone());
|
|
}
|
|
out
|
|
}
|
|
/// `ItemModelResolver.updateForTopItem`.
|
|
pub fn resolve(
|
|
&self,
|
|
stack: &StackView,
|
|
display: DisplayContext,
|
|
owner: Option<&OwnerState>,
|
|
level: Option<&LevelState>,
|
|
seed: i32,
|
|
env: &dyn ItemEnv,
|
|
) -> ItemRenderState {
|
|
let ctx = Context {
|
|
display,
|
|
owner,
|
|
level,
|
|
seed,
|
|
};
|
|
let resolved = self.models.resolve(stack, &ctx, env);
|
|
let mut animated = false;
|
|
let layers = resolved
|
|
.layers
|
|
.into_iter()
|
|
.map(|layer| {
|
|
let (geometry, baked, extents) = match layer.content {
|
|
LayerContent::Model { model } => {
|
|
let baked = self.bake(&model);
|
|
let extents = self.quad_extents(&model, &baked);
|
|
(LayerGeometry::Quads(baked.clone()), baked, extents)
|
|
}
|
|
LayerContent::Missing => {
|
|
let baked = self.bake(MISSING_MODEL);
|
|
let extents = self.quad_extents(MISSING_MODEL, &baked);
|
|
(LayerGeometry::Quads(baked.clone()), baked, extents)
|
|
}
|
|
LayerContent::Special {
|
|
base,
|
|
model,
|
|
argument,
|
|
} => {
|
|
let baked = self.bake(&base);
|
|
let extents = self.special_extents(&model);
|
|
(LayerGeometry::Special { model, argument }, baked, extents)
|
|
}
|
|
};
|
|
if layer.foil != FoilType::None {
|
|
animated = true;
|
|
}
|
|
LayerRender {
|
|
geometry,
|
|
tints: layer.tints,
|
|
foil: layer.foil,
|
|
matrix: glam_matrix(&baked.layer_matrix(display, &layer.transform)),
|
|
uses_block_light: baked.uses_block_light,
|
|
particle: sprite_name(&baked.particle.sprite).to_owned(),
|
|
extents,
|
|
}
|
|
})
|
|
.collect();
|
|
ItemRenderState {
|
|
display,
|
|
layers,
|
|
oversized_in_gui: resolved.oversized_in_gui,
|
|
animated,
|
|
}
|
|
}
|
|
/// `GrassColor.get` over the loaded colormap.
|
|
pub fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
|
|
let rain = downfall * temperature;
|
|
let x = ((1.0 - temperature) * 255.0) as i64;
|
|
let y = ((1.0 - rain) * 255.0) as i64;
|
|
let index = (y << 8 | x) as usize;
|
|
self.grass.get(index).copied().unwrap_or(-65281)
|
|
}
|
|
/// Submit a special model renderer directly (worn skulls of
|
|
/// `CustomHeadLayer`, which draw the skull model, not the item).
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn submit_special(
|
|
&self,
|
|
model: &SpecialModel,
|
|
argument: &Value,
|
|
has_foil: bool,
|
|
pose: Mat4,
|
|
sprites: &HashMap<String, Rect>,
|
|
host: &dyn SpecialHost,
|
|
sink: &mut dyn ItemSink,
|
|
) {
|
|
special::submit(self, model, argument, has_foil, pose, sprites, host, sink);
|
|
}
|
|
/// `Item.getId` (0 when the registry report is missing).
|
|
pub fn item_id(&self, item: &str) -> i32 {
|
|
self.item_ids.get(item).copied().unwrap_or(0)
|
|
}
|
|
pub(crate) fn part(&self, key: &str) -> Option<&ModelPart> {
|
|
self.parts.get(key)
|
|
}
|
|
}
|
|
/// A `horizon-assets` (row-major, JOML-exact) matrix as glam's.
|
|
pub fn glam_matrix(m: &horizon_assets::math::Mat4) -> Mat4 {
|
|
Mat4::from_cols_array_2d(&m.rows()).transpose()
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Stacks
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// An NBT value as the JSON its component codec reads.
|
|
pub fn tag_json(tag: &Tag) -> Value {
|
|
match tag {
|
|
Tag::End => Value::Null,
|
|
Tag::Byte(v) => Value::from(*v),
|
|
Tag::Short(v) => Value::from(*v),
|
|
Tag::Int(v) => Value::from(*v),
|
|
Tag::Long(v) => Value::from(*v),
|
|
Tag::Float(bits) => serde_json::Number::from_f64(f64::from(f32::from_bits(*bits)))
|
|
.map_or(Value::Null, Value::Number),
|
|
Tag::Double(bits) => {
|
|
serde_json::Number::from_f64(f64::from_bits(*bits)).map_or(Value::Null, Value::Number)
|
|
}
|
|
Tag::ByteArray(a) => Value::Array(a.iter().map(|b| Value::from(*b as i8)).collect()),
|
|
Tag::String(s) => Value::String(s.to_string_lossy()),
|
|
Tag::List(l) => Value::Array(l.iter().map(tag_json).collect()),
|
|
Tag::Compound(c) => Value::Object(
|
|
c.iter()
|
|
.map(|(k, v)| (k.to_string_lossy(), tag_json(v)))
|
|
.collect(),
|
|
),
|
|
Tag::IntArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()),
|
|
Tag::LongArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()),
|
|
}
|
|
}
|
|
/// The resolver's view of a client stack: its item, count and component patch.
|
|
pub fn stack_view(stack: &crate::items::ItemStack) -> StackView {
|
|
let mut view = StackView::new(&stack.item, stack.count as i32);
|
|
if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) {
|
|
for (k, v) in &c {
|
|
let key = k.to_string_lossy();
|
|
match key.strip_prefix('!') {
|
|
Some(removed) => view.patch.insert(removed.to_owned(), None),
|
|
None => view.patch.insert(key, Some(tag_json(v))),
|
|
};
|
|
}
|
|
}
|
|
view
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// World drawing
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// Entity vertices for submitted quads: the `item`/`entity` shader's
|
|
/// `minecraft_mix_light` with the level's diffuse lights on the vertex
|
|
/// colour, the packed lightmap coordinates (raised by light emission) and
|
|
/// overlay 7 for the glint.
|
|
pub struct WorldSink<'a> {
|
|
pub out: &'a mut Vec<Vertex>,
|
|
/// Packed light (`block_entity_render::vertex_light`).
|
|
pub light: u32,
|
|
/// The level's diffuse lights; `None` leaves the colour unshaded.
|
|
pub lights: Option<(Vec3, Vec3)>,
|
|
}
|
|
impl ItemSink for WorldSink<'_> {
|
|
fn quad(&mut self, q: ItemQuad) {
|
|
let brightness = self.lights.map_or(1.0, |l| diffuse(q.normal, l));
|
|
let [a, r, g, b] = q.color.to_be_bytes();
|
|
let c = |v: u8| (f32::from(v) * brightness) as u32;
|
|
let color = u32::from(a) << 24 | c(b) << 16 | c(g) << 8 | c(r);
|
|
// `LightCoordsUtil.lightCoordsWithEmission`: block light at least the emission.
|
|
let emission = u32::from(q.light_emission) * 16;
|
|
let light = if (self.light >> 8 & 0xFF) < emission {
|
|
(self.light & 0xFF) | emission << 8
|
|
} else {
|
|
self.light
|
|
};
|
|
let overlay = if q.foil == Foil::None { 0 } else { 7 };
|
|
for (p, uv) in q.pos.iter().zip(q.uv) {
|
|
self.out.push(Vertex {
|
|
pos: p.to_array(),
|
|
uv,
|
|
layer: overlay,
|
|
color,
|
|
light,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `ItemEntity.getSpin`.
|
|
pub fn item_spin(age_in_ticks: f32, bob_offset: f32) -> f32 {
|
|
age_in_ticks / 20.0 + bob_offset
|
|
}
|
|
/// `ItemClusterRenderState.getRenderedAmount`.
|
|
pub fn rendered_amount(count: u32) -> u32 {
|
|
match count {
|
|
0..=1 => 1,
|
|
2..=16 => 2,
|
|
17..=32 => 3,
|
|
33..=48 => 4,
|
|
_ => 5,
|
|
}
|
|
}
|
|
/// `ItemEntityRenderer.submitMultipleFromCount`: the poses of each copy of
|
|
/// a stack (`seed` is `ItemClusterRenderState.getSeedForItemStack`).
|
|
pub fn cluster_poses(state: &ItemRenderState, pose: Mat4, amount: u32, seed: i64) -> Vec<Mat4> {
|
|
use horizon_core::random::{LegacyRandom, RandomSource};
|
|
let mut out = Vec::new();
|
|
if amount == 0 {
|
|
return out;
|
|
}
|
|
let mut random = LegacyRandom::new(seed);
|
|
let (lo, hi) = state.bounding_box();
|
|
let depth = hi.z - lo.z;
|
|
let mut next = || random.next_float() * 2.0 - 1.0;
|
|
if depth > 0.0625 {
|
|
out.push(pose);
|
|
for _ in 1..amount {
|
|
let (x, y, z) = (next() * 0.15, next() * 0.15, next() * 0.15);
|
|
out.push(pose * Mat4::from_translation(Vec3::new(x, y, z)));
|
|
}
|
|
} else {
|
|
let offset = depth * 1.5;
|
|
let mut p = pose
|
|
* Mat4::from_translation(Vec3::new(0.0, 0.0, -(offset * (amount - 1) as f32 / 2.0)));
|
|
out.push(p);
|
|
p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset));
|
|
for _ in 1..amount {
|
|
let (x, y) = (next() * 0.15 * 0.5, next() * 0.15 * 0.5);
|
|
out.push(p * Mat4::from_translation(Vec3::new(x, y, 0.0)));
|
|
p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn rendered_amounts_follow_the_count_bands() {
|
|
let bands: Vec<u32> = [0, 1, 2, 16, 17, 32, 33, 48, 49, 64]
|
|
.iter()
|
|
.map(|c| rendered_amount(*c))
|
|
.collect();
|
|
assert_eq!(bands, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
|
|
}
|
|
#[test]
|
|
fn nbt_components_read_as_json() {
|
|
let tag = Tag::compound([
|
|
("a", Tag::Int(3)),
|
|
("b", Tag::List(vec![Tag::String("x".into())])),
|
|
("c", Tag::Float(1.5f32.to_bits())),
|
|
]);
|
|
assert_eq!(
|
|
tag_json(&tag),
|
|
serde_json::json!({"a": 3, "b": ["x"], "c": 1.5})
|
|
);
|
|
}
|
|
#[test]
|
|
fn normals_follow_the_inverse_transpose() {
|
|
let m = Mat4::from_scale(Vec3::new(2.0, 1.0, 1.0));
|
|
assert_eq!(transform_normal(m, Vec3::X), Vec3::X);
|
|
let r = Mat4::from_rotation_y(std::f32::consts::FRAC_PI_2);
|
|
assert!((transform_normal(r, Vec3::Z) - Vec3::X).length() < 1e-6);
|
|
}
|
|
}
|