Draw the first-person hand with its own projection at hudFov

GameRenderer.render3dHud sets up the hand's projection at Camera's hudFov
(70, changed only by death and fluids), never the FOV option or the
sprint, speed and bow modifier. The hand pass now has its own globals
with that projection (a port of JOML setPerspective, as Projection does).
The camera harness compares the world and hand projection matrices at FOV
options 30, 70, 110 and others with vanilla's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 15:07:39 +02:00
parent 27a32cc30d
commit f2c7a2d359
9 changed files with 158 additions and 7 deletions
+10 -1
View File
@@ -5,7 +5,7 @@ use horizon_client::{
Result,
camera::{
AvatarBob, BobState, Camera, CameraEntity, CameraFluid, CameraType, FovPlayer, HurtBob,
LivingCamera, UseItem, bob_matrix, field_of_view_modifier,
LivingCamera, UseItem, bob_matrix, field_of_view_modifier, perspective,
},
};
use horizon_core::{
@@ -258,6 +258,15 @@ fn camera(c: &Value, out: &mut impl Write) -> Result<()> {
fb(fov),
fb(hud)
)?;
let (w, h, far) = (fl(&op[4]), fl(&op[5]), fl(&op[6]));
let matrix =
|m: [f32; 16]| m.iter().map(|&x| format!(" {}", fb(x))).collect::<String>();
writeln!(
out,
"projection{}{}",
matrix(perspective(fov, w, h, far, 0.05, true)),
matrix(perspective(hud, w, h, far, 0.05, true))
)?;
}
other => panic!("{other}"),
}
+38
View File
@@ -583,6 +583,44 @@ impl Camera {
modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid)
}
}
/// `Projection.getMatrix` for a perspective set up by `setupPerspective`:
/// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near,
/// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed
/// (`near` is `zFar`); the hand pass here keeps them in order.
pub fn perspective(
fov_degrees: f32,
width: f32,
height: f32,
near: f32,
far: f32,
zero_to_one: bool,
) -> [f32; 16] {
let h = horizon_core::jmath::tan(f64::from(fov_degrees * DEG_TO_RAD * 0.5)) as f32;
let aspect = width / height;
let mut m = [0.0f32; 16];
m[0] = 1.0 / (h * aspect);
m[5] = 1.0 / h;
let e = 1.0e-6f32;
if far > 0.0 && far.is_infinite() {
m[10] = e - 1.0;
m[14] = (e - if zero_to_one { 1.0 } else { 2.0 }) * near;
} else if near > 0.0 && near.is_infinite() {
m[10] = (if zero_to_one { 0.0 } else { 1.0 }) - e;
m[14] = ((if zero_to_one { 1.0 } else { 2.0 }) - e) * far;
} else {
m[10] = (if zero_to_one { far } else { far + near }) / (near - far);
m[14] = (if zero_to_one { far } else { far + far }) * near / (near - far);
}
m[11] = -1.0;
m
}
/// `GameRenderer.render3dHud`: the first-person hand and held items are
/// drawn with their own projection at `hudFov` (70 degrees, changed only by
/// death and fluids), never the FOV option or the sprint, speed and bow
/// modifier.
pub fn hand_projection(hud_fov: f32, width: f32, height: f32, far: f32) -> [f32; 16] {
perspective(hud_fov, width, height, 0.05, far, true)
}
/// `Camera.modifyFovBasedOnDeathOrFluid`. `dead` is the camera entity's
/// `deathTime` while it is a living entity that is dead or dying.
pub fn modify_fov_based_on_death_or_fluid(
+1
View File
@@ -7319,6 +7319,7 @@ impl Game<'_> {
additive: &additive,
celestial: &celestial,
hand: &hand,
hand_fov_degrees: self.hud_fov_degrees(alpha as f32, camera.to_array()),
screen: &screen,
border,
game_time: self.world.game_time as f32,
+9
View File
@@ -86,6 +86,15 @@ impl Game<'_> {
false,
)
}
/// `Camera.calculateHudFov`: the first-person hand's field of view.
pub(super) fn hud_fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 {
self.view.calculate_hud_fov(
partial,
self.fov_effect_scale(),
self.death_time(),
self.camera_fluid(camera),
)
}
/// The pose `GameRenderer.renderLevel` multiplies into the projection:
/// `bobHurt`, then `bobView` with the View Bobbing option.
pub(super) fn bob_matrix(&self, partial: f32) -> glam::Mat4 {
+55 -1
View File
@@ -78,6 +78,9 @@ pub struct Frame<'a> {
pub celestial: &'a [Vertex],
/// First-person hand and held item, drawn after clearing depth.
pub hand: &'a [Vertex],
/// `CameraRenderState.hudFov`: the hand's own field of view
/// (`GameRenderer.render3dHud`).
pub hand_fov_degrees: f32,
/// Full-screen camera effects drawn over the world and hand, under the HUD.
pub screen: &'a [crate::screen_effects::ScreenQuad],
/// The world border wall, when near enough to be drawn.
@@ -139,6 +142,9 @@ pub struct Renderer {
screen_buffer: wgpu::Buffer,
screen_capacity: u64,
entity_group: wgpu::BindGroup,
/// The entity resources with the hand's projection (`hand_globals`).
hand_group: wgpu::BindGroup,
hand_globals: wgpu::Buffer,
entity_buffer: wgpu::Buffer,
entity_capacity: u64,
group: wgpu::BindGroup,
@@ -470,6 +476,12 @@ impl Renderer {
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let hand_globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("First-person hand globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, layers);
let sprite_texture = device.create_texture_with_data(
&queue,
@@ -665,6 +677,32 @@ impl Renderer {
},
],
});
let hand_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("First-person hand resources"),
layout: &entity_bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: hand_globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Entity layout"),
bind_group_layouts: &[Some(&entity_bindings)],
@@ -1065,6 +1103,8 @@ impl Renderer {
screen_buffer,
screen_capacity,
entity_group,
hand_group,
hand_globals,
entity_buffer,
entity_capacity,
group,
@@ -1492,6 +1532,20 @@ impl Renderer {
};
self.queue
.write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));
// GameRenderer.render3dHud: the hand's projection at hudFov, with the
// bob in its pose rather than the projection (same product).
let hand_projection = Mat4::from_cols_array(&crate::camera::hand_projection(
frame.hand_fov_degrees,
self.config.width as f32,
self.config.height.max(1) as f32,
(frame.distance * 4.0).max(1024.0),
));
let hand_globals = Globals {
view_proj: (hand_projection * frame.bob * view).to_cols_array_2d(),
..globals
};
self.queue
.write_buffer(&self.hand_globals, 0, bytemuck::bytes_of(&hand_globals));
// Frustum culling and camera-relative origins.
let planes = frustum(view_proj);
let camera = frame.camera;
@@ -1803,7 +1857,7 @@ impl Renderer {
..Default::default()
});
pass.set_pipeline(&self.entity_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_bind_group(0, &self.hand_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

@@ -299,6 +299,11 @@ public final class VanillaCameraOracle {
+ " " + fb(up.x()) + " " + fb(up.y()) + " " + fb(up.z())
+ " " + fb(left.x()) + " " + fb(left.y()) + " " + fb(left.z())
+ " " + camera.isDetached() + " " + fb(fv) + " " + fb(hv));
// Camera.setupPerspective and GameRenderer.render3dHud's hudProjection:
// Projection.getMatrix's setPerspective (planes reversed, zero-to-one depth).
float w = f(op.get(4)), h = f(op.get(5)), far = f(op.get(6));
out.println("projection" + matrix(new Matrix4f().setPerspective(fv * (float) (Math.PI / 180.0), w / h, far, 0.05F, true))
+ matrix(new Matrix4f().setPerspective(hv * (float) (Math.PI / 180.0), w / h, far, 0.05F, true)));
}
default -> throw new IllegalArgumentException(op.toString());
}
@@ -388,6 +393,16 @@ public final class VanillaCameraOracle {
out.println(sb);
}
static String matrix(Matrix4f m) {
var sb = new StringBuilder();
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
sb.append(' ').append(fb(m.get(col, row)));
}
}
return sb.toString();
}
static void avatar(JsonObject c, PrintWriter out) throws Exception {
StubPlayer p = make(StubPlayer.class);
var state = new ClientAvatarState();
+30 -5
View File
@@ -4,8 +4,10 @@ field-of-view easing), alignWithEntity (view rotation quaternion and basis,
interpolated eye, third person back and front, camera distance and scale
attributes with mounts, getMaxZoom clipping against visual shapes, sleeping),
calculateFov/calculateHudFov (option, modifier, death and fluid effects,
panoramic mode), AbstractClientPlayer.getFieldOfViewModifier (flight, speed
attribute against walking speed, bow draw, spyglass), the walk and bob
panoramic mode) with the world projection and the first-person hand's
(GameRenderer.render3dHud at hudFov, whatever the FOV option),
AbstractClientPlayer.getFieldOfViewModifier (flight, speed attribute against
walking speed, bow draw, spyglass), the walk and bob
history (ClientAvatarState, updateBob) and GameRenderer.bobHurt/bobView,
driven tick by tick and frame by frame with identical scripted states."""
import json
@@ -91,6 +93,12 @@ def entity_state(rng, center):
return s
def window(rng):
"""Window size and Camera.depthFar for the world and hand projections."""
w, h = rng.choice([(1600, 1000), (854, 480), (1920, 1080), (800, 1200), (1, 1), (rng.randint(1, 4000), rng.randint(1, 3000))])
return [fbits(w), fbits(h), fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))]
def camera_cases(rng):
for n in range(2500):
center = rng.choice([(0, 64, 0), (-10, -60, 7), (1000, 120, -3000), (0, 0, 0)])
@@ -105,12 +113,27 @@ def camera_cases(rng):
ops.append(['tick'])
elif kind == 'frame':
pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()])
ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05])
ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng))
else:
ops.append(['type', rng.randrange(3)])
yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]),
effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]),
cells=world(rng, center), ops=ops)
# The hand's projection at FOV 30, 70 and 110 while walking, sprinting, under
# speed, drawing a bow, dying and in fluids: GameRenderer.render3dHud uses
# hudFov, never the option or the modifier.
for fov in (30, 70, 110):
for speed in (f32(0.1), f32(0.1) * 1.3, 0.2, 0.05):
for use in (None, ['bow', 10]):
for dead in (None, 5):
for fluid in (0, 1, 2):
s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)],
xr=fbits(0.0), yr=fbits(0.0), xro=fbits(0.0), yro=fbits(0.0), eye=fbits(1.62), flying=False,
ws=fbits(0.1), speed=dbits(speed), use=use, scale_attr=dbits(1.0), dist=dbits(4.0),
sleeping=None, dead=dead, mount=None)
ops = [['entity', s]] + [['tick']] * 8 + [['frame', fbits(pt), fluid, False, fbits(1600.0), fbits(1000.0), fbits(768.0)]
for pt in (0.0, 0.5, 1.0)]
yield dict(t='camera', fov=fov, effect=dbits(1.0), type=0, cells={}, ops=ops)
# A walled-in third-person camera stepping through every distance bound.
for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]:
for wall in range(0, 6):
@@ -124,7 +147,7 @@ def camera_cases(rng):
xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False,
ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist),
sleeping=None, dead=None, mount=None)
ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] for pt in (0.0, 0.5, 1.0)]
ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)]
yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops)
@@ -184,7 +207,9 @@ def main():
'interpolated eye with eye-height easing, first person, third person back and mirrored front, scale and '
'camera_distance attributes including a living mount, getMaxZoom over the actual Level.clip with '
'ClipContext.Block.VISUAL against controlled visual shapes, sleeping bed orientation), calculateFov and '
'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), '
'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), the world projection '
'(Camera.setupPerspective) and the hand projection GameRenderer.render3dHud sets up at hudFov, as JOML setPerspective '
'matrices, at FOV options 30, 70 and 110 among others, '
'AbstractClientPlayer.getFieldOfViewModifier with real Abilities, attribute maps and item stacks, '
'ClientAvatarState walk/bob history with AbstractClientPlayer.updateBob, and GameRenderer.bobHurt/bobView '
'as the full JOML pose matrix with its property flags. The camera entity is a shell with controlled '