Load every vanilla block model and export gameplay facts

Model catalog now binds all registered blockstates. Sprites accept
fractional alpha, interpolated animations and non-16px frames
(resampled into the shared 16px array). Resource preparation extracts
every jar asset and data file, exports per-state light/hardness/sound
facts through a vanilla exporter, and bundles item default components
from vanilla's data generator reports.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-07 18:52:46 +02:00
parent 082cbb4077
commit 5799bc6dc6
6 changed files with 150 additions and 38 deletions
+7 -2
View File
@@ -55,8 +55,13 @@ pub fn prepare(
registry: &BlockRegistry,
sprites: &mut Sprites,
) -> Result<PreparedModels> {
let mut blocks = GALLERY.map(|(name, _)| name).to_vec();
blocks.extend(crate::assets::MATERIALS);
let facts: serde_json::Map<String, Value> =
serde_json::from_reader(std::fs::File::open(root.join("model-states.json"))?)?;
let blocks: Vec<&str> = facts
.keys()
.filter(|name| registry.default_state(name).is_some())
.filter_map(|name| name.strip_prefix("minecraft:"))
.collect();
let catalog = StateModels::load(root, registry, &blocks, sprites)?;
let mut placements = Vec::new();
let mut states = Vec::new();
+4 -6
View File
@@ -31,6 +31,8 @@ pub struct BakedFace {
pub quad: ModelQuad,
pub layer: u32,
pub opaque: bool,
/// Fractional alpha: drawn in the sorted translucent pass.
pub translucent: bool,
}
pub struct BakedModel {
pub faces: Vec<BakedFace>,
@@ -168,14 +170,10 @@ impl StateModels {
bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?
.into_iter()
.map(|quad| {
if quad.material.force_translucent || quad.tint_index != -1 {
return Err(
"inspection gallery requires untinted opaque or binary-cutout materials"
.into(),
);
}
let layer = sprites.insert(root, &quad.material.sprite)?;
Ok(BakedFace {
translucent: quad.material.force_translucent
|| sprites.translucent[layer as usize],
quad,
layer,
opaque: sprites.opaque[layer as usize],
+3 -1
View File
@@ -27,7 +27,7 @@ pub fn cube_styles(faces: &[BakedFace]) -> Option<[CubeStyle; 6]> {
}
let mut styles = [None; 6];
for face in faces {
if !face.opaque || face.quad.light_emission != 0 {
if !face.opaque || face.translucent || face.quad.tint_index != -1 || face.quad.light_emission != 0 {
return None;
}
let q = &face.quad;
@@ -114,6 +114,7 @@ mod tests {
quad,
layer: 7,
opaque: true,
translucent: false,
})
.collect();
let Some(styles) = cube_styles(&faces) else {
@@ -147,6 +148,7 @@ mod tests {
quad,
layer: 0,
opaque: true,
translucent: false,
})
.collect();
faces[0].opaque = false;
+24 -27
View File
@@ -1,4 +1,4 @@
//! Shared nearest-sampled sprite array for the controlled scene.
//! Shared nearest-sampled sprite array for block and item textures.
use crate::Result;
use horizon_assets::animation::{AnimationClip, AnimationMetadata};
use std::{
@@ -31,7 +31,10 @@ pub struct Sprites {
pub layers: BTreeMap<String, u32>,
pub animations: Vec<SpriteAnimation>,
pub opaque: Vec<bool>,
pub translucent: Vec<bool>,
}
/// Edge length of every sprite array layer.
pub const SPRITE_SIZE: u32 = 16;
impl Sprites {
pub fn insert(&mut self, root: &Path, name: &str) -> Result<u32> {
if let Some(layer) = self.layers.get(name) {
@@ -62,27 +65,14 @@ impl Sprites {
];
let info = reader.next_frame(&mut bytes)?;
let (width, height) = if let Some(animation) = &animation {
if animation.interpolate {
return Err(
"interpolated animation is not yet supported by the inspection renderer".into(),
);
}
let [width, height] =
animation.frame_size(i32::try_from(info.width)?, i32::try_from(info.height)?);
(u32::try_from(width)?, u32::try_from(height)?)
} else {
(info.width, info.height)
};
if width != height
|| width == 0
|| info.width % width != 0
|| info.height % height != 0
|| (self.size != 0 && self.size != width)
{
return Err(format!(
"inspection sprite {name} must be square and match the sprite array dimensions"
)
.into());
if width == 0 || height == 0 || info.width % width != 0 || info.height % height != 0 {
return Err(format!("sprite {name} has invalid frame dimensions").into());
}
let channels = info.color_type.samples();
let mut pixels = Vec::with_capacity(info.width as usize * info.height as usize * 4);
@@ -94,12 +84,6 @@ impl Sprites {
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
_ => return Err("unsupported expanded sprite format".into()),
};
if rgba[3] != 0 && rgba[3] != 255 {
return Err(format!(
"inspection sprite {name} requires fractional-alpha rendering"
)
.into());
}
pixels.extend(rgba);
}
let layer = u32::try_from(self.layers.len())?;
@@ -109,10 +93,16 @@ impl Sprites {
for index in 0..count {
let x = index % columns * width;
let y = index / columns * height;
let mut frame = Vec::with_capacity((width * height * 4) as usize);
for row in y..y + height {
let offset = ((row * info.width + x) * 4) as usize;
frame.extend_from_slice(&pixels[offset..offset + (width * 4) as usize]);
// Every array layer is SPRITE_SIZE square; other sizes are
// nearest-resampled so UVs (normalized per layer) are unchanged.
let mut frame = Vec::with_capacity((SPRITE_SIZE * SPRITE_SIZE * 4) as usize);
for row in 0..SPRITE_SIZE {
let source_row = y + row * height / SPRITE_SIZE;
for column in 0..SPRITE_SIZE {
let offset =
((source_row * info.width + x + column * width / SPRITE_SIZE) * 4) as usize;
frame.extend_from_slice(&pixels[offset..offset + 4]);
}
}
frames.push(frame);
}
@@ -133,8 +123,15 @@ impl Sprites {
}
self.opaque
.push(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
self.translucent.push(
pixels
.as_chunks::<4>()
.0
.iter()
.any(|p| p[3] != 0 && p[3] != 255),
);
self.layers.insert(name.to_owned(), layer);
self.size = width;
self.size = SPRITE_SIZE;
self.pixels.extend_from_slice(&frames[initial]);
Ok(layer)
}
@@ -0,0 +1,79 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.server.Bootstrap;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
/**
* Original exporter of per-state gameplay facts read through vanilla's own accessors:
* light, hardness, sounds and tool requirements. Item components come from the
* vanilla data generator's component reports.
*/
public final class VanillaGameplayFactsExporter {
private static JsonObject sound(SoundEvent event) {
var result = new JsonObject();
result.addProperty("id", event.location().toString());
return result;
}
private static JsonArray states() {
var states = new JsonArray();
var level = EmptyBlockGetter.INSTANCE;
for (var state : Block.BLOCK_STATE_REGISTRY) {
var o = new JsonObject();
var block = state.getBlock();
o.addProperty("id", Block.getId(state));
o.addProperty("emission", state.getLightEmission());
o.addProperty("dampening", state.getLightDampening());
o.addProperty("skylight_down", state.propagatesSkylightDown());
o.addProperty("shape_occlusion", state.useShapeForLightOcclusion());
o.addProperty("can_occlude", state.canOcclude());
o.addProperty("solid_render", state.isSolidRender());
o.addProperty("hardness", state.getDestroySpeed(level, BlockPos.ZERO));
o.addProperty("requires_tool", state.requiresCorrectToolForDrops());
o.addProperty("replaceable", state.canBeReplaced());
o.addProperty("random_ticks", state.isRandomlyTicking());
o.addProperty("block_entity", state.hasBlockEntity());
o.addProperty("render_shape", state.getRenderShape().name());
o.addProperty("liquid", state.liquid());
o.addProperty("ignited_by_lava", state.ignitedByLava());
o.addProperty("push", state.getPistonPushReaction().name());
o.addProperty("offset", state.hasOffsetFunction());
o.addProperty("full_collision", state.isCollisionShapeFullBlock(level, BlockPos.ZERO));
o.addProperty("map_color", state.getMapColor(level, BlockPos.ZERO).col);
o.addProperty("friction", block.getFriction());
o.addProperty("speed_factor", block.getSpeedFactor());
o.addProperty("jump_factor", block.getJumpFactor());
o.addProperty("explosion_resistance", block.getExplosionResistance());
o.addProperty("item", BuiltInRegistries.ITEM.getKey(block.asItem()).toString());
var sound = state.getSoundType();
var sounds = new JsonObject();
sounds.addProperty("volume", sound.getVolume());
sounds.addProperty("pitch", sound.getPitch());
sounds.add("break", sound(sound.getBreakSound()));
sounds.add("step", sound(sound.getStepSound()));
sounds.add("place", sound(sound.getPlaceSound()));
sounds.add("hit", sound(sound.getHitSound()));
sounds.add("fall", sound(sound.getFallSound()));
o.add("sound", sounds);
states.add(o);
}
return states;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var result = new JsonObject();
result.add("states", states());
Files.writeString(Path.of(args[0]), new Gson().toJson(result), StandardCharsets.UTF_8);
}
}
+33 -2
View File
@@ -161,8 +161,9 @@ def main():
(root/'render-definitions.json').write_bytes((export/'definitions.json').read_bytes())
(root/'occlusion.nbt').write_bytes((export/'occlusion.nbt').read_bytes())
count = 0
prefixes = ('assets/minecraft/blockstates/', 'assets/minecraft/models/block/',
'assets/minecraft/textures/block/')
# The playable client needs every client asset (textures, models, fonts, GUI)
# and every data-pack resource (worldgen, recipes, loot tables, tags).
prefixes = ('assets/', 'data/')
with zipfile.ZipFile(jars['client']) as archive:
version = json.loads(archive.read('version.json'))
for name in archive.namelist():
@@ -177,6 +178,35 @@ def main():
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
count += 1
gameplay = root / 'gameplay-facts.json'
gameplay_oracle = oracle.with_name('VanillaGameplayFactsExporter.java')
gameplay_sources = base.source_hashes([gameplay_oracle])
if not (previous.get('gameplay_exporters_sha256') == gameplay_sources and gameplay.exists()
and previous.get('server_sha256') == origin['server_sha256']):
classes = lab.LOCAL / 'gameplay-facts' / 'classes'; classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
with (root / 'gameplay-export.log').open('w') as log:
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
'-cp', dependencies, '-d', str(classes), str(gameplay_oracle)],
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaGameplayFactsExporter', str(gameplay)],
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
items = root / 'items.json'
if not items.exists() or previous.get('server_sha256') != origin['server_sha256']:
# Vanilla's own data generator reports every item's default components.
datagen = lab.LOCAL / 'datagen'; datagen.mkdir(exist_ok=True)
with (datagen / 'datagen.log').open('w') as log:
subprocess.run(['java', '-DbundlerMainClass=net.minecraft.data.Main', '-jar',
str(jars['server'].with_name('server.jar')), '--reports', '--output', 'out'],
cwd=datagen, check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
reports = datagen / 'out' / 'reports'
components = {f'minecraft:{f.stem}': json.loads(f.read_text())['components']
for f in sorted((reports / 'minecraft' / 'components' / 'item').glob('*.json'))}
items.write_text(json.dumps(components))
(root / 'biome-parameters').mkdir(exist_ok=True)
for f in (reports / 'biome_parameters' / 'minecraft').glob('*.json'):
(root / 'biome-parameters' / f.name).write_bytes(f.read_bytes())
lab.write_json(manifest, {'schema': 7, **origin,
'health_exporters_sha256': health_sources,
'health_files_sha256': {name: lab.digest(root/name, 'sha256') for name in health_files},
@@ -187,6 +217,7 @@ def main():
'render_exporters_sha256': render_sources,
'render_files_sha256': {name: lab.digest(root/name, 'sha256') for name in render_files},
'model_state_exporters_sha256': binding_sources,
'gameplay_exporters_sha256': gameplay_sources,
'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'],
'facts_sha256': lab.digest(facts, 'sha256'),
'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})