Merge pull request #1916 from ludovic111/feat/shader-packs-shadow-casters

🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
This commit is contained in:
Ludovic Marie
2026-10-26 04:27:16 +01:00
committed by GitHub
10 changed files with 271 additions and 45 deletions
+15 -5
View File
@@ -25,6 +25,20 @@ impl Culler {
vertices: &mut Vec<crate::mesher::Vertex>,
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
let hidden = self.hidden(vertices, start, opaque);
if hidden {
vertices.truncate(start);
}
hidden
}
/// Whether this entity's completed camera-relative mesh (`vertices[start..]`) is hidden.
pub fn hidden(
&self,
vertices: &[crate::mesher::Vertex],
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
if start >= vertices.len() || self.remaining.get() == 0 {
return false;
@@ -42,11 +56,7 @@ impl Culler {
}
}
// Cover floating-point and rasterization edges as well as the vertices.
if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) {
vertices.truncate(start);
return true;
}
false
self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque)
}
/// Returns true only when a complete opaque block plane covers the bounds.
+7 -1
View File
@@ -1509,6 +1509,9 @@ struct Game<'a> {
/// This frame's view frustum, for culling entities and block entities.
view_frustum: Option<horizon_client::gfx::Frustum>,
entity_culler: Option<horizon_client::entity_culling::Culler>,
/// `Renderer::pack_shadow_casters` for this frame's entities: (keep what the culler hides,
/// build the player's model in first person); (false, false) without a shader pack.
pack_shadow_casters: (bool, bool),
/// A scripted flight from the control socket (`fly`).
flight: Option<control::Flight>,
/// The running agent action from the control socket (game/agent.rs).
@@ -6878,8 +6881,10 @@ impl Game<'_> {
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
// Mobs and their projectiles (a span each).
self.mob_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:player");
// In first person only a shader pack's shadow pass draws the player.
self.mark_player(out.len(), self.camera_type.first_person());
self.player_model_geometry(camera, self.clock.camera_fraction(), &mut out);
self.mark_entity(out.len(), "minecraft:player");
self.guest_model_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:evoker_fangs");
self.fangs_geometry(camera, alpha, &mut out);
@@ -12202,6 +12207,7 @@ impl<'a> Game<'a> {
agent: agent::Agent::default(),
view_frustum: None,
entity_culler: None,
pack_shadow_casters: (false, false),
pending_uploads: Vec::new(),
frame_graph: Default::default(),
extras: Default::default(),
@@ -15,6 +15,11 @@ fn opaque(facts: &StateFacts) -> bool {
impl Game<'_> {
pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) {
// Spans tell the pack's passes which entities are hidden; without them, nothing changes.
self.pack_shadow_casters = match (&self.renderer, &self.pack_ids) {
(Some(r), Some(_)) => r.pack_shadow_casters(),
_ => (false, false),
};
let at = camera.to_array().map(|v| v.floor() as i32);
self.entity_culler = (self.settings.horizon.entity_culling
// Packs can replace an opaque block's model or texture.
@@ -28,24 +33,29 @@ impl Game<'_> {
/// Use complete generated geometry so equipment, animation and custom
/// models cannot stick out of an assumed collision-sized culling box.
pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec<Vertex>, start: usize) {
if let Some(culler) = &self.entity_culler {
culler.cull_vertices(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
let Some(culler) = &self.entity_culler else {
return;
};
let hidden = culler.hidden(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
// A shader pack's shadow pass still draws what the camera cannot see.
if hidden && !(self.pack_shadow_casters.0 && self.hide_spans_from(start, vertices.len())) {
vertices.truncate(start);
}
}
}
@@ -412,7 +412,8 @@ impl Game<'_> {
}
/// Whether the player's own model shows in the world view.
fn player_model_shown(&self) -> bool {
!self.camera_type.first_person()
// A shader pack's shadow pass draws the player in first person too (shadowPlayer).
(!self.camera_type.first_person() || self.pack_shadow_casters.1)
&& self.sleeping.is_none()
&& !self.spectator()
&& self.potions.effects.get("minecraft:invisibility").is_none()
+27 -1
View File
@@ -232,6 +232,32 @@ impl Game<'_> {
.unwrap_or(ids.missing_block)
});
self.push_span(start, "BLOCK_ENTITIES", id);
let emission = self
.res
.facts()
.get(horizon_world::registry::BlockStateId(state))
.emission;
if let Some(last) = self.entity_spans.borrow_mut().last_mut() {
last.emissive = emission > 0;
}
}
/// Starts the span of the local player's model; `hidden` in first person, where only a
/// pack's shadow pass draws it.
pub(super) fn mark_player(&self, start: usize, hidden: bool) {
self.mark_entity(start, "minecraft:player");
if self.pack_ids.is_some()
&& let Some(last) = self.entity_spans.borrow_mut().last_mut()
{
last.player = true;
last.hidden = hidden;
}
}
/// Marks vertices `start..end` (one entity) as hidden from the camera, for an entity
/// Horizon's culling would drop but a pack's shadow pass still draws (`EntitySpan::hide`).
pub(super) fn hide_spans_from(&self, start: usize, end: usize) -> bool {
EntitySpan::hide(&mut self.entity_spans.borrow_mut(), start, end)
}
/// Starts a span of geometry that is not an entity (`PARTICLES`, `DESTROY`...).
@@ -247,7 +273,7 @@ impl Game<'_> {
start: start as u32,
stage: horizon_shaders::render_stage(stage),
id,
translucent: false,
..Default::default()
};
// A span that drew nothing gives way to the next.
match spans.last_mut() {
+12
View File
@@ -2599,6 +2599,18 @@ impl Renderer {
pub fn section_count(&self) -> usize {
self.sections.len()
}
/// What a shader pack's shadow pass draws of the entities this frame: (entities or block
/// entities other than the player, so those Horizon's culling hides from the camera are
/// kept for it; the local player, so its model is built in first person too). (false,
/// false) without a pack or its shadow pass.
pub fn pack_shadow_casters(&self) -> (bool, bool) {
let Some((_, Some(post))) = &self.pack_post else {
return (false, false);
};
let c = post.shadow_casters();
((c.entities && !c.only_player) || c.blocks, c.entities)
}
pub fn has_section(&self, key: SectionKey) -> bool {
self.sections.contains(key)
}
+70 -1
View File
@@ -7,7 +7,7 @@ use horizon_shaders::{RENDER_STAGES, render_stage};
/// Where a run of `Frame::entities` begins, and what it is (slice 7): the run lasts until the
/// next span. Recorded only while a shader pack draws entities, so Horizon's own frames carry
/// none; Horizon itself still draws the whole list at once.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EntitySpan {
/// The first vertex.
pub start: u32,
@@ -18,6 +18,44 @@ pub struct EntitySpan {
pub id: i32,
/// An entity part that blends (a name tag, a shadow): `gbuffers_entities_translucent`.
pub translucent: bool,
/// Hidden from the camera (Horizon's entity culling, the player in first person): only the
/// shadow pass draws it.
pub hidden: bool,
/// The local player (`shadowPlayer`).
pub player: bool,
/// A block entity whose block emits light (`shadowLightBlockEntities`).
pub emissive: bool,
}
impl EntitySpan {
/// Marks vertices `start..end` of `spans`' list (one entity) as hidden: the span covering
/// `start` is split there, the spans inside are hidden, and the geometry after `end` goes
/// on in the last span's kind. False when no span covers `start`.
pub fn hide(spans: &mut Vec<EntitySpan>, start: usize, end: usize) -> bool {
let Some(i) = spans.iter().rposition(|s| s.start as usize <= start) else {
return false;
};
let after = spans[spans.len() - 1];
if spans[i].start as usize != start {
let split = EntitySpan {
start: start as u32,
..spans[i]
};
spans.insert(i + 1, split);
}
for s in spans.iter_mut().skip(i) {
if s.start as usize >= start {
s.hidden = true;
}
}
if end > start {
spans.push(EntitySpan {
start: end as u32,
..after
});
}
true
}
}
/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`.
@@ -81,3 +119,34 @@ impl DrawUniforms {
pass.set_bind_group(2, &self.group, &[self.stride * render_stage(stage)]);
}
}
#[cfg(test)]
mod tests {
use super::EntitySpan;
fn span(start: u32, id: i32) -> EntitySpan {
EntitySpan {
start,
id,
..Default::default()
}
}
#[test]
fn hide_splits_the_span_around_one_entity() {
// Two cows in one span: the second (vertices 8..16) is hidden.
let mut spans = vec![span(0, 7)];
assert!(EntitySpan::hide(&mut spans, 8, 16));
let hidden = EntitySpan {
hidden: true,
..span(8, 7)
};
assert_eq!(spans, [span(0, 7), hidden, span(16, 7)]);
// An entity with its own span and a part after it (armour) is hidden whole.
let mut spans = vec![span(0, 1), span(4, 2), span(6, 3)];
assert!(EntitySpan::hide(&mut spans, 4, 10));
assert!(!spans[0].hidden && spans[1].hidden && spans[2].hidden);
assert_eq!(spans[3], span(10, 3));
assert!(!EntitySpan::hide(&mut Vec::new(), 0, 4));
}
}
+53 -6
View File
@@ -170,6 +170,30 @@ pub(super) struct Draw {
pub slot: u32,
}
/// Which entity runs a pack's shadow pass draws (2.4, 3.2).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Casters {
/// `shadow_entities` (or `shadow`) draws entities...
pub entities: bool,
/// ...only the local player (`shadowPlayer` without `shadowEntities`).
pub only_player: bool,
/// `shadow_block` (or `shadow`) draws block entities...
pub blocks: bool,
/// ...only those whose block emits light (`shadowLightBlockEntities`).
pub only_lit: bool,
}
impl Casters {
/// Whether the shadow pass draws `span`'s run, of kind `program`.
pub fn cast(&self, span: &EntitySpan, program: usize) -> bool {
match program {
ENTITY => self.entities && (!self.only_player || span.player),
BLOCK => self.blocks && (!self.only_lit || span.emissive),
_ => false,
}
}
}
/// The vertices and per-draw uniforms of the runs a pack draws, rebuilt each frame.
pub(super) struct PackEntities {
vertices: wgpu::Buffer,
@@ -285,7 +309,7 @@ impl PackEntities {
/// Splits `entities` between the pack, which draws the runs of `spans` its programs cover
/// (`drawn`: whether it has `gbuffers_entities`, `gbuffers_block` or their fallbacks), and
/// Horizon, which draws the rest (`rest`). Uploads the pack's part, and the runs its shadow
/// programs draw (`shadow`: entities, block entities).
/// programs draw (`shadow`). Runs hidden from the camera only ever cast shadows.
#[allow(clippy::too_many_arguments)]
pub fn prepare(
&mut self,
@@ -295,7 +319,7 @@ impl PackEntities {
entities: &[Vertex],
spans: &[EntitySpan],
drawn: [bool; PROGRAMS],
shadow: [bool; 2],
shadow: Casters,
rest: &mut Vec<Vertex>,
) {
self.draws.clear();
@@ -307,9 +331,9 @@ impl PackEntities {
for (span, range) in runs(entities.len(), spans) {
let run = &entities[range];
let program = program_of(&span).filter(|_| plain(run));
let pack = program.is_some_and(|p| drawn[p]);
let casts = program.is_some_and(|p| shadow.get(p).copied().unwrap_or(false));
if !pack {
let pack = program.is_some_and(|p| drawn[p]) && !span.hidden;
let casts = program.is_some_and(|p| shadow.cast(&span, p));
if !pack && !span.hidden {
rest.extend_from_slice(run);
}
let Some(program) = program.filter(|_| (pack || casts) && !run.is_empty()) else {
@@ -446,7 +470,7 @@ mod tests {
start,
stage: render_stage(stage),
id,
translucent: false,
..Default::default()
};
let spans = [
span(2, "ENTITIES", 7),
@@ -473,5 +497,28 @@ mod tests {
assert_eq!(entity_color(1)[0], 1.0);
assert!((entity_color(1)[3] - (1.0 - 178.0 / 255.0)).abs() < 1e-6);
assert_eq!(entity_color(0), [0.0; 4]);
// The shadow pass: entities, the player alone, block entities, those that emit light.
let all = Casters {
entities: true,
blocks: true,
..Default::default()
};
let player = EntitySpan {
player: true,
..spans[0]
};
let lit = EntitySpan {
emissive: true,
..spans[2]
};
assert!(all.cast(&spans[0], ENTITY) && all.cast(&spans[2], BLOCK));
assert!(!all.cast(&spans[1], PARTICLE));
let some = Casters {
only_player: true,
only_lit: true,
..all
};
assert!(!some.cast(&spans[0], ENTITY) && some.cast(&player, ENTITY));
assert!(!some.cast(&spans[2], BLOCK) && some.cast(&lit, BLOCK));
}
}
+33 -9
View File
@@ -149,6 +149,8 @@ struct Entities {
late: [bool; PROGRAMS],
/// What draws entities and block entities into the shadow map (2.4).
shadow: [Option<Pass>; 2],
/// Only the player, only block entities that emit light (3.2).
only: (bool, bool),
}
impl Entities {
@@ -1086,6 +1088,7 @@ impl PackPost {
post.particles,
];
let late = [false, false, post.translucent_late, post.particles_late];
let shadow_only = (post.shadow_only_player, post.shadow_only_lit_blocks);
let shadow_programs = [post.shadow_entities, post.shadow_block];
let entity_vertices = (programs.iter().chain(&shadow_programs))
.any(Option::is_some)
@@ -1114,6 +1117,7 @@ impl PackPost {
passes: entity_passes,
late,
shadow: shadow_entities,
only: shadow_only,
});
let cloud_geometry = world.clouds.map(|layout| Geometry {
buffers: &entity_buffers,
@@ -1221,10 +1225,17 @@ impl PackPost {
// Timed (and labelled) apart from the terrain's shadow pass, which may run the same
// program.
let mut entities = entities;
for (part, pass) in (entities.iter_mut()).flat_map(|e| parts.iter().zip(&mut e.shadow)) {
if let Some(p) = pass {
notes.push(format!("{part} cast shadows with {}", p.name));
p.name.push_str(&format!(" ({part})"));
for e in entities.iter_mut() {
let only = [
(e.only.0, " (only the player)"),
(e.only.1, " (only those that emit light)"),
];
for ((part, pass), (only, which)) in parts.iter().zip(&mut e.shadow).zip(only) {
if let Some(p) = pass {
let which = if only { which } else { "" };
notes.push(format!("{part}{which} cast shadows with {}", p.name));
p.name.push_str(&format!(" ({part})"));
}
}
}
let depth1 = water.is_some()
@@ -1874,17 +1885,13 @@ impl PackPost {
spans: &[super::pack_draw::EntitySpan],
rest: &mut Vec<super::Vertex>,
) {
let shadow = self.shadow_casters();
let Some(e) = &mut self.entities else {
rest.clear();
rest.extend_from_slice(entities);
return;
};
let drawn = e.passes.each_ref().map(Option::is_some);
// Only while the shadow pass draws this frame.
let shadow = e
.shadow
.each_ref()
.map(|p| p.is_some() && self.shadow_targets.is_some());
e.geometry.prepare(
device,
queue,
@@ -1897,6 +1904,23 @@ impl PackPost {
);
}
/// Which entity runs the shadow pass draws: none without it.
pub fn shadow_casters(&self) -> super::pack_entities::Casters {
let Some(e) = self
.entities
.as_ref()
.filter(|_| self.shadow_targets.is_some())
else {
return Default::default();
};
super::pack_entities::Casters {
entities: e.shadow[0].is_some(),
only_player: e.only.0,
blocks: e.shadow[1].is_some(),
only_lit: e.only.1,
}
}
/// Whether the pack draws entities or block entities itself.
pub fn has_entities(&self) -> bool {
self.entities.is_some()
+24 -3
View File
@@ -252,6 +252,11 @@ pub struct Post {
/// `shadow`) from the light, unless `shadowEntities`/`shadowBlockEntities` is false.
pub shadow_entities: Option<PostProgram>,
pub shadow_block: Option<PostProgram>,
/// `shadowEntities=false` with `shadowPlayer=true`: of the entities, only the player casts.
pub shadow_only_player: bool,
/// `shadowBlockEntities=false` with `shadowLightBlockEntities=true`: only block entities
/// whose block emits light cast.
pub shadow_only_lit_blocks: bool,
/// `shadowcomp`..`shadowcomp99`, after the shadow pass (2.1).
pub shadow_comp: Vec<PostProgram>,
/// Translucent entities draw after deferred (`separateEntityDraws`, 3.2).
@@ -323,6 +328,8 @@ pub fn load_post(
shadow_water: None,
shadow_entities: None,
shadow_block: None,
shadow_only_player: false,
shadow_only_lit_blocks: false,
shadow_comp: Vec::new(),
translucent_late: false,
particles_late: false,
@@ -545,18 +552,23 @@ fn load_shadow(
})
};
// `shadowTerrain`, `shadowTranslucent`, `shadowEntities` and `shadowBlockEntities` (3.2)
// leave their part out of the shadow pass; all are on by default (OQ-19).
// leave their part out of the shadow pass; all are on by default (OQ-19). `shadowPlayer`
// and `shadowLightBlockEntities` (E, off by default) keep the player, and block entities
// that emit light, when the first two are off.
let keep = |key: &str| properties.get(key).is_none_or(|v| v.trim() != "false");
let set = |key: &str| properties.get(key).is_some_and(|v| v.trim() == "true");
let only_player = !keep("shadowEntities") && set("shadowPlayer");
let only_lit = !keep("shadowBlockEntities") && set("shadowLightBlockEntities");
let shadow = keep("shadowTerrain")
.then(|| load(&["shadow"], terrain))
.flatten();
let water = keep("shadowTranslucent")
.then(|| load(&["shadow_water", "shadow"], terrain))
.flatten();
let shadow_entities = keep("shadowEntities")
let shadow_entities = (keep("shadowEntities") || only_player)
.then(|| load(&["shadow_entities", "shadow"], entities))
.flatten();
let shadow_block = keep("shadowBlockEntities")
let shadow_block = (keep("shadowBlockEntities") || only_lit)
.then(|| load(&["shadow_block", "shadow"], entities))
.flatten();
if shadow.is_none() && terrain.is_some() {
@@ -569,6 +581,8 @@ fn load_shadow(
loader.post.shadow_water = water;
loader.post.shadow_entities = shadow_entities;
loader.post.shadow_block = shadow_block;
loader.post.shadow_only_player = only_player;
loader.post.shadow_only_lit_blocks = only_lit;
}
struct Loader<'a> {
@@ -892,6 +906,13 @@ mod tests {
assert!(
off.shadow.is_some() && off.shadow_entities.is_none() && off.shadow_block.is_none()
);
// shadowPlayer and shadowLightBlockEntities keep a part of each.
let some = load(
"shadowEntities=false\nshadowPlayer=true\nshadowBlockEntities=false\nshadowLightBlockEntities=true",
);
assert!(some.shadow_entities.is_some() && some.shadow_only_player);
assert!(some.shadow_block.is_some() && some.shadow_only_lit_blocks);
assert!(!post.shadow_only_player && !post.shadow_only_lit_blocks);
let comp: Vec<_> = post
.shadow_comp
.iter()