mod range;
mod render_layers;
use std::any::TypeId;
pub use range::*;
pub use render_layers::*;
use bevy_app::{Plugin, PostUpdate};
use bevy_asset::{Assets, Handle};
use bevy_derive::Deref;
use bevy_ecs::{prelude::*, query::QueryFilter};
use bevy_hierarchy::{Children, Parent};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_transform::{components::GlobalTransform, TransformSystem};
use bevy_utils::{Parallel, TypeIdMap};
use crate::{
camera::{Camera, CameraProjection},
mesh::Mesh,
primitives::{Aabb, Frustum, Sphere},
};
use super::NoCpuCulling;
#[derive(Component, Clone, Copy, Reflect, Debug, PartialEq, Eq, Default)]
#[reflect(Component, Default)]
pub enum Visibility {
#[default]
Inherited,
Hidden,
Visible,
}
impl PartialEq<Visibility> for &Visibility {
#[inline]
fn eq(&self, other: &Visibility) -> bool {
<Visibility as PartialEq<Visibility>>::eq(*self, other)
}
}
impl PartialEq<&Visibility> for Visibility {
#[inline]
fn eq(&self, other: &&Visibility) -> bool {
<Visibility as PartialEq<Visibility>>::eq(self, *other)
}
}
#[derive(Component, Deref, Debug, Default, Clone, Copy, Reflect, PartialEq, Eq)]
#[reflect(Component, Default)]
pub struct InheritedVisibility(bool);
impl InheritedVisibility {
pub const HIDDEN: Self = Self(false);
pub const VISIBLE: Self = Self(true);
#[inline]
pub fn get(self) -> bool {
self.0
}
}
#[derive(Component, Deref, Debug, Default, Clone, Copy, Reflect, PartialEq, Eq)]
#[reflect(Component, Default)]
pub struct ViewVisibility(bool);
impl ViewVisibility {
pub const HIDDEN: Self = Self(false);
#[inline]
pub fn get(self) -> bool {
self.0
}
#[inline]
pub fn set(&mut self) {
self.0 = true;
}
}
#[derive(Bundle, Debug, Clone, Default)]
pub struct VisibilityBundle {
pub visibility: Visibility,
pub inherited_visibility: InheritedVisibility,
pub view_visibility: ViewVisibility,
}
#[derive(Component, Default, Reflect)]
#[reflect(Component, Default)]
pub struct NoFrustumCulling;
#[derive(Clone, Component, Default, Debug, Reflect)]
#[reflect(Component, Default)]
pub struct VisibleEntities {
#[reflect(ignore)]
pub entities: TypeIdMap<Vec<Entity>>,
}
impl VisibleEntities {
pub fn get<QF>(&self) -> &[Entity]
where
QF: 'static,
{
match self.entities.get(&TypeId::of::<QF>()) {
Some(entities) => &entities[..],
None => &[],
}
}
pub fn get_mut<QF>(&mut self) -> &mut Vec<Entity>
where
QF: 'static,
{
self.entities.entry(TypeId::of::<QF>()).or_default()
}
pub fn iter<QF>(&self) -> impl DoubleEndedIterator<Item = &Entity>
where
QF: 'static,
{
self.get::<QF>().iter()
}
pub fn len<QF>(&self) -> usize
where
QF: 'static,
{
self.get::<QF>().len()
}
pub fn is_empty<QF>(&self) -> bool
where
QF: 'static,
{
self.get::<QF>().is_empty()
}
pub fn clear<QF>(&mut self)
where
QF: 'static,
{
self.get_mut::<QF>().clear();
}
pub fn push<QF>(&mut self, entity: Entity)
where
QF: 'static,
{
self.get_mut::<QF>().push(entity);
}
}
pub type WithMesh = With<Handle<Mesh>>;
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum VisibilitySystems {
CalculateBounds,
UpdateFrusta,
VisibilityPropagate,
CheckVisibility,
}
pub struct VisibilityPlugin;
impl Plugin for VisibilityPlugin {
fn build(&self, app: &mut bevy_app::App) {
use VisibilitySystems::*;
app.configure_sets(
PostUpdate,
(CalculateBounds, UpdateFrusta, VisibilityPropagate)
.before(CheckVisibility)
.after(TransformSystem::TransformPropagate),
)
.add_systems(
PostUpdate,
(
calculate_bounds.in_set(CalculateBounds),
(visibility_propagate_system, reset_view_visibility).in_set(VisibilityPropagate),
check_visibility::<WithMesh>.in_set(CheckVisibility),
),
);
}
}
pub fn calculate_bounds(
mut commands: Commands,
meshes: Res<Assets<Mesh>>,
without_aabb: Query<(Entity, &Handle<Mesh>), (Without<Aabb>, Without<NoFrustumCulling>)>,
) {
for (entity, mesh_handle) in &without_aabb {
if let Some(mesh) = meshes.get(mesh_handle) {
if let Some(aabb) = mesh.compute_aabb() {
commands.entity(entity).try_insert(aabb);
}
}
}
}
pub fn update_frusta<T: Component + CameraProjection + Send + Sync + 'static>(
mut views: Query<
(&GlobalTransform, &T, &mut Frustum),
Or<(Changed<GlobalTransform>, Changed<T>)>,
>,
) {
for (transform, projection, mut frustum) in &mut views {
*frustum = projection.compute_frustum(transform);
}
}
fn visibility_propagate_system(
changed: Query<
(Entity, &Visibility, Option<&Parent>, Option<&Children>),
(With<InheritedVisibility>, Changed<Visibility>),
>,
mut visibility_query: Query<(&Visibility, &mut InheritedVisibility)>,
children_query: Query<&Children, (With<Visibility>, With<InheritedVisibility>)>,
) {
for (entity, visibility, parent, children) in &changed {
let is_visible = match visibility {
Visibility::Visible => true,
Visibility::Hidden => false,
Visibility::Inherited => parent
.and_then(|p| visibility_query.get(p.get()).ok())
.map_or(true, |(_, x)| x.get()),
};
let (_, mut inherited_visibility) = visibility_query
.get_mut(entity)
.expect("With<InheritedVisibility> ensures this query will return a value");
if inherited_visibility.get() != is_visible {
inherited_visibility.0 = is_visible;
for &child in children.into_iter().flatten() {
let _ =
propagate_recursive(is_visible, child, &mut visibility_query, &children_query);
}
}
}
}
fn propagate_recursive(
parent_is_visible: bool,
entity: Entity,
visibility_query: &mut Query<(&Visibility, &mut InheritedVisibility)>,
children_query: &Query<&Children, (With<Visibility>, With<InheritedVisibility>)>,
) -> Result<(), ()> {
let (visibility, mut inherited_visibility) = visibility_query.get_mut(entity).map_err(drop)?;
let is_visible = match visibility {
Visibility::Visible => true,
Visibility::Hidden => false,
Visibility::Inherited => parent_is_visible,
};
if inherited_visibility.get() != is_visible {
inherited_visibility.0 = is_visible;
for &child in children_query.get(entity).ok().into_iter().flatten() {
let _ = propagate_recursive(is_visible, child, visibility_query, children_query);
}
}
Ok(())
}
fn reset_view_visibility(mut query: Query<&mut ViewVisibility>) {
query.iter_mut().for_each(|mut view_visibility| {
*view_visibility.bypass_change_detection() = ViewVisibility::HIDDEN;
});
}
pub fn check_visibility<QF>(
mut thread_queues: Local<Parallel<Vec<Entity>>>,
mut view_query: Query<(
Entity,
&mut VisibleEntities,
&Frustum,
Option<&RenderLayers>,
&Camera,
Has<NoCpuCulling>,
)>,
mut visible_aabb_query: Query<
(
Entity,
&InheritedVisibility,
&mut ViewVisibility,
Option<&RenderLayers>,
Option<&Aabb>,
&GlobalTransform,
Has<NoFrustumCulling>,
Has<VisibilityRange>,
),
QF,
>,
visible_entity_ranges: Option<Res<VisibleEntityRanges>>,
) where
QF: QueryFilter + 'static,
{
let visible_entity_ranges = visible_entity_ranges.as_deref();
for (view, mut visible_entities, frustum, maybe_view_mask, camera, no_cpu_culling) in
&mut view_query
{
if !camera.is_active {
continue;
}
let view_mask = maybe_view_mask.unwrap_or_default();
visible_aabb_query.par_iter_mut().for_each_init(
|| thread_queues.borrow_local_mut(),
|queue, query_item| {
let (
entity,
inherited_visibility,
mut view_visibility,
maybe_entity_mask,
maybe_model_aabb,
transform,
no_frustum_culling,
has_visibility_range,
) = query_item;
if !inherited_visibility.get() {
return;
}
let entity_mask = maybe_entity_mask.unwrap_or_default();
if !view_mask.intersects(entity_mask) {
return;
}
if has_visibility_range
&& visible_entity_ranges.is_some_and(|visible_entity_ranges| {
!visible_entity_ranges.entity_is_in_range_of_view(entity, view)
})
{
return;
}
if !no_frustum_culling && !no_cpu_culling {
if let Some(model_aabb) = maybe_model_aabb {
let world_from_local = transform.affine();
let model_sphere = Sphere {
center: world_from_local.transform_point3a(model_aabb.center),
radius: transform.radius_vec3a(model_aabb.half_extents),
};
if !frustum.intersects_sphere(&model_sphere, false) {
return;
}
if !frustum.intersects_obb(model_aabb, &world_from_local, true, false) {
return;
}
}
}
view_visibility.set();
queue.push(entity);
},
);
visible_entities.clear::<QF>();
thread_queues.drain_into(visible_entities.get_mut::<QF>());
}
}
#[cfg(test)]
mod test {
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use super::*;
use bevy_hierarchy::BuildWorldChildren;
fn visibility_bundle(visibility: Visibility) -> VisibilityBundle {
VisibilityBundle {
visibility,
..Default::default()
}
}
#[test]
fn visibility_propagation() {
let mut app = App::new();
app.add_systems(Update, visibility_propagate_system);
let root1 = app
.world_mut()
.spawn(visibility_bundle(Visibility::Hidden))
.id();
let root1_child1 = app.world_mut().spawn(VisibilityBundle::default()).id();
let root1_child2 = app
.world_mut()
.spawn(visibility_bundle(Visibility::Hidden))
.id();
let root1_child1_grandchild1 = app.world_mut().spawn(VisibilityBundle::default()).id();
let root1_child2_grandchild1 = app.world_mut().spawn(VisibilityBundle::default()).id();
app.world_mut()
.entity_mut(root1)
.push_children(&[root1_child1, root1_child2]);
app.world_mut()
.entity_mut(root1_child1)
.push_children(&[root1_child1_grandchild1]);
app.world_mut()
.entity_mut(root1_child2)
.push_children(&[root1_child2_grandchild1]);
let root2 = app.world_mut().spawn(VisibilityBundle::default()).id();
let root2_child1 = app.world_mut().spawn(VisibilityBundle::default()).id();
let root2_child2 = app
.world_mut()
.spawn(visibility_bundle(Visibility::Hidden))
.id();
let root2_child1_grandchild1 = app.world_mut().spawn(VisibilityBundle::default()).id();
let root2_child2_grandchild1 = app.world_mut().spawn(VisibilityBundle::default()).id();
app.world_mut()
.entity_mut(root2)
.push_children(&[root2_child1, root2_child2]);
app.world_mut()
.entity_mut(root2_child1)
.push_children(&[root2_child1_grandchild1]);
app.world_mut()
.entity_mut(root2_child2)
.push_children(&[root2_child2_grandchild1]);
app.update();
let is_visible = |e: Entity| {
app.world()
.entity(e)
.get::<InheritedVisibility>()
.unwrap()
.get()
};
assert!(
!is_visible(root1),
"invisibility propagates down tree from root"
);
assert!(
!is_visible(root1_child1),
"invisibility propagates down tree from root"
);
assert!(
!is_visible(root1_child2),
"invisibility propagates down tree from root"
);
assert!(
!is_visible(root1_child1_grandchild1),
"invisibility propagates down tree from root"
);
assert!(
!is_visible(root1_child2_grandchild1),
"invisibility propagates down tree from root"
);
assert!(
is_visible(root2),
"visibility propagates down tree from root"
);
assert!(
is_visible(root2_child1),
"visibility propagates down tree from root"
);
assert!(
!is_visible(root2_child2),
"visibility propagates down tree from root, but local invisibility is preserved"
);
assert!(
is_visible(root2_child1_grandchild1),
"visibility propagates down tree from root"
);
assert!(
!is_visible(root2_child2_grandchild1),
"child's invisibility propagates down to grandchild"
);
}
#[test]
fn visibility_propagation_unconditional_visible() {
use Visibility::{Hidden, Inherited, Visible};
let mut app = App::new();
app.add_systems(Update, visibility_propagate_system);
let root1 = app.world_mut().spawn(visibility_bundle(Visible)).id();
let root1_child1 = app.world_mut().spawn(visibility_bundle(Inherited)).id();
let root1_child2 = app.world_mut().spawn(visibility_bundle(Hidden)).id();
let root1_child1_grandchild1 = app.world_mut().spawn(visibility_bundle(Visible)).id();
let root1_child2_grandchild1 = app.world_mut().spawn(visibility_bundle(Visible)).id();
let root2 = app.world_mut().spawn(visibility_bundle(Inherited)).id();
let root3 = app.world_mut().spawn(visibility_bundle(Hidden)).id();
app.world_mut()
.entity_mut(root1)
.push_children(&[root1_child1, root1_child2]);
app.world_mut()
.entity_mut(root1_child1)
.push_children(&[root1_child1_grandchild1]);
app.world_mut()
.entity_mut(root1_child2)
.push_children(&[root1_child2_grandchild1]);
app.update();
let is_visible = |e: Entity| {
app.world()
.entity(e)
.get::<InheritedVisibility>()
.unwrap()
.get()
};
assert!(
is_visible(root1),
"an unconditionally visible root is visible"
);
assert!(
is_visible(root1_child1),
"an inheriting child of an unconditionally visible parent is visible"
);
assert!(
!is_visible(root1_child2),
"a hidden child on an unconditionally visible parent is hidden"
);
assert!(
is_visible(root1_child1_grandchild1),
"an unconditionally visible child of an inheriting parent is visible"
);
assert!(
is_visible(root1_child2_grandchild1),
"an unconditionally visible child of a hidden parent is visible"
);
assert!(is_visible(root2), "an inheriting root is visible");
assert!(!is_visible(root3), "a hidden root is hidden");
}
#[test]
fn visibility_propagation_change_detection() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(visibility_propagate_system);
let id1 = world.spawn(VisibilityBundle::default()).id();
let id2 = world.spawn(VisibilityBundle::default()).id();
world.entity_mut(id1).push_children(&[id2]);
let id3 = world.spawn(visibility_bundle(Visibility::Hidden)).id();
world.entity_mut(id2).push_children(&[id3]);
let id4 = world.spawn(VisibilityBundle::default()).id();
world.entity_mut(id3).push_children(&[id4]);
schedule.run(&mut world);
world.clear_trackers();
let mut q = world.query::<Ref<InheritedVisibility>>();
assert!(!q.get(&world, id1).unwrap().is_changed());
assert!(!q.get(&world, id2).unwrap().is_changed());
assert!(!q.get(&world, id3).unwrap().is_changed());
assert!(!q.get(&world, id4).unwrap().is_changed());
world.clear_trackers();
world.entity_mut(id1).insert(Visibility::Hidden);
schedule.run(&mut world);
assert!(q.get(&world, id1).unwrap().is_changed());
assert!(q.get(&world, id2).unwrap().is_changed());
assert!(!q.get(&world, id3).unwrap().is_changed());
assert!(!q.get(&world, id4).unwrap().is_changed());
world.clear_trackers();
schedule.run(&mut world);
assert!(!q.get(&world, id1).unwrap().is_changed());
assert!(!q.get(&world, id2).unwrap().is_changed());
assert!(!q.get(&world, id3).unwrap().is_changed());
assert!(!q.get(&world, id4).unwrap().is_changed());
world.clear_trackers();
world.entity_mut(id3).insert(Visibility::Inherited);
schedule.run(&mut world);
assert!(!q.get(&world, id1).unwrap().is_changed());
assert!(!q.get(&world, id2).unwrap().is_changed());
assert!(!q.get(&world, id3).unwrap().is_changed());
assert!(!q.get(&world, id4).unwrap().is_changed());
world.clear_trackers();
world.entity_mut(id2).insert(Visibility::Visible);
schedule.run(&mut world);
assert!(!q.get(&world, id1).unwrap().is_changed());
assert!(q.get(&world, id2).unwrap().is_changed());
assert!(q.get(&world, id3).unwrap().is_changed());
assert!(q.get(&world, id4).unwrap().is_changed());
world.clear_trackers();
schedule.run(&mut world);
assert!(!q.get(&world, id1).unwrap().is_changed());
assert!(!q.get(&world, id2).unwrap().is_changed());
assert!(!q.get(&world, id3).unwrap().is_changed());
assert!(!q.get(&world, id4).unwrap().is_changed());
}
#[test]
fn visibility_propagation_with_invalid_parent() {
let mut world = World::new();
let mut schedule = Schedule::default();
schedule.add_systems(visibility_propagate_system);
let parent = world.spawn(()).id();
let child = world.spawn(VisibilityBundle::default()).id();
world.entity_mut(parent).push_children(&[child]);
schedule.run(&mut world);
world.clear_trackers();
let child_visible = world.entity(child).get::<InheritedVisibility>().unwrap().0;
assert!(child_visible);
}
#[test]
fn ensure_visibility_enum_size() {
use std::mem;
assert_eq!(1, mem::size_of::<Visibility>());
assert_eq!(1, mem::size_of::<Option<Visibility>>());
}
}