Path: blob/main/crates/bevy_render/src/render_phase/rangefinder.rs
6596 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 `translation`.18#[inline]19pub fn distance_translation(&self, translation: &Vec3) -> f32 {20// NOTE: row 2 of the inverse view matrix dotted with the translation from the model matrix21// gives the z component of translation of the mesh in view-space22self.view_from_world_row_2.dot(translation.extend(1.0))23}2425/// Calculates the distance, or view-space `Z` value, for the given `transform`.26#[inline]27pub fn distance(&self, transform: &Mat4) -> f32 {28// NOTE: row 2 of the inverse view matrix dotted with column 3 of the model matrix29// gives the z component of translation of the mesh in view-space30self.view_from_world_row_2.dot(transform.col(3))31}32}3334#[cfg(test)]35mod tests {36use super::ViewRangefinder3d;37use bevy_math::{Affine3A, Mat4, Vec3};3839#[test]40fn distance() {41let view_matrix = Affine3A::from_translation(Vec3::new(0.0, 0.0, -1.0));42let rangefinder = ViewRangefinder3d::from_world_from_view(&view_matrix);43assert_eq!(rangefinder.distance(&Mat4::IDENTITY), 1.0);44assert_eq!(45rangefinder.distance(&Mat4::from_translation(Vec3::new(0.0, 0.0, 1.0))),462.047);48}49}505152