use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
use super::LightingSystems;
use crate::chunk::{CHUNK_SIZE, ChunkCoord, VOXEL_SIZE};
use crate::world::{ChunkManager, ViewerPosition};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlacedLight {
pub color: Color,
pub intensity: f32,
pub range: f32,
pub radius: f32,
pub shadows_enabled: bool,
pub offset: Vec3,
}
impl Default for PlacedLight {
fn default() -> Self {
Self {
color: Color::WHITE,
intensity: 1_000_000.0,
range: 20.0,
radius: 0.0,
shadows_enabled: false,
offset: Vec3::ZERO,
}
}
}
impl PlacedLight {
pub fn world_position(&self, voxel: IVec3) -> Vec3 {
(voxel.as_vec3() + Vec3::splat(0.5)) * VOXEL_SIZE + self.offset
}
fn apply(&self, light: &mut PointLight) {
light.color = self.color;
light.intensity = self.intensity;
light.range = self.range;
light.radius = self.radius;
light.shadows_enabled = self.shadows_enabled;
}
}
pub fn placed_light_voxel(world_pos: Vec3) -> IVec3 {
(world_pos / VOXEL_SIZE).floor().as_ivec3()
}
pub fn placed_light_chunk(voxel: IVec3) -> ChunkCoord {
voxel.div_euclid(IVec3::splat(CHUNK_SIZE as i32))
}
#[derive(Resource, Debug, Clone, Default)]
pub struct PlacedLights {
lights: HashMap<IVec3, PlacedLight>,
}
impl PlacedLights {
pub fn insert(&mut self, voxel: IVec3, light: PlacedLight) -> Option<PlacedLight> {
self.lights.insert(voxel, light)
}
pub fn remove(&mut self, voxel: IVec3) -> Option<PlacedLight> {
self.lights.remove(&voxel)
}
pub fn get(&self, voxel: IVec3) -> Option<&PlacedLight> {
self.lights.get(&voxel)
}
pub fn get_mut(&mut self, voxel: IVec3) -> Option<&mut PlacedLight> {
self.lights.get_mut(&voxel)
}
pub fn contains(&self, voxel: IVec3) -> bool {
self.lights.contains_key(&voxel)
}
pub fn len(&self) -> usize {
self.lights.len()
}
pub fn is_empty(&self) -> bool {
self.lights.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (IVec3, &PlacedLight)> + '_ {
self.lights.iter().map(|(voxel, light)| (*voxel, light))
}
pub fn clear(&mut self) {
self.lights.clear();
}
}
#[derive(Resource, Debug, Clone, Copy, PartialEq)]
pub struct PlacedLightBudget {
pub max_active: usize,
pub max_distance: f32,
}
impl Default for PlacedLightBudget {
fn default() -> Self {
Self {
max_active: 16,
max_distance: f32::INFINITY,
}
}
}
pub fn select_active_lights(
candidates: impl IntoIterator<Item = (IVec3, Vec3)>,
viewer: Vec3,
budget: &PlacedLightBudget,
) -> Vec<IVec3> {
if budget.max_active == 0 || budget.max_distance < 0.0 {
return Vec::new();
}
let max_distance_squared = if budget.max_distance.is_nan() {
f32::INFINITY
} else {
budget.max_distance * budget.max_distance
};
let mut ranked: Vec<(f32, IVec3)> = candidates
.into_iter()
.filter_map(|(voxel, position)| {
let distance_squared = position.distance_squared(viewer);
(distance_squared <= max_distance_squared).then_some((distance_squared, voxel))
})
.collect();
ranked.sort_by(|a, b| {
a.0.total_cmp(&b.0)
.then_with(|| a.1.to_array().cmp(&b.1.to_array()))
});
ranked.truncate(budget.max_active);
ranked.into_iter().map(|(_, voxel)| voxel).collect()
}
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PlacedLightSource {
pub voxel: IVec3,
}
fn sync_placed_lights(
mut commands: Commands,
lights: Res<PlacedLights>,
budget: Res<PlacedLightBudget>,
viewer: Option<Res<ViewerPosition>>,
manager: Option<Res<ChunkManager>>,
mut spawned: Query<(Entity, &PlacedLightSource, &mut PointLight, &mut Transform)>,
) {
if lights.is_empty() && spawned.is_empty() {
return;
}
let viewer = viewer.map_or(Vec3::ZERO, |viewer| viewer.position);
let candidates = lights.iter().filter_map(|(voxel, light)| {
let loaded = match &manager {
Some(manager) => manager.is_loaded(placed_light_chunk(voxel)),
None => true,
};
loaded.then(|| (voxel, light.world_position(voxel)))
});
let active: HashSet<IVec3> = select_active_lights(candidates, viewer, &budget)
.into_iter()
.collect();
let records_changed = lights.is_changed();
let mut shown: HashSet<IVec3> = HashSet::new();
for (entity, source, mut point, mut transform) in &mut spawned {
let record = lights
.get(source.voxel)
.filter(|_| active.contains(&source.voxel));
match record {
Some(light) if shown.insert(source.voxel) => {
if records_changed {
light.apply(&mut point);
transform.translation = light.world_position(source.voxel);
}
}
_ => commands.entity(entity).try_despawn(),
}
}
for voxel in active {
if shown.contains(&voxel) {
continue;
}
if let Some(light) = lights.get(voxel) {
let mut point = PointLight::default();
light.apply(&mut point);
commands.spawn((
PlacedLightSource { voxel },
point,
Transform::from_translation(light.world_position(voxel)),
));
}
}
}
pub struct PlacedLightsPlugin;
impl Plugin for PlacedLightsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<PlacedLights>();
app.init_resource::<PlacedLightBudget>();
app.add_systems(Update, sync_placed_lights.in_set(LightingSystems::Placed));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn budget(max_active: usize, max_distance: f32) -> PlacedLightBudget {
PlacedLightBudget {
max_active,
max_distance,
}
}
fn on_x_axis(xs: &[i32]) -> Vec<(IVec3, Vec3)> {
xs.iter()
.map(|&x| {
let voxel = IVec3::new(x, 0, 0);
(voxel, PlacedLight::default().world_position(voxel))
})
.collect()
}
fn app() -> App {
let mut app = App::new();
app.add_plugins(PlacedLightsPlugin);
app
}
fn shown(app: &mut App) -> Vec<IVec3> {
let mut query = app.world_mut().query::<&PlacedLightSource>();
let mut voxels: Vec<IVec3> = query.iter(app.world()).map(|s| s.voxel).collect();
voxels.sort_by_key(|v| v.to_array());
voxels
}
fn place(app: &mut App, voxel: IVec3, light: PlacedLight) {
app.world_mut()
.resource_mut::<PlacedLights>()
.insert(voxel, light);
}
#[test]
fn defaults_match_the_engine_point_light() {
let light = PlacedLight::default();
let engine = PointLight::default();
assert_eq!(light.color, engine.color);
assert_eq!(light.intensity, engine.intensity);
assert_eq!(light.range, engine.range);
assert_eq!(light.radius, engine.radius);
assert_eq!(light.shadows_enabled, engine.shadows_enabled);
assert_eq!(light.offset, Vec3::ZERO);
let budget = PlacedLightBudget::default();
assert_eq!(budget.max_active, 16);
assert_eq!(budget.max_distance, f32::INFINITY);
}
#[test]
fn voxel_and_chunk_helpers_handle_negative_positions() {
assert_eq!(
placed_light_voxel(Vec3::new(0.0, 15.99, 16.0)),
IVec3::new(0, 15, 16)
);
assert_eq!(
placed_light_voxel(Vec3::new(-0.01, -1.0, -16.5)),
IVec3::new(-1, -1, -17)
);
assert_eq!(
placed_light_chunk(IVec3::new(0, 15, 16)),
IVec3::new(0, 0, 1)
);
assert_eq!(
placed_light_chunk(IVec3::new(-1, -16, -17)),
IVec3::new(-1, -1, -2)
);
for voxel in [IVec3::new(-1, 31, 5), IVec3::new(-33, 0, 16)] {
let center = PlacedLight::default().world_position(voxel);
assert_eq!(
placed_light_chunk(voxel),
crate::chunk::world_to_chunk_coord(center)
);
}
}
#[test]
fn registry_inserts_replaces_and_removes() {
let mut lights = PlacedLights::default();
let voxel = IVec3::new(1, 2, 3);
assert!(lights.is_empty());
assert!(lights.insert(voxel, PlacedLight::default()).is_none());
let replaced = lights.insert(
voxel,
PlacedLight {
range: 5.0,
..default()
},
);
assert_eq!(replaced, Some(PlacedLight::default()));
assert_eq!(lights.len(), 1);
assert_eq!(lights.get(voxel).unwrap().range, 5.0);
assert_eq!(lights.iter().count(), 1);
assert!(!lights.contains(IVec3::ZERO));
assert!(lights.remove(IVec3::ZERO).is_none());
assert!(lights.remove(voxel).is_some());
lights.insert(voxel, PlacedLight::default());
lights.clear();
assert!(lights.is_empty());
}
#[test]
fn selection_keeps_the_nearest_within_the_budget() {
let candidates = on_x_axis(&[30, 2, -5, 12, 1]);
let active = select_active_lights(candidates, Vec3::ZERO, &budget(3, f32::INFINITY));
assert_eq!(
active,
vec![
IVec3::new(1, 0, 0),
IVec3::new(2, 0, 0),
IVec3::new(-5, 0, 0)
]
);
}
#[test]
fn selection_follows_the_viewer() {
let candidates = on_x_axis(&[0, 10, 20, 30]);
let active = select_active_lights(
candidates,
Vec3::new(29.0, 0.5, 0.5),
&budget(2, f32::INFINITY),
);
assert_eq!(active, vec![IVec3::new(30, 0, 0), IVec3::new(20, 0, 0)]);
}
#[test]
fn selection_drops_lights_beyond_the_distance() {
let candidates = on_x_axis(&[1, 5, 50]);
let active = select_active_lights(candidates, Vec3::new(0.0, 0.5, 0.5), &budget(10, 6.0));
assert_eq!(active, vec![IVec3::new(1, 0, 0), IVec3::new(5, 0, 0)]);
}
#[test]
fn selection_with_zero_budget_or_negative_distance_is_empty() {
let candidates = on_x_axis(&[1, 2]);
assert!(select_active_lights(candidates.clone(), Vec3::ZERO, &budget(0, 100.0)).is_empty());
assert!(select_active_lights(candidates, Vec3::ZERO, &budget(4, -1.0)).is_empty());
}
#[test]
fn selection_treats_nan_distance_as_no_limit_and_skips_bad_positions() {
let mut candidates = on_x_axis(&[1, 1000]);
candidates.push((IVec3::new(7, 7, 7), Vec3::splat(f32::NAN)));
let active = select_active_lights(candidates, Vec3::ZERO, &budget(10, f32::NAN));
assert_eq!(active, vec![IVec3::new(1, 0, 0), IVec3::new(1000, 0, 0)]);
}
#[test]
fn selection_breaks_ties_by_voxel_position() {
let voxels = [
IVec3::new(3, 0, 0),
IVec3::new(-3, 0, 0),
IVec3::new(0, 3, 0),
IVec3::new(0, -3, 0),
];
let forward: Vec<(IVec3, Vec3)> = voxels.iter().map(|&v| (v, v.as_vec3())).collect();
let mut backward = forward.clone();
backward.reverse();
let a = select_active_lights(forward, Vec3::ZERO, &budget(2, f32::INFINITY));
let b = select_active_lights(backward, Vec3::ZERO, &budget(2, f32::INFINITY));
assert_eq!(a, b);
assert_eq!(a, vec![IVec3::new(-3, 0, 0), IVec3::new(0, -3, 0)]);
}
#[test]
fn a_record_becomes_one_point_light_at_its_position() {
let mut app = app();
let voxel = IVec3::new(2, 3, -4);
let light = PlacedLight {
color: Color::srgb(1.0, 0.5, 0.0),
intensity: 777.0,
range: 9.0,
radius: 0.25,
shadows_enabled: true,
offset: Vec3::new(0.0, 0.5, 0.0),
};
place(&mut app, voxel, light);
app.update();
app.update();
let mut query = app
.world_mut()
.query::<(&PlacedLightSource, &PointLight, &Transform)>();
let found: Vec<_> = query.iter(app.world()).collect();
assert_eq!(found.len(), 1);
let (source, point, transform) = found[0];
assert_eq!(source.voxel, voxel);
assert_eq!(point.color, light.color);
assert_eq!(point.intensity, 777.0);
assert_eq!(point.range, 9.0);
assert_eq!(point.radius, 0.25);
assert!(point.shadows_enabled);
assert_eq!(transform.translation, Vec3::new(2.5, 4.0, -3.5));
}
#[test]
fn no_records_means_no_entities() {
let mut app = app();
app.update();
assert!(shown(&mut app).is_empty());
}
#[test]
fn only_the_nearest_lights_within_the_budget_are_shown() {
let mut app = app();
app.insert_resource(budget(2, f32::INFINITY));
app.insert_resource(ViewerPosition {
position: Vec3::new(0.0, 0.5, 0.5),
});
for x in [1, 10, 20] {
place(&mut app, IVec3::new(x, 0, 0), PlacedLight::default());
}
app.update();
assert_eq!(
shown(&mut app),
vec![IVec3::new(1, 0, 0), IVec3::new(10, 0, 0)]
);
app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(25.0, 0.5, 0.5);
app.update();
assert_eq!(
shown(&mut app),
vec![IVec3::new(10, 0, 0), IVec3::new(20, 0, 0)]
);
}
#[test]
fn a_light_in_an_unloaded_chunk_is_despawned_and_returns_on_reload() {
let mut app = app();
let chunk = IVec3::new(1, 0, 0);
let chunk_entity = app.world_mut().spawn_empty().id();
let mut manager = ChunkManager::default();
manager.register(chunk, chunk_entity);
app.insert_resource(manager);
let voxel = IVec3::new(20, 3, 3); let elsewhere = IVec3::new(-5, 3, 3); place(&mut app, voxel, PlacedLight::default());
place(&mut app, elsewhere, PlacedLight::default());
app.update();
assert_eq!(shown(&mut app), vec![voxel]);
app.world_mut()
.resource_mut::<ChunkManager>()
.unregister(chunk);
app.update();
assert!(shown(&mut app).is_empty());
assert!(app.world().resource::<PlacedLights>().contains(voxel));
app.world_mut()
.resource_mut::<ChunkManager>()
.register(chunk, chunk_entity);
app.update();
assert_eq!(shown(&mut app), vec![voxel]);
}
#[test]
fn removing_a_record_despawns_its_light() {
let mut app = app();
let voxel = IVec3::new(0, 0, 0);
place(&mut app, voxel, PlacedLight::default());
place(&mut app, IVec3::new(1, 0, 0), PlacedLight::default());
app.update();
assert_eq!(shown(&mut app).len(), 2);
app.world_mut().resource_mut::<PlacedLights>().remove(voxel);
app.update();
assert_eq!(shown(&mut app), vec![IVec3::new(1, 0, 0)]);
app.world_mut().resource_mut::<PlacedLights>().clear();
app.update();
assert!(shown(&mut app).is_empty());
}
#[test]
fn changing_a_record_updates_the_same_entity() {
let mut app = app();
let voxel = IVec3::new(4, 4, 4);
place(&mut app, voxel, PlacedLight::default());
app.update();
let mut query = app
.world_mut()
.query_filtered::<Entity, With<PlacedLightSource>>();
let entity = query.single(app.world()).expect("one light");
{
let mut lights = app.world_mut().resource_mut::<PlacedLights>();
let record = lights.get_mut(voxel).unwrap();
record.intensity = 3.0;
record.offset = Vec3::new(0.25, 0.0, 0.0);
}
app.update();
assert_eq!(query.single(app.world()).expect("one light"), entity);
assert_eq!(
app.world().get::<PointLight>(entity).unwrap().intensity,
3.0
);
assert_eq!(
app.world().get::<Transform>(entity).unwrap().translation,
Vec3::new(4.75, 4.5, 4.5)
);
}
#[test]
fn a_budget_change_applies_on_the_next_frame() {
let mut app = app();
for x in [1, 2, 3] {
place(&mut app, IVec3::new(x, 0, 0), PlacedLight::default());
}
app.update();
assert_eq!(shown(&mut app).len(), 3);
app.world_mut()
.resource_mut::<PlacedLightBudget>()
.max_active = 1;
app.update();
assert_eq!(shown(&mut app), vec![IVec3::new(1, 0, 0)]);
app.world_mut()
.resource_mut::<PlacedLightBudget>()
.max_active = 0;
app.update();
assert!(shown(&mut app).is_empty());
}
}