Instance one mass group of mod models on the GPU (#147)
After the retained meshes of #126 a frame still transformed and uploaded every model's vertices every frame (~3.1 MB vertex + ~4 MB motion at ~135 models in the #126 M5 report). The one mass group of identical models now draws from a GPU mesh retained per pack generation: a frame writes only instance records (current and previous drawn pose, model id, light, glow) and the same stream feeds the HD G-buffer, the HD motion pass, the sun shadow cascades and the classic entity pass (main and mod cameras). The instance shader mirrors the CPU bake's transform, normal quantization and light/material rules; a static model carries identical poses and keeps zero object velocity (#143's contract, unchanged jitter conventions). Everything else stays on the per-vertex path, bit-identical to before: groups under eight models, HORIZON_MODEL_INSTANCING=0, a shader pack that draws entities, or a missing renderer fall back whole. The diagnostic runtime toggle `model-instancing on|off` (control command) switches paths without a restart so the bench driver can compare both on one recording; the drawn-pose history both paths keep makes the switch seamless for motion. Reload and world unload drop the GPU meshes with the #126 cache; the pack generation guard catches a reload too. Counters in `stats`: instanced_models, instanced_quads, instance_bytes, gpu_mesh_builds. Driver support for the #147 bench: `stats raw` reports every recorded frame/CPU/GPU time; HORIZON_MOD_FUEL_PROFILE=1 reports the guests' observed fuel per callback and average wall time per call in `stats`. Tests: mod_models::tests (group choice and tie-break, GPU mesh faces, shader math vs the CPU matrix, static zero velocity, the #126 parity test unchanged), gfx attribute-layout and WGSL validation tests. Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
@@ -157,6 +157,59 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
|
||||
out.prev_clip = globals.prev_view_proj * vec4(previous + globals.camera_delta.xyz, 1.0);
|
||||
return out;
|
||||
}
|
||||
// AirDef fork (#147): one mass group of mod models, GPU-instanced. Slot 0 is
|
||||
// the retained mesh of the group's block state (model space, atlas-resolved
|
||||
// UVs, unquantized normals, material and emission); slot 1 steps per model:
|
||||
// its current and previous drawn poses, light, id and flags. The transform,
|
||||
// normal quantization and light/material rules mirror the CPU bake
|
||||
// (game/mod_models.rs's emit_mod_mesh), so main, motion and shadows share one
|
||||
// instance stream and the fallback stays vertex-identical.
|
||||
fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
|
||||
return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);
|
||||
}
|
||||
fn model_instance_vertex(position: vec3<f32>, uv: vec2<f32>, normal: vec3<f32>,
|
||||
layer: u32, emission: u32, pose: vec4<f32>, rotation: vec4<f32>,
|
||||
light: u32, flags: u32) -> Out {
|
||||
// The model's unit cube turned and scaled about its centre, as the CPU's
|
||||
// scale_rotation_translation * translate(-0.5) matrix transforms it.
|
||||
let at = quat_rotate(rotation, (position - vec3(0.5)) * pose.w) + pose.xyz;
|
||||
// Uniform scale cancels in the inverse-transpose's normalize; a degenerate
|
||||
// face keeps the zero normal the CPU's normalize_or_zero gives it.
|
||||
let n = quat_rotate(rotation, normal);
|
||||
let len = length(n);
|
||||
let nn = select(vec3(0.0), n / len, len > 1e-8);
|
||||
// RGBA8_SNORM, truncated toward zero as the CPU's `as i8` does.
|
||||
let qn = vec3<i32>(clamp(nn, vec3(-1.0), vec3(1.0)) * 127.0);
|
||||
var overlay = layer;
|
||||
var packed = (light & 0xFFu) | (max((light >> 8u) & 0xFFu, emission) << 8u);
|
||||
if (flags & 1u) != 0u {
|
||||
overlay = 40u;
|
||||
} else if layer == 40u {
|
||||
packed = 240u | (240u << 8u);
|
||||
}
|
||||
let bytes = vec4(packed & 0xFFu, (packed >> 8u) & 0xFFu,
|
||||
(packed >> 16u) & 0xFFu, (packed >> 24u) & 0xFFu);
|
||||
return entity_vertex(at, uv, overlay, vec4(1.0), bytes, vec4(vec3<f32>(qn) / 127.0, 1.0));
|
||||
}
|
||||
@vertex fn vs_model_instance(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) normal: vec3<f32>, @location(3) layer: u32, @location(4) emission: u32,
|
||||
@location(5) pose: vec4<f32>, @location(6) rotation: vec4<f32>,
|
||||
@location(7) previous: vec4<f32>, @location(8) old_rotation: vec4<f32>,
|
||||
@location(9) light: u32, @location(10) id: u32, @location(11) flags: u32) -> Out {
|
||||
return model_instance_vertex(position, uv, normal, layer, emission, pose, rotation, light, flags);
|
||||
}
|
||||
// The motion-only pass: the same instance stream, the previous drawn pose
|
||||
// where the vertex was. A static model's poses match and its vector stays zero.
|
||||
@vertex fn vs_model_instance_motion(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) normal: vec3<f32>, @location(3) layer: u32, @location(4) emission: u32,
|
||||
@location(5) pose: vec4<f32>, @location(6) rotation: vec4<f32>,
|
||||
@location(7) previous: vec4<f32>, @location(8) old_rotation: vec4<f32>,
|
||||
@location(9) light: u32, @location(10) id: u32, @location(11) flags: u32) -> Out {
|
||||
var out = model_instance_vertex(position, uv, normal, layer, emission, pose, rotation, light, flags);
|
||||
let was = quat_rotate(old_rotation, (position - vec3(0.5)) * previous.w) + previous.xyz;
|
||||
out.prev_clip = globals.prev_view_proj * vec4(was + globals.camera_delta.xyz, 1.0);
|
||||
return out;
|
||||
}
|
||||
// Retained bolt-local geometry, translated using the same f64 camera
|
||||
// subtraction as the former CPU path before adding each local f32 position.
|
||||
// The bolt offset is instance attribute 7: 6 is the entity vertex's glint UV.
|
||||
|
||||
@@ -12003,6 +12003,22 @@ impl Game<'_> {
|
||||
let motion_models = std::mem::take(&mut self.mods.models.motion);
|
||||
#[cfg(not(feature = "mods"))]
|
||||
let motion_models = Vec::new();
|
||||
// The instanced mod-model group (#147): its records and mesh state.
|
||||
// The title draws no world, and its classic pass would draw the records.
|
||||
#[cfg(feature = "mods")]
|
||||
let model_instances = if title {
|
||||
Vec::new()
|
||||
} else {
|
||||
std::mem::take(&mut self.mods.models.instances)
|
||||
};
|
||||
#[cfg(not(feature = "mods"))]
|
||||
let model_instances = Vec::new();
|
||||
#[cfg(feature = "mods")]
|
||||
let model_instance_state = (!title)
|
||||
.then(|| self.mods.models.instance_state.map(|s| s.0))
|
||||
.flatten();
|
||||
#[cfg(not(feature = "mods"))]
|
||||
let model_instance_state = None;
|
||||
// The main view is the frame itself, not a picture of its own.
|
||||
let mod_views: Vec<_> = self
|
||||
.mod_views(alpha)
|
||||
@@ -12115,6 +12131,8 @@ impl Game<'_> {
|
||||
}),
|
||||
entities: &entities,
|
||||
motion_models: &motion_models,
|
||||
model_instances: &model_instances,
|
||||
model_instance_state,
|
||||
entity_spans: &entity_spans,
|
||||
glowing: &glowing,
|
||||
dynamic_lights: &self.dynamic_lights,
|
||||
@@ -12191,6 +12209,7 @@ impl Game<'_> {
|
||||
#[cfg(feature = "mods")]
|
||||
{
|
||||
self.mods.models.motion = motion_models;
|
||||
self.mods.models.instances = model_instances;
|
||||
}
|
||||
*self.entity_spans.get_mut() = entity_spans;
|
||||
*self.glowing_vertices.get_mut() = glowing;
|
||||
@@ -15048,6 +15067,8 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
nether_lighting: false,
|
||||
entities: &[],
|
||||
motion_models: &[],
|
||||
model_instances: &[],
|
||||
model_instance_state: None,
|
||||
entity_spans: &[],
|
||||
glowing: &[],
|
||||
dynamic_lights: &[],
|
||||
|
||||
@@ -35,7 +35,8 @@ const HELP: &[&str] = &[
|
||||
"type TEXT type into the open chat box (key enter tap sends)",
|
||||
"chat-log [N] the newest N chat messages (default 10)",
|
||||
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs mods graphics graphics-advanced)",
|
||||
"stats [reset] frame-time summary since the last reset",
|
||||
"stats [reset|raw] frame-time summary since the last reset (raw: every frame/cpu/gpu time too)",
|
||||
"model-instancing on|off GPU instancing of the mod models' mass group (#147 diagnostic; off = per-vertex fallback)",
|
||||
"bench SECONDS reset stats, wait, then reply with the summary",
|
||||
"fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)",
|
||||
"open WORLD [SEED] [creative] open or create a world from the title screen",
|
||||
@@ -703,12 +704,67 @@ impl Game<'_> {
|
||||
let mut summary = self.frame_stats.summary();
|
||||
// AirDef fork (#126): what the mod-model path did since the reset.
|
||||
summary["mod_models"] = self.mod_model_profile();
|
||||
// AirDef fork (#147): every recorded frame time, for the bench
|
||||
// driver's own percentiles and worst-frame counts.
|
||||
if words.contains(&"raw") {
|
||||
summary["frame_ms"] = self.frame_stats.frame_millis().into();
|
||||
summary["cpu_ms"] = self.frame_stats.cpu_millis().into();
|
||||
summary["gpu_ms"] = self.frame_stats.gpu_millis().into();
|
||||
}
|
||||
// The guests' observed fuel and wall time (`HORIZON_MOD_FUEL_PROFILE=1`).
|
||||
#[cfg(feature = "mods")]
|
||||
if let Some(profile) = self.mods.mods.fuel_profile() {
|
||||
summary["mod_fuel"] = serde_json::Value::Object(
|
||||
profile
|
||||
.iter()
|
||||
.map(|((id, callback), p)| {
|
||||
(
|
||||
format!("{id}:{callback}"),
|
||||
json!({
|
||||
"calls": p.calls,
|
||||
"max_used": p.max_used,
|
||||
"budget": p.budget,
|
||||
"failures": p.failures,
|
||||
}),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
summary["mod_cost_ms"] = serde_json::Value::Object(
|
||||
self.mods
|
||||
.mods
|
||||
.entries()
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let id = e.manifest.as_ref()?.id.clone();
|
||||
Some((
|
||||
id,
|
||||
json!({
|
||||
"avg_call_ms": e.cost.as_secs_f64() * 1000.0,
|
||||
"status": format!("{:?}", e.status),
|
||||
}),
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if words.get(1) == Some(&"reset") {
|
||||
self.frame_stats.reset();
|
||||
self.reset_mod_model_profile();
|
||||
}
|
||||
Ok(Some(summary))
|
||||
}
|
||||
"model-instancing" => {
|
||||
// AirDef fork (#147): the diagnostic toggle — both paths on one
|
||||
// recording, no restart. The pose history makes the switch seamless.
|
||||
let on = match arg(1)? {
|
||||
"on" => true,
|
||||
"off" => false,
|
||||
other => return Err(format!("model-instancing needs on|off, not {other}").into()),
|
||||
};
|
||||
horizon_client::gfx::set_model_instancing(on);
|
||||
Ok(Some(json!({ "model_instancing": on })))
|
||||
}
|
||||
"bench" => {
|
||||
let seconds: f64 = arg(1)?.parse()?;
|
||||
if self.pending_bench.is_some() {
|
||||
|
||||
@@ -9,6 +9,9 @@ use {
|
||||
horizon_client::{
|
||||
assets::RenderAssets,
|
||||
mesher::{MotionVertex, Vertex},
|
||||
model_instance::{
|
||||
MIN_INSTANCED_MODELS, MODEL_INSTANCE_GLOW, ModelInstance, ModelMeshVertex,
|
||||
},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
},
|
||||
horizon_core::random::RandomSource,
|
||||
@@ -82,6 +85,12 @@ pub(super) struct ModelProfile {
|
||||
pub motion_bytes: u64,
|
||||
pub mesh_builds: u64,
|
||||
pub atlas_scans: u64,
|
||||
/// The instanced group (#147): models drawn from the retained GPU mesh,
|
||||
/// their quads, the instance records' bytes and the GPU mesh uploads.
|
||||
pub instanced_models: u64,
|
||||
pub instanced_quads: u64,
|
||||
pub instance_bytes: u64,
|
||||
pub gpu_mesh_builds: u64,
|
||||
}
|
||||
|
||||
/// The models the running mods keep, by (mod, id).
|
||||
@@ -91,6 +100,12 @@ pub(super) struct ModModels {
|
||||
poses: HashMap<(usize, u32), Pose>,
|
||||
/// Current and previous-frame vertices for the HD motion-only pass.
|
||||
pub(super) motion: Vec<MotionVertex>,
|
||||
/// The instanced group's records for this frame (#147), and the block state
|
||||
/// of its retained GPU mesh; empty/none on the per-vertex fallback path.
|
||||
pub(super) instances: Vec<ModelInstance>,
|
||||
pub(super) instance_state: Option<BlockStateId>,
|
||||
/// The states whose meshes the renderer holds, for this pack generation.
|
||||
gpu_meshes: std::collections::HashSet<BlockStateId>,
|
||||
/// Retained meshes of the models' block states (#126), per pack generation.
|
||||
mesh: MeshCache,
|
||||
/// Counters of the model path since the last `stats reset` / `bench`.
|
||||
@@ -192,6 +207,76 @@ fn emit_mod_mesh(
|
||||
}
|
||||
}
|
||||
|
||||
/// The one mass group to instance (#147): the state with the most drawable
|
||||
/// models, at least `MIN_INSTANCED_MODELS` of them; ties go to the smallest
|
||||
/// state id so the choice does not depend on the poses' hash order.
|
||||
#[cfg(feature = "mods")]
|
||||
fn pick_instance_group(counts: &HashMap<BlockStateId, usize>) -> Option<BlockStateId> {
|
||||
counts
|
||||
.iter()
|
||||
.filter(|(_, n)| **n >= MIN_INSTANCED_MODELS)
|
||||
.max_by_key(|(state, n)| (**n, std::cmp::Reverse(**state)))
|
||||
.map(|(state, _)| *state)
|
||||
}
|
||||
|
||||
/// One instance record (#147): the drawn pose and the last drawn one, both
|
||||
/// camera-relative with the scale in `w`, the packed light, the mod's model id
|
||||
/// and the glow flag. A model that did not move since the last drawn frame
|
||||
/// carries identical poses: the motion pass keeps its zero object velocity.
|
||||
#[cfg(feature = "mods")]
|
||||
fn instance_record(
|
||||
camera: DVec3,
|
||||
rendered: RenderedPose,
|
||||
previous: RenderedPose,
|
||||
light: u32,
|
||||
id: u32,
|
||||
glow: bool,
|
||||
) -> ModelInstance {
|
||||
ModelInstance {
|
||||
pose: [
|
||||
(rendered.at - camera).x as f32,
|
||||
(rendered.at - camera).y as f32,
|
||||
(rendered.at - camera).z as f32,
|
||||
rendered.scale,
|
||||
],
|
||||
rotation: rendered.rotation.to_array(),
|
||||
previous: [
|
||||
(previous.at - camera).x as f32,
|
||||
(previous.at - camera).y as f32,
|
||||
(previous.at - camera).z as f32,
|
||||
previous.scale,
|
||||
],
|
||||
old_rotation: previous.rotation.to_array(),
|
||||
light,
|
||||
id,
|
||||
flags: if glow { MODEL_INSTANCE_GLOW } else { 0 },
|
||||
_pad: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A retained mesh as the GPU keeps it (#147): model-space positions and
|
||||
/// normals, atlas-resolved UVs, the material and emission. The instance
|
||||
/// shader transforms and quantizes these exactly as `emit_mod_mesh` does.
|
||||
#[cfg(feature = "mods")]
|
||||
fn model_mesh_vertices(faces: &[MeshFace]) -> Vec<ModelMeshVertex> {
|
||||
let mut out = Vec::with_capacity(faces.len() * 4);
|
||||
for f in faces {
|
||||
for k in 0..4 {
|
||||
out.push(ModelMeshVertex {
|
||||
pos: f.positions[k],
|
||||
uv: [
|
||||
f.rect[0] + f.uv[k][0] * (f.rect[2] - f.rect[0]),
|
||||
f.rect[1] + f.uv[k][1] * (f.rect[3] - f.rect[1]),
|
||||
],
|
||||
normal: f.normal.to_array(),
|
||||
layer: f.material,
|
||||
emission: f.emission,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A build without the `mods` feature draws no mod models.
|
||||
#[cfg(not(feature = "mods"))]
|
||||
impl Game<'_> {
|
||||
@@ -327,13 +412,23 @@ impl Game<'_> {
|
||||
spots.insert(key, (before, *l));
|
||||
}
|
||||
self.mods.models.spots = spots;
|
||||
let views: Vec<(u64, CameraView)> = self.mods.mods.views().map(|(owner, v)| (owner, *v)).collect();
|
||||
let views: Vec<(u64, CameraView)> = self
|
||||
.mods
|
||||
.mods
|
||||
.views()
|
||||
.map(|(owner, v)| (owner, *v))
|
||||
.collect();
|
||||
let old = std::mem::take(&mut self.mods.models.views);
|
||||
self.mods.models.views = views.into_iter().map(|(owner, v)| {
|
||||
let before = old.iter().find(|(o, _, previous)| *o == owner && previous.id == v.id)
|
||||
.map_or(v, |(_, _, previous)| *previous);
|
||||
(owner, before, v)
|
||||
}).collect();
|
||||
self.mods.models.views = views
|
||||
.into_iter()
|
||||
.map(|(owner, v)| {
|
||||
let before = old
|
||||
.iter()
|
||||
.find(|(o, _, previous)| *o == owner && previous.id == v.id)
|
||||
.map_or(v, |(_, _, previous)| *previous);
|
||||
(owner, before, v)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// The HD lighting a mod asked for, if any.
|
||||
@@ -524,13 +619,22 @@ impl Game<'_> {
|
||||
/// The camera a mod asked the screen's world from (`render.set-main-view`), for this frame.
|
||||
pub(super) fn mod_main_view(&self, alpha: f64) -> Option<horizon_client::gfx::ModView> {
|
||||
let (owner, id) = self.mods.mods.owned_main_view()?;
|
||||
self.mod_views(alpha).into_iter().find(|v| v.owner == owner && v.id == id)
|
||||
self.mod_views(alpha)
|
||||
.into_iter()
|
||||
.find(|v| v.owner == owner && v.id == id)
|
||||
}
|
||||
|
||||
/// Drop the retained model meshes: a resource reload or a world unload
|
||||
/// invalidates them (the pack generation guard also catches a reload).
|
||||
/// The GPU meshes and the frame's instance records go with them (#147).
|
||||
pub(super) fn forget_mod_meshes(&mut self) {
|
||||
self.mods.models.mesh = MeshCache::default();
|
||||
self.mods.models.gpu_meshes.clear();
|
||||
self.mods.models.instances.clear();
|
||||
self.mods.models.instance_state = None;
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
renderer.forget_model_meshes();
|
||||
}
|
||||
}
|
||||
|
||||
/// The model path's counters for the `stats` control command (#126).
|
||||
@@ -545,6 +649,10 @@ impl Game<'_> {
|
||||
"motion_bytes": p.motion_bytes,
|
||||
"mesh_builds": p.mesh_builds,
|
||||
"atlas_scans": p.atlas_scans,
|
||||
"instanced_models": p.instanced_models,
|
||||
"instanced_quads": p.instanced_quads,
|
||||
"instance_bytes": p.instance_bytes,
|
||||
"gpu_mesh_builds": p.gpu_mesh_builds,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -578,6 +686,11 @@ impl Game<'_> {
|
||||
mesh.special = special;
|
||||
mesh.pack = Some(generation.clone());
|
||||
self.mods.models.profile.atlas_scans += 1;
|
||||
// The GPU meshes pointed into the old generation's atlas (#147).
|
||||
self.mods.models.gpu_meshes.clear();
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
renderer.forget_model_meshes();
|
||||
}
|
||||
}
|
||||
|
||||
/// Bake one state's faces against the atlas once (#126): sprite rectangles,
|
||||
@@ -634,9 +747,16 @@ impl Game<'_> {
|
||||
/// Draws every mod model between its last two poses, lit by the world
|
||||
/// (or at full brightness), its faces shaded by its own rotation. The
|
||||
/// faces come from the retained meshes (#126): a frame transforms them,
|
||||
/// it does not bake the models again.
|
||||
/// it does not bake the models again. The one mass group of identical
|
||||
/// models (#147) is GPU-instanced instead: its mesh is retained on the
|
||||
/// GPU per pack generation and the frame only writes instance records
|
||||
/// (current/previous pose, id, light) that the main, motion and shadow
|
||||
/// passes share. Every other model stays on the per-vertex path, as does
|
||||
/// the whole frame when instancing is off or a shader pack draws entities.
|
||||
pub(super) fn mod_model_geometry(&mut self, camera: DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
self.mods.models.motion.clear();
|
||||
self.mods.models.instances.clear();
|
||||
self.mods.models.instance_state = None;
|
||||
if self.mods.models.poses.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -662,9 +782,17 @@ impl Game<'_> {
|
||||
for (_, p) in &poses {
|
||||
self.build_mod_mesh(p.state);
|
||||
}
|
||||
let meshes = &self.mods.models.mesh.meshes;
|
||||
let profile = &mut self.mods.models.profile;
|
||||
profile.frames += 1;
|
||||
// Per model, not per vertex: cull, shrink the far impostors, interpolate
|
||||
// the pose and read the light. The emit below only transforms the faces.
|
||||
let mut prepared: Vec<(
|
||||
(usize, u32),
|
||||
BlockStateId,
|
||||
bool,
|
||||
u32,
|
||||
RenderedPose,
|
||||
RenderedPose,
|
||||
)> = Vec::with_capacity(poses.len());
|
||||
let mut counts: HashMap<BlockStateId, usize> = HashMap::new();
|
||||
for (key, p) in poses {
|
||||
let mut at = p.previous.lerp(p.position, t);
|
||||
let d = at.distance(camera);
|
||||
@@ -699,47 +827,93 @@ impl Game<'_> {
|
||||
);
|
||||
(u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8)
|
||||
};
|
||||
// The model's unit cube turned and scaled about its centre.
|
||||
let m = Mat4::from_scale_rotation_translation(
|
||||
Vec3::splat(scale),
|
||||
rotation,
|
||||
(at - camera).as_vec3(),
|
||||
) * Mat4::from_translation(Vec3::splat(-0.5));
|
||||
let faces = &meshes[&p.state];
|
||||
let start = out.len();
|
||||
// One normal matrix per instance, not per face: the inverse transpose
|
||||
// `transform_normal` builds is the same for every face of the model.
|
||||
let nm = Mat3::from_mat4(m).inverse().transpose();
|
||||
emit_mod_mesh(faces, m, nm, light, p.glow, out);
|
||||
profile.models += 1;
|
||||
profile.quads += faces.len() as u64;
|
||||
profile.vertex_bytes += ((out.len() - start) * std::mem::size_of::<Vertex>()) as u64;
|
||||
if motion {
|
||||
let previous_matrix = Mat4::from_scale_rotation_translation(
|
||||
Vec3::splat(previous.scale),
|
||||
previous.rotation,
|
||||
(previous.at - camera).as_vec3(),
|
||||
) * Mat4::from_translation(Vec3::splat(-0.5));
|
||||
// The motion pass only needs where each vertex was: transform the
|
||||
// retained faces again, no second model bake (#124's motion kept).
|
||||
let motion_start = self.mods.models.motion.len();
|
||||
for (face, quad) in faces.iter().zip(out[start..].chunks(4)) {
|
||||
for k in 0..4 {
|
||||
self.mods.models.motion.push(MotionVertex::new(
|
||||
quad[k],
|
||||
previous_matrix
|
||||
.transform_point3(Vec3::from_array(face.positions[k]))
|
||||
.to_array(),
|
||||
));
|
||||
}
|
||||
*counts.entry(p.state).or_default() += 1;
|
||||
prepared.push((key, p.state, p.glow, light, rendered, previous));
|
||||
}
|
||||
// The mass group: the most models of one state, enough of them to be
|
||||
// worth instancing. A shader pack's entity programs would not see the
|
||||
// instanced draws, so the frame stays on the per-vertex path then.
|
||||
let mut group = (horizon_client::gfx::model_instancing_enabled()
|
||||
&& self.renderer.is_some()
|
||||
&& !self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.pack_has_entities()))
|
||||
.then(|| pick_instance_group(&counts))
|
||||
.flatten();
|
||||
if let Some(state) = group {
|
||||
if !self.mods.models.gpu_meshes.contains(&state) {
|
||||
let vertices = model_mesh_vertices(&self.mods.models.mesh.meshes[&state]);
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
renderer.upload_model_mesh(state.0, &vertices);
|
||||
self.mods.models.gpu_meshes.insert(state);
|
||||
self.mods.models.profile.gpu_mesh_builds += 1;
|
||||
}
|
||||
}
|
||||
if !self.mods.models.gpu_meshes.contains(&state) {
|
||||
group = None;
|
||||
}
|
||||
}
|
||||
let meshes = &self.mods.models.mesh.meshes;
|
||||
let profile = &mut self.mods.models.profile;
|
||||
profile.frames += 1;
|
||||
for (key, state, glow, light, rendered, previous) in prepared {
|
||||
let faces = &meshes[&state];
|
||||
if group == Some(state) {
|
||||
// One record where the per-vertex path writes the whole mesh:
|
||||
// the shader applies the same transform, light and materials.
|
||||
self.mods.models.instances.push(instance_record(
|
||||
camera, rendered, previous, light, key.1, glow,
|
||||
));
|
||||
profile.models += 1;
|
||||
profile.quads += faces.len() as u64;
|
||||
profile.instanced_models += 1;
|
||||
profile.instanced_quads += faces.len() as u64;
|
||||
profile.instance_bytes += std::mem::size_of::<ModelInstance>() as u64;
|
||||
} else {
|
||||
// The model's unit cube turned and scaled about its centre.
|
||||
let m = Mat4::from_scale_rotation_translation(
|
||||
Vec3::splat(rendered.scale),
|
||||
rendered.rotation,
|
||||
(rendered.at - camera).as_vec3(),
|
||||
) * Mat4::from_translation(Vec3::splat(-0.5));
|
||||
let start = out.len();
|
||||
// One normal matrix per instance, not per face: the inverse transpose
|
||||
// `transform_normal` builds is the same for every face of the model.
|
||||
let nm = Mat3::from_mat4(m).inverse().transpose();
|
||||
emit_mod_mesh(faces, m, nm, light, glow, out);
|
||||
profile.models += 1;
|
||||
profile.quads += faces.len() as u64;
|
||||
profile.vertex_bytes +=
|
||||
((out.len() - start) * std::mem::size_of::<Vertex>()) as u64;
|
||||
if motion {
|
||||
let previous_matrix = Mat4::from_scale_rotation_translation(
|
||||
Vec3::splat(previous.scale),
|
||||
previous.rotation,
|
||||
(previous.at - camera).as_vec3(),
|
||||
) * Mat4::from_translation(Vec3::splat(-0.5));
|
||||
// The motion pass only needs where each vertex was: transform the
|
||||
// retained faces again, no second model bake (#124's motion kept).
|
||||
let motion_start = self.mods.models.motion.len();
|
||||
for (face, quad) in faces.iter().zip(out[start..].chunks(4)) {
|
||||
for k in 0..4 {
|
||||
self.mods.models.motion.push(MotionVertex::new(
|
||||
quad[k],
|
||||
previous_matrix
|
||||
.transform_point3(Vec3::from_array(face.positions[k]))
|
||||
.to_array(),
|
||||
));
|
||||
}
|
||||
}
|
||||
profile.motion_quads += faces.len() as u64;
|
||||
profile.motion_bytes += ((self.mods.models.motion.len() - motion_start)
|
||||
* std::mem::size_of::<MotionVertex>())
|
||||
as u64;
|
||||
}
|
||||
profile.motion_quads += faces.len() as u64;
|
||||
profile.motion_bytes += ((self.mods.models.motion.len() - motion_start)
|
||||
* std::mem::size_of::<MotionVertex>())
|
||||
as u64;
|
||||
}
|
||||
self.mods.models.poses.get_mut(&key).unwrap().rendered = Some(rendered);
|
||||
}
|
||||
self.mods.models.instance_state = group.filter(|_| !self.mods.models.instances.is_empty());
|
||||
}
|
||||
|
||||
/// Before each frame: the renderer gets the mod's post pass when it changed, and its
|
||||
@@ -1037,4 +1211,206 @@ mod tests {
|
||||
assert_eq!(quad_material(0.15, 0.1, &special), MODEL_PAINTED);
|
||||
assert_eq!(quad_material(0.15, 0.2, &special), MODEL_PAINTED);
|
||||
}
|
||||
|
||||
/// The mass group (#147): the most models of one state, ties to the smallest
|
||||
/// state id (the poses' hash order must not decide), and nothing below the
|
||||
/// instancing minimum — the frame stays on the per-vertex fallback then.
|
||||
#[test]
|
||||
fn instance_group_picks_the_most_models_deterministically() {
|
||||
let (a, b, c) = (BlockStateId(7), BlockStateId(3), BlockStateId(9));
|
||||
let mut counts = HashMap::new();
|
||||
counts.insert(a, 40);
|
||||
counts.insert(b, 40);
|
||||
counts.insert(c, 3);
|
||||
assert_eq!(pick_instance_group(&counts), Some(b));
|
||||
counts.insert(c, 41);
|
||||
assert_eq!(pick_instance_group(&counts), Some(c));
|
||||
let small: HashMap<_, _> = [(a, MIN_INSTANCED_MODELS - 1)].into_iter().collect();
|
||||
assert_eq!(pick_instance_group(&small), None);
|
||||
let exact: HashMap<_, _> = [(a, MIN_INSTANCED_MODELS)].into_iter().collect();
|
||||
assert_eq!(pick_instance_group(&exact), Some(a));
|
||||
assert_eq!(pick_instance_group(&HashMap::new()), None);
|
||||
}
|
||||
|
||||
/// The GPU mesh keeps the faces the CPU bake transforms: model-space
|
||||
/// positions and normals, the same atlas-resolved UVs, material, emission.
|
||||
#[test]
|
||||
fn gpu_mesh_vertices_match_the_retained_faces() {
|
||||
let faces = vec![
|
||||
MeshFace {
|
||||
positions: [
|
||||
[0.0, 0.0, 0.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[1.0, 1.0, 0.0],
|
||||
[0.0, 1.0, 0.0],
|
||||
],
|
||||
uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]],
|
||||
rect: [0.10, 0.20, 0.30, 0.60],
|
||||
normal: Vec3::Y,
|
||||
emission: 112,
|
||||
material: MODEL_BARE_METAL,
|
||||
},
|
||||
MeshFace {
|
||||
positions: [[0.25, 0.5, 0.75]; 4],
|
||||
uv: [[0.25, 0.75]; 4],
|
||||
rect: [0.50, 0.10, 0.60, 0.20],
|
||||
normal: Vec3::ZERO,
|
||||
emission: 0,
|
||||
material: MODEL_GLOW,
|
||||
},
|
||||
];
|
||||
let mesh = model_mesh_vertices(&faces);
|
||||
assert_eq!(mesh.len(), faces.len() * 4);
|
||||
// The identity transform: the CPU bake writes the model space itself.
|
||||
let mut baked = Vec::new();
|
||||
emit_mod_mesh(
|
||||
&faces,
|
||||
Mat4::IDENTITY,
|
||||
Mat3::IDENTITY,
|
||||
0x8050,
|
||||
false,
|
||||
&mut baked,
|
||||
);
|
||||
for (i, v) in mesh.iter().enumerate() {
|
||||
let f = &faces[i / 4];
|
||||
let k = i % 4;
|
||||
assert_eq!(v.pos, f.positions[k]);
|
||||
assert_eq!(v.normal, f.normal.to_array());
|
||||
assert_eq!(v.layer, f.material);
|
||||
assert_eq!(v.emission, f.emission);
|
||||
assert_eq!(v.uv, baked[i].uv);
|
||||
assert_eq!(v.pos, baked[i].pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance shader's transform (entity.wgsl's quat_rotate about the
|
||||
/// centre) matches the CPU matrix the fallback bakes with, and its normal
|
||||
/// quantization matches `emit_mod_mesh`'s to the last bit or one ulp of the
|
||||
/// i8 packing (f32 rounding order differs between CPU and GPU).
|
||||
#[test]
|
||||
fn instanced_shader_math_matches_the_cpu_bake() {
|
||||
// entity.wgsl: v + 2 * cross(q.xyz, cross(q.xyz, v) + q.w * v).
|
||||
fn quat_rotate(q: Quat, v: Vec3) -> Vec3 {
|
||||
let xyz = Vec3::new(q.x, q.y, q.z);
|
||||
v + 2.0 * xyz.cross(xyz.cross(v) + q.w * v)
|
||||
}
|
||||
fn shader_pos(p: Vec3, pose: [f32; 4], q: Quat) -> Vec3 {
|
||||
quat_rotate(q, (p - Vec3::splat(0.5)) * pose[3]) + Vec3::new(pose[0], pose[1], pose[2])
|
||||
}
|
||||
let cube = [
|
||||
[0.0, 0.0, 0.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[1.0, 1.0, 0.0],
|
||||
[0.0, 1.0, 0.0],
|
||||
];
|
||||
let faces = vec![MeshFace {
|
||||
positions: cube,
|
||||
uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]],
|
||||
rect: [0.10, 0.10, 0.20, 0.20],
|
||||
normal: Vec3::new(0.0, 1.0, 0.0),
|
||||
emission: 0,
|
||||
material: MODEL_PAINTED,
|
||||
}];
|
||||
let turns = [
|
||||
Quat::IDENTITY,
|
||||
Quat::from_rotation_y(0.7),
|
||||
Quat::from_xyzw(0.2, 0.4, 0.1, 0.9).normalize(),
|
||||
Quat::from_rotation_x(1.3) * Quat::from_rotation_z(-0.4),
|
||||
];
|
||||
let camera = DVec3::new(1200.25, 70.5, -3400.75);
|
||||
let mut worst_pos = 0.0f32;
|
||||
let mut normal_diffs = 0;
|
||||
let mut normals = 0;
|
||||
for scale in [1.0f32, 0.35, 4.0] {
|
||||
for rotation in turns {
|
||||
for at in [camera, camera + DVec3::new(120.5, -30.25, 77.75)] {
|
||||
let m = Mat4::from_scale_rotation_translation(
|
||||
Vec3::splat(scale),
|
||||
rotation,
|
||||
(at - camera).as_vec3(),
|
||||
) * Mat4::from_translation(Vec3::splat(-0.5));
|
||||
let nm = Mat3::from_mat4(m).inverse().transpose();
|
||||
let pose = [
|
||||
(at - camera).x as f32,
|
||||
(at - camera).y as f32,
|
||||
(at - camera).z as f32,
|
||||
scale,
|
||||
];
|
||||
let mut baked = Vec::new();
|
||||
emit_mod_mesh(&faces, m, nm, 0, false, &mut baked);
|
||||
for (k, v) in baked.iter().enumerate() {
|
||||
let got = shader_pos(Vec3::from_array(cube[k]), pose, rotation);
|
||||
let want = Vec3::from_array(v.pos);
|
||||
worst_pos = worst_pos.max((got - want).length() / want.length().max(1.0));
|
||||
// The shader's normal: rotate, normalize, truncate *127.
|
||||
let n = quat_rotate(rotation, faces[0].normal);
|
||||
let n = if n.length() > 1e-8 {
|
||||
n.normalize()
|
||||
} else {
|
||||
Vec3::ZERO
|
||||
};
|
||||
let q = n.clamp(Vec3::splat(-1.0), Vec3::splat(1.0)) * 127.0;
|
||||
let q = [q.x as i8, q.y as i8, q.z as i8];
|
||||
for c in 0..3 {
|
||||
normals += 1;
|
||||
normal_diffs += (q[c] != v.normal[c]) as u32;
|
||||
assert!((q[c] as i16 - v.normal[c] as i16).abs() <= 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// f32 rounding only: far below a pixel at any model size.
|
||||
assert!(
|
||||
worst_pos < 1e-5,
|
||||
"worst relative position error {worst_pos}"
|
||||
);
|
||||
// The truncation boundary may flip one step on rare rounding ties.
|
||||
assert!(
|
||||
normal_diffs * 100 <= normals,
|
||||
"{normal_diffs}/{normals} normals differ"
|
||||
);
|
||||
}
|
||||
|
||||
/// A model that did not move keeps identical current/previous poses: the
|
||||
/// motion pass's previous position equals the current one and its object
|
||||
/// velocity stays zero (#143's static contract, on the instanced path too).
|
||||
#[test]
|
||||
fn static_instance_keeps_zero_object_velocity() {
|
||||
let camera = DVec3::new(10.0, 70.0, -20.0);
|
||||
let rendered = RenderedPose {
|
||||
at: camera + DVec3::new(5.5, 2.25, 9.0),
|
||||
rotation: Quat::from_rotation_y(0.9),
|
||||
scale: 2.0,
|
||||
};
|
||||
let record = instance_record(camera, rendered, rendered, 0x8050, 77, false);
|
||||
assert_eq!(record.pose, record.previous);
|
||||
assert_eq!(record.rotation, record.old_rotation);
|
||||
assert_eq!(record.light, 0x8050);
|
||||
assert_eq!(record.id, 77);
|
||||
assert_eq!(record.flags, 0);
|
||||
// The shader's two transforms of the same vertex agree bit for bit.
|
||||
fn quat_rotate(q: Quat, v: Vec3) -> Vec3 {
|
||||
let xyz = Vec3::new(q.x, q.y, q.z);
|
||||
v + 2.0 * xyz.cross(xyz.cross(v) + q.w * v)
|
||||
}
|
||||
let q = Quat::from_array(record.rotation);
|
||||
let p = Vec3::new(0.25, 0.75, 0.5);
|
||||
let now = quat_rotate(q, (p - Vec3::splat(0.5)) * record.pose[3])
|
||||
+ Vec3::new(record.pose[0], record.pose[1], record.pose[2]);
|
||||
let was = quat_rotate(
|
||||
Quat::from_array(record.old_rotation),
|
||||
(p - Vec3::splat(0.5)) * record.previous[3],
|
||||
) + Vec3::new(record.previous[0], record.previous[1], record.previous[2]);
|
||||
assert_eq!(now, was);
|
||||
// A moved model carries its last drawn pose, not the current one.
|
||||
let before = RenderedPose {
|
||||
at: rendered.at - DVec3::new(2.0, 0.0, 0.0),
|
||||
..rendered
|
||||
};
|
||||
let moved = instance_record(camera, rendered, before, 0, 78, true);
|
||||
assert_ne!(moved.pose, moved.previous);
|
||||
assert_eq!(moved.previous[0], record.pose[0] - 2.0);
|
||||
assert_eq!(moved.flags, MODEL_INSTANCE_GLOW);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,13 @@ use {
|
||||
winit::{event::MouseButton, keyboard::KeyCode},
|
||||
};
|
||||
|
||||
/// Guest fuel profiling for the bench driver (#147): `HORIZON_MOD_FUEL_PROFILE=1`.
|
||||
#[cfg(feature = "mods")]
|
||||
fn mod_fuel_profile_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("HORIZON_MOD_FUEL_PROFILE").map_or(false, |v| v == "1"))
|
||||
}
|
||||
|
||||
/// Chunks mods may have loaded at once, and how long one is held after its last request (20 s).
|
||||
#[cfg(feature = "mods")]
|
||||
const CHUNK_TICKETS: usize = 64;
|
||||
@@ -734,6 +741,11 @@ impl Game<'_> {
|
||||
self.sync_mod_sources();
|
||||
return;
|
||||
}
|
||||
// AirDef fork (#147): the bench driver observes the guests' fuel per
|
||||
// callback (`stats` reports it); off unless asked for.
|
||||
if mod_fuel_profile_enabled() && self.mods.mods.fuel_profile().is_none() {
|
||||
self.mods.mods.enable_fuel_profile();
|
||||
}
|
||||
self.tick_mod_use();
|
||||
self.take_mod_chunk_requests();
|
||||
for (i, columns) in self.mods.mods.take_ground_queries() {
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{
|
||||
graphics::GraphicsApi,
|
||||
hud::{HudBatch, HudRenderer},
|
||||
mesher::{MotionVertex, SectionMesh, Sides, TerrainVertex, Vertex},
|
||||
model_instance::{ModelInstance, ModelMeshVertex},
|
||||
sprites::SpriteAnimation,
|
||||
};
|
||||
use glam::{DVec3, Mat4, Vec3, Vec4};
|
||||
@@ -27,11 +28,45 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState {
|
||||
const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] =
|
||||
wgpu::vertex_attr_array![0=>Float32x3,1=>Uint16x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4];
|
||||
|
||||
/// AirDef fork (#147): the instanced mod models' mesh vertex (slot 0) and
|
||||
/// instance record (slot 1), for entity.wgsl's `vs_model_instance`.
|
||||
const MODEL_MESH_ATTRIBUTES: [wgpu::VertexAttribute; 5] =
|
||||
wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Float32x3,3=>Uint32,4=>Uint32];
|
||||
const MODEL_INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 7] = wgpu::vertex_attr_array![5=>Float32x4,6=>Float32x4,7=>Float32x4,8=>Float32x4,9=>Uint32,10=>Uint32,11=>Uint32];
|
||||
|
||||
/// entity.wgsl after the OverlayTexture constants it reads.
|
||||
fn entity_shader() -> String {
|
||||
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
|
||||
}
|
||||
|
||||
/// AirDef fork (#147): the mod models' mass group is GPU-instanced unless
|
||||
/// `HORIZON_MODEL_INSTANCING=0` (diagnostics only; the fallback is the
|
||||
/// per-vertex bake, vertex-identical to the pre-instancing path). The bench
|
||||
/// driver flips it at runtime (`model-instancing` control command) to compare
|
||||
/// both paths on one recording; the pose history both paths keep makes the
|
||||
/// switch seamless for motion.
|
||||
static MODEL_INSTANCING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
|
||||
|
||||
/// Read `HORIZON_MODEL_INSTANCING` once, at renderer startup.
|
||||
pub fn init_model_instancing() {
|
||||
static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
|
||||
INIT.get_or_init(|| {
|
||||
MODEL_INSTANCING.store(
|
||||
std::env::var("HORIZON_MODEL_INSTANCING").map_or(true, |v| v != "0"),
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn model_instancing_enabled() -> bool {
|
||||
MODEL_INSTANCING.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The diagnostic runtime toggle (#147): off is the per-vertex fallback.
|
||||
pub fn set_model_instancing(on: bool) {
|
||||
MODEL_INSTANCING.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod crumbling_tests;
|
||||
mod entity_batch;
|
||||
@@ -336,6 +371,11 @@ pub struct Frame<'a> {
|
||||
pub entities: &'a [Vertex],
|
||||
/// Mod models with their previous drawn transforms, for the HD motion-only pass.
|
||||
pub motion_models: &'a [MotionVertex],
|
||||
/// The instanced mod-model group (#147): one record per model, drawn from the
|
||||
/// retained GPU mesh of `model_instance_state` in the main, motion and shadow
|
||||
/// passes. Empty when the frame stays on the per-vertex fallback path.
|
||||
pub model_instances: &'a [ModelInstance],
|
||||
pub model_instance_state: Option<u32>,
|
||||
/// The glowing entities' silhouettes in their team colours (`OutlineBufferSource`),
|
||||
/// outlined through walls after the hand.
|
||||
pub glowing: &'a [Vertex],
|
||||
@@ -633,6 +673,16 @@ pub struct Renderer {
|
||||
gbuffer_motion_models: wgpu::RenderPipeline,
|
||||
motion_models_buffer: wgpu::Buffer,
|
||||
motion_models_capacity: u64,
|
||||
/// The instanced mod-model group (#147): retained meshes by block state for
|
||||
/// the pack generation the game last uploaded, the frame's instance records,
|
||||
/// and the pipelines that draw them in the main, motion and shadow passes.
|
||||
model_meshes: HashMap<u32, (wgpu::Buffer, u32)>,
|
||||
model_instance_buffer: wgpu::Buffer,
|
||||
model_instance_capacity: u64,
|
||||
gbuffer_model_instance: wgpu::RenderPipeline,
|
||||
motion_model_instance: wgpu::RenderPipeline,
|
||||
shadow_model_instance: wgpu::RenderPipeline,
|
||||
entity_model_instance: wgpu::RenderPipeline,
|
||||
/// The HD sun shadows: depth only, from the light, and the sections in its farther cascade.
|
||||
shadow_terrain: wgpu::RenderPipeline,
|
||||
/// The near cascade's depth without leaves, and its colour map's leaves and glass
|
||||
@@ -1199,6 +1249,7 @@ impl Renderer {
|
||||
water_layers: [u32; 2],
|
||||
hd_materials: hd::MaterialTable,
|
||||
) -> Result<Self> {
|
||||
init_model_instancing();
|
||||
let split = sprite_split();
|
||||
if layers > split * SPRITE_ARRAYS {
|
||||
return Err(format!(
|
||||
@@ -2340,37 +2391,129 @@ impl Renderer {
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let gbuffer_motion_models = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("HD motion models"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some("vs_entity_motion"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &motion_vertex,
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
let gbuffer_motion_models =
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("HD motion models"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some("vs_entity_motion"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &motion_vertex,
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::Equal),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some("fs_entity_motion"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: hd::MOTION,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
// AirDef fork (#147): the instanced mod-model group. Slot 0 is the retained
|
||||
// mesh of the group's block state; slot 1 steps per model record. The same
|
||||
// two buffers feed the main, motion and shadow passes.
|
||||
let model_buffers = [
|
||||
Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<ModelMeshVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &MODEL_MESH_ATTRIBUTES,
|
||||
}),
|
||||
Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<ModelInstance>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &MODEL_INSTANCE_ATTRIBUTES,
|
||||
}),
|
||||
];
|
||||
let model_instance_pipeline =
|
||||
|label: &str,
|
||||
entry: &str,
|
||||
fragment: &str,
|
||||
depth: Option<wgpu::DepthStencilState>,
|
||||
targets: &[Option<wgpu::ColorTargetState>]| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &model_buffers,
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: depth,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some(fragment),
|
||||
compilation_options: Default::default(),
|
||||
targets,
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let gbuffer_model_instance = model_instance_pipeline(
|
||||
"HD G-buffer instanced models",
|
||||
"vs_model_instance",
|
||||
"fs_entity_gbuffer",
|
||||
gbuffer_depth.clone(),
|
||||
&gbuffer_targets,
|
||||
);
|
||||
let motion_model_instance = model_instance_pipeline(
|
||||
"HD motion instanced models",
|
||||
"vs_model_instance_motion",
|
||||
"fs_entity_motion",
|
||||
Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::Equal),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some("fs_entity_motion"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: hd::MOTION,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: hd::MOTION,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
);
|
||||
let shadow_model_instance = model_instance_pipeline(
|
||||
"HD shadows instanced models",
|
||||
"vs_model_instance",
|
||||
"fs_entity_sun_shadow",
|
||||
shadow_depth.clone(),
|
||||
&[],
|
||||
);
|
||||
let entity_model_instance = model_instance_pipeline(
|
||||
"Instanced models",
|
||||
"vs_model_instance",
|
||||
"fs_entity",
|
||||
Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
blend: Some(alpha_blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
);
|
||||
let shadow_entity = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("HD shadows entities"),
|
||||
layout: Some(&entity_layout),
|
||||
@@ -2896,6 +3039,13 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let model_instance_capacity = 1 << 8;
|
||||
let model_instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Model instance records"),
|
||||
size: model_instance_capacity * std::mem::size_of::<ModelInstance>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let flat_wanted = flat::wanted(&adapter, &device);
|
||||
// Readable as storage where flat draws run: a shader pack's terrain program reads them.
|
||||
let arena = arena::Arena::new(
|
||||
@@ -3147,6 +3297,13 @@ impl Renderer {
|
||||
gbuffer_motion_models,
|
||||
motion_models_buffer,
|
||||
motion_models_capacity,
|
||||
model_meshes: HashMap::new(),
|
||||
model_instance_buffer,
|
||||
model_instance_capacity,
|
||||
gbuffer_model_instance,
|
||||
motion_model_instance,
|
||||
shadow_model_instance,
|
||||
entity_model_instance,
|
||||
shadow_terrain,
|
||||
shadow_terrain_near,
|
||||
shadow_tint_leaves,
|
||||
@@ -3405,6 +3562,64 @@ impl Renderer {
|
||||
((c.entities && !c.only_player) || c.blocks, c.entities)
|
||||
}
|
||||
|
||||
/// A shader pack draws the entity spans itself: the instanced mod-model
|
||||
/// group would bypass its programs, so the game keeps those models on the
|
||||
/// per-vertex path while it does.
|
||||
pub fn pack_has_entities(&self) -> bool {
|
||||
self.pack_post
|
||||
.as_ref()
|
||||
.is_some_and(|(_, post)| post.as_ref().is_some_and(|p| p.has_entities()))
|
||||
}
|
||||
|
||||
/// Retain one block state's model mesh on the GPU (#147), for the pack
|
||||
/// generation the game resolved it against. One upload per state per
|
||||
/// generation; frames only write instance records afterwards.
|
||||
pub fn upload_model_mesh(&mut self, state: u32, vertices: &[ModelMeshVertex]) {
|
||||
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Instanced model mesh"),
|
||||
size: std::mem::size_of_val(vertices) as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
self.queue
|
||||
.write_buffer(&buffer, 0, bytemuck::cast_slice(vertices));
|
||||
self.model_meshes
|
||||
.insert(state, (buffer, vertices.len() as u32 / 4));
|
||||
}
|
||||
|
||||
/// Drop the retained model meshes: a resource reload or a world unload
|
||||
/// invalidates them, as the game's own mesh cache (`forget_mod_meshes`).
|
||||
pub fn forget_model_meshes(&mut self) {
|
||||
self.model_meshes.clear();
|
||||
}
|
||||
|
||||
/// Draw the frame's instanced mod-model group from its retained mesh, in
|
||||
/// whichever pass draws the entities: main, motion, shadows, mod cameras.
|
||||
/// The parts come separately so the HD state's mutable borrow stays live.
|
||||
fn draw_model_instances(
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
pipeline: &wgpu::RenderPipeline,
|
||||
entity_group: &wgpu::BindGroup,
|
||||
indices: &wgpu::Buffer,
|
||||
meshes: &HashMap<u32, (wgpu::Buffer, u32)>,
|
||||
instance_buffer: &wgpu::Buffer,
|
||||
frame: &Frame,
|
||||
) {
|
||||
let Some(state) = frame.model_instance_state else {
|
||||
return;
|
||||
};
|
||||
let instances = frame.model_instances.len() as u32;
|
||||
let Some((mesh, quads)) = meshes.get(&state).filter(|_| instances > 0) else {
|
||||
return;
|
||||
};
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, entity_group, &[]);
|
||||
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, mesh.slice(..));
|
||||
pass.set_vertex_buffer(1, instance_buffer.slice(..));
|
||||
pass.draw_indexed(0..quads * 6, 0, 0..instances);
|
||||
}
|
||||
|
||||
pub fn has_section(&self, key: SectionKey) -> bool {
|
||||
self.sections.contains(key)
|
||||
}
|
||||
@@ -3671,6 +3886,16 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
}
|
||||
// The instanced group is in this picture too, wherever its models are (#147).
|
||||
Self::draw_model_instances(
|
||||
&mut pass,
|
||||
&self.entity_model_instance,
|
||||
&self.entity_group,
|
||||
&self.indices,
|
||||
&self.model_meshes,
|
||||
&self.model_instance_buffer,
|
||||
frame,
|
||||
);
|
||||
drop(pass);
|
||||
// The mod's post pass with this camera: its blasts, flashes and glows in the picture,
|
||||
// as much as the picture's size is worth. The picture's own camera and world are
|
||||
@@ -5288,6 +5513,26 @@ impl Renderer {
|
||||
bytemuck::cast_slice(frame.motion_models),
|
||||
);
|
||||
}
|
||||
// The instanced group's records (#147): one pose pair, id and light per
|
||||
// model, where the per-vertex path would upload the whole mesh again.
|
||||
let model_instances = frame.model_instances.len() as u64;
|
||||
if model_instances > self.model_instance_capacity {
|
||||
self.model_instance_capacity = model_instances.next_power_of_two();
|
||||
self.model_instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Model instance records"),
|
||||
size: self.model_instance_capacity * std::mem::size_of::<ModelInstance>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
}
|
||||
if model_instances > 0 {
|
||||
self.uploads.buffer(
|
||||
&mut encoder,
|
||||
&self.model_instance_buffer,
|
||||
0,
|
||||
bytemuck::cast_slice(frame.model_instances),
|
||||
);
|
||||
}
|
||||
self.entity_outline.prepare(
|
||||
&self.device,
|
||||
&mut self.uploads,
|
||||
@@ -5685,6 +5930,17 @@ impl Renderer {
|
||||
pass.draw_indexed(first * 6..end * 6, 0, 0..1);
|
||||
}
|
||||
}
|
||||
// Models behind the main camera still cast here; the glowing
|
||||
// faces the CPU runs skip are discarded by fs_entity_sun_shadow.
|
||||
Self::draw_model_instances(
|
||||
&mut pass,
|
||||
&self.shadow_model_instance,
|
||||
&self.entity_group,
|
||||
&self.indices,
|
||||
&self.model_meshes,
|
||||
&self.model_instance_buffer,
|
||||
frame,
|
||||
);
|
||||
drop(pass);
|
||||
if tinted {
|
||||
// What leaves and glass do to the sunlight in the near box: colours
|
||||
@@ -5775,14 +6031,35 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
}
|
||||
Self::draw_model_instances(
|
||||
&mut pass,
|
||||
&self.gbuffer_model_instance,
|
||||
&self.entity_group,
|
||||
&self.indices,
|
||||
&self.model_meshes,
|
||||
&self.model_instance_buffer,
|
||||
frame,
|
||||
);
|
||||
drop(pass);
|
||||
if motion_vertices > 0 {
|
||||
if motion_vertices > 0 || !frame.model_instances.is_empty() {
|
||||
let mut pass = hd.motion_models_pass(&mut encoder);
|
||||
pass.set_pipeline(&self.gbuffer_motion_models);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.motion_models_buffer.slice(..));
|
||||
pass.draw_indexed(0..motion_vertices as u32 / 4 * 6, 0, 0..1);
|
||||
if motion_vertices > 0 {
|
||||
pass.set_pipeline(&self.gbuffer_motion_models);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.motion_models_buffer.slice(..));
|
||||
pass.draw_indexed(0..motion_vertices as u32 / 4 * 6, 0, 0..1);
|
||||
}
|
||||
// The same instance stream as the main pass: its depth matches (#147).
|
||||
Self::draw_model_instances(
|
||||
&mut pass,
|
||||
&self.motion_model_instance,
|
||||
&self.entity_group,
|
||||
&self.indices,
|
||||
&self.model_meshes,
|
||||
&self.model_instance_buffer,
|
||||
frame,
|
||||
);
|
||||
}
|
||||
// Contact shadows from the G-buffer's depth and normals, for the lighting.
|
||||
hd.ao(&mut encoder);
|
||||
@@ -6050,6 +6327,17 @@ impl Renderer {
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
}
|
||||
Self::draw_model_instances(
|
||||
&mut pass,
|
||||
&self.entity_model_instance,
|
||||
&self.entity_group,
|
||||
&self.indices,
|
||||
&self.model_meshes,
|
||||
&self.model_instance_buffer,
|
||||
frame,
|
||||
);
|
||||
if entity_quads > 0 {
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if translucent_item_quads > 0 {
|
||||
@@ -7161,6 +7449,37 @@ mod tests {
|
||||
assert_eq!(std::mem::size_of::<TerrainVertex>(), 24);
|
||||
}
|
||||
#[test]
|
||||
fn model_instance_attributes_follow_their_structs() {
|
||||
use super::{ModelInstance, ModelMeshVertex};
|
||||
use std::mem::offset_of;
|
||||
let mesh = super::MODEL_MESH_ATTRIBUTES.map(|a| (a.shader_location, a.offset as usize));
|
||||
assert_eq!(
|
||||
mesh,
|
||||
[
|
||||
(0, offset_of!(ModelMeshVertex, pos)),
|
||||
(1, offset_of!(ModelMeshVertex, uv)),
|
||||
(2, offset_of!(ModelMeshVertex, normal)),
|
||||
(3, offset_of!(ModelMeshVertex, layer)),
|
||||
(4, offset_of!(ModelMeshVertex, emission)),
|
||||
]
|
||||
);
|
||||
let inst = super::MODEL_INSTANCE_ATTRIBUTES.map(|a| (a.shader_location, a.offset as usize));
|
||||
assert_eq!(
|
||||
inst,
|
||||
[
|
||||
(5, offset_of!(ModelInstance, pose)),
|
||||
(6, offset_of!(ModelInstance, rotation)),
|
||||
(7, offset_of!(ModelInstance, previous)),
|
||||
(8, offset_of!(ModelInstance, old_rotation)),
|
||||
(9, offset_of!(ModelInstance, light)),
|
||||
(10, offset_of!(ModelInstance, id)),
|
||||
(11, offset_of!(ModelInstance, flags)),
|
||||
]
|
||||
);
|
||||
assert_eq!(std::mem::size_of::<ModelMeshVertex>(), 40);
|
||||
assert_eq!(std::mem::size_of::<ModelInstance>(), 80);
|
||||
}
|
||||
#[test]
|
||||
fn cracks_multiply_instead_of_covering_the_block() {
|
||||
let blend = super::CRUMBLING_BLEND;
|
||||
assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst);
|
||||
|
||||
@@ -109,6 +109,7 @@ pub mod mipmap;
|
||||
pub mod mobs;
|
||||
pub mod mod_content;
|
||||
pub mod mod_list;
|
||||
pub mod model_instance;
|
||||
mod model_library;
|
||||
pub mod models;
|
||||
pub mod motion;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! AirDef fork (#147): GPU-instanced mod models. One mass group of identical
|
||||
//! models is drawn from a retained GPU mesh per block state (uploaded once per
|
||||
//! pack generation) and one instance record per model, shared by the main,
|
||||
//! motion and shadow passes. The records carry the current and previous drawn
|
||||
//! poses, the model's id and its light; the vertex shader applies the same
|
||||
//! transform, normal quantization and material/light rules the CPU bake does
|
||||
//! (`game/mod_models.rs`), so the fallback path stays vertex-identical.
|
||||
|
||||
/// One vertex of a retained model mesh, in model space: the unit cube about
|
||||
/// its centre, the UVs already resolved against the atlas, the face normal
|
||||
/// unquantized (the shader rotates and quantizes it per instance), the special
|
||||
/// material overlay and the face's light emission (16 per level).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct ModelMeshVertex {
|
||||
pub pos: [f32; 3],
|
||||
pub uv: [f32; 2],
|
||||
pub normal: [f32; 3],
|
||||
pub layer: u32,
|
||||
pub emission: u32,
|
||||
}
|
||||
|
||||
/// One drawn model of the instanced group: where it is this frame and where it
|
||||
/// was last drawn (camera-relative, the scale in `w`), its light packed as the
|
||||
/// CPU path packs it (sky in bits 0..8, block in 8..16), the mod's model id and
|
||||
/// flags. The motion pass turns the previous pose into the same motion vector
|
||||
/// the per-vertex motion bake produced; a model that did not move carries
|
||||
/// identical poses and keeps zero object velocity (#143's static contract).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct ModelInstance {
|
||||
pub pose: [f32; 4],
|
||||
pub rotation: [f32; 4],
|
||||
pub previous: [f32; 4],
|
||||
pub old_rotation: [f32; 4],
|
||||
pub light: u32,
|
||||
pub id: u32,
|
||||
pub flags: u32,
|
||||
pub _pad: u32,
|
||||
}
|
||||
|
||||
/// `ModelInstance::flags`: the whole model glows (overlay 40, full brightness).
|
||||
pub const MODEL_INSTANCE_GLOW: u32 = 1;
|
||||
|
||||
/// The group's smallest worth instancing: below it the CPU bake is cheaper
|
||||
/// than a mesh upload plus the instanced draws, and the frame stays on the
|
||||
/// fallback path.
|
||||
pub const MIN_INSTANCED_MODELS: usize = 8;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn records_are_tightly_packed_for_the_vertex_layout() {
|
||||
assert_eq!(std::mem::size_of::<ModelMeshVertex>(), 40);
|
||||
assert_eq!(std::mem::size_of::<ModelInstance>(), 80);
|
||||
assert_eq!(std::mem::offset_of!(ModelInstance, light), 64);
|
||||
assert_eq!(std::mem::offset_of!(ModelInstance, id), 68);
|
||||
assert_eq!(std::mem::offset_of!(ModelInstance, flags), 72);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user