Path: blob/main/crates/bevy_render/src/render_phase/rangefinder.rs
9353 views
use bevy_math::{Affine3A, Mat4, Vec3, Vec4};12/// A distance calculator for the draw order of [`PhaseItem`](crate::render_phase::PhaseItem)s.3pub struct ViewRangefinder3d {4view_from_world_row_2: Vec4,5}67impl ViewRangefinder3d {8/// Creates a 3D rangefinder for a view matrix.9pub fn from_world_from_view(world_from_view: &Affine3A) -> ViewRangefinder3d {10let view_from_world = world_from_view.inverse();1112ViewRangefinder3d {13view_from_world_row_2: Mat4::from(view_from_world).row(2),14}15}1617/// Calculates the distance, or view-space `Z` value, for the given world-space `position`.18#[inline]19pub fn distance(&self, position: &Vec3) -> f32 {20// NOTE: row 2 of the inverse view matrix dotted with the world-space position21// gives the z component of the point in view-space22self.view_from_world_row_2.dot(position.extend(1.0))23}24}2526#[cfg(test)]27mod tests {28use super::ViewRangefinder3d;29use bevy_math::{Affine3A, Vec3};3031#[test]32fn distance() {33let view_matrix = Affine3A::from_translation(Vec3::new(0.0, 0.0, -1.0));34let rangefinder = ViewRangefinder3d::from_world_from_view(&view_matrix);35assert_eq!(rangefinder.distance(&Vec3::new(0., 0., 0.)), 1.0);36assert_eq!(rangefinder.distance(&Vec3::new(0., 0., 1.)), 2.0);37}38}394041