Skip to content

Commit 8b9aa2c

Browse files
committed
Freeing memory held by visible entities vector (#3009)
- Freeing unused memory held by visible entities - Fixed comment style # Objective With Rust 1.56 it's possible to shrink vectors to a specified capacity. Visibility system had a comment before asking for that feature to free unused memory by a vector if its capacity is two times larger than the length. ## Solution Shrinking the vector of visible entities to the nearest power of 2 elements next to `len()`, if capacity exceeds it more than two times.
1 parent 7540328 commit 8b9aa2c

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

crates/bevy_pbr/src/light.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1557,6 +1557,22 @@ pub fn check_light_mesh_visibility(
15571557
(Without<NotShadowCaster>, Without<DirectionalLight>),
15581558
>,
15591559
) {
1560+
fn shrink_entities(visible_entities: &mut VisibleEntities) {
1561+
// Check that visible entities capacity() is no more than two times greater than len()
1562+
let capacity = visible_entities.entities.capacity();
1563+
let reserved = capacity
1564+
.checked_div(visible_entities.entities.len())
1565+
.map_or(0, |reserve| {
1566+
if reserve > 2 {
1567+
capacity / (reserve / 2)
1568+
} else {
1569+
capacity
1570+
}
1571+
});
1572+
1573+
visible_entities.entities.shrink_to(reserved);
1574+
}
1575+
15601576
// Directional lights
15611577
for (
15621578
directional_light,
@@ -1598,8 +1614,7 @@ pub fn check_light_mesh_visibility(
15981614
visible_entities.entities.push(entity);
15991615
}
16001616

1601-
// TODO: check for big changes in visible entities len() vs capacity() (ex: 2x) and resize
1602-
// to prevent holding unneeded memory
1617+
shrink_entities(&mut visible_entities);
16031618
}
16041619

16051620
for visible_lights in &visible_point_lights {
@@ -1670,11 +1685,12 @@ pub fn check_light_mesh_visibility(
16701685
}
16711686
}
16721687

1673-
// TODO: check for big changes in visible entities len() vs capacity() (ex: 2x) and resize
1674-
// to prevent holding unneeded memory
1688+
for visible_entities in cubemap_visible_entities.iter_mut() {
1689+
shrink_entities(visible_entities);
1690+
}
16751691
}
16761692

1677-
// spot lights
1693+
// Spot lights
16781694
if let Ok((point_light, transform, frustum, mut visible_entities, maybe_view_mask)) =
16791695
spot_lights.get_mut(light_entity)
16801696
{
@@ -1726,8 +1742,7 @@ pub fn check_light_mesh_visibility(
17261742
}
17271743
}
17281744

1729-
// TODO: check for big changes in visible entities len() vs capacity() (ex: 2x) and resize
1730-
// to prevent holding unneeded memory
1745+
shrink_entities(&mut visible_entities);
17311746
}
17321747
}
17331748
}

0 commit comments

Comments
 (0)