use super::{
Arc, Color, Error, Fog3d, Lighting3d, Mesh3d, MeshStyle3d, NEXT_SCENE3D_ID, Ordering,
RetainedMesh3d, Texture3dError, TextureMaterial3d, Transform3d, WireframeStyle3d, fmt, texture,
validate_mesh_source_style, validate_mesh_style, validate_scene3d_transform,
};
#[cfg(test)]
mod tests;
#[cfg(test)]
pub(super) use tests::verify_scene_accounting;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Object3dId {
pub(super) scene_id: u64,
pub(super) object_id: u64,
slot: usize,
}
impl Object3dId {
pub const fn get(self) -> u64 {
self.object_id
}
}
#[derive(Clone)]
pub struct Mesh3dInstance {
pub(super) id: Object3dId,
pub(super) mesh: RetainedMesh3d,
pub(super) transform: Transform3d,
pub(super) style: MeshStyle3d,
pub(super) visible: bool,
}
impl Mesh3dInstance {
fn new(
id: Object3dId,
mesh: &RetainedMesh3d,
transform: Transform3d,
style: MeshStyle3d,
) -> Self {
Self {
id,
mesh: mesh.clone(),
transform,
style,
visible: true,
}
}
pub const fn id(&self) -> Object3dId {
self.id
}
pub const fn mesh(&self) -> &RetainedMesh3d {
&self.mesh
}
pub const fn transform(&self) -> Transform3d {
self.transform
}
pub const fn style(&self) -> MeshStyle3d {
self.style
}
pub const fn is_visible(&self) -> bool {
self.visible
}
pub const fn wireframe(&self) -> Option<WireframeStyle3d> {
self.style.wireframe_style()
}
}
pub struct Scene3d {
pub(super) scene_id: u64,
pub(super) background: Color,
pub(super) lighting: Lighting3d,
pub(super) fog: Option<Fog3d>,
pub(super) instances: Vec<Mesh3dInstance>,
pub(super) next_object_id: u64,
pub(super) renderer_identity: Option<Arc<()>>,
slots: Vec<ObjectSlot>,
free_slot: Option<usize>,
resources: Vec<ResourceUsage>,
resource_totals: ResourceTotals,
visible_count: usize,
budget: Scene3dBudget,
}
#[derive(Clone)]
struct ObjectSlot {
dense_index: Option<usize>,
next_free: Option<usize>,
}
#[derive(Clone, Copy)]
struct ResourceUsage {
key: (u8, usize),
references: usize,
bytes: usize,
}
#[derive(Default)]
struct ResourceTotals {
bytes: [usize; 4],
counts: [usize; 4],
}
pub(super) struct DynamicSceneMeshChange {
index: usize,
outgoing: [ResourceUsage; 4],
resources: Option<Vec<ResourceUsage>>,
}
impl DynamicSceneMeshChange {
pub(super) fn object_index(&self) -> usize {
self.index
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dBudget {
max_objects: usize,
max_storage_bytes: usize,
max_mesh_cpu_bytes: usize,
max_mesh_gpu_bytes: usize,
max_texture_cpu_bytes: usize,
max_texture_gpu_bytes: usize,
}
impl Scene3dBudget {
pub fn new(
max_objects: usize,
max_storage_bytes: usize,
max_mesh_cpu_bytes: usize,
max_mesh_gpu_bytes: usize,
) -> Result<Self, Scene3dError> {
if [
max_objects,
max_storage_bytes,
max_mesh_cpu_bytes,
max_mesh_gpu_bytes,
]
.contains(&0)
{
return Err(Scene3dError::InvalidBudget);
}
Ok(Self {
max_objects,
max_storage_bytes,
max_mesh_cpu_bytes,
max_mesh_gpu_bytes,
max_texture_cpu_bytes: 64 * 1024 * 1024,
max_texture_gpu_bytes: 64 * 1024 * 1024,
})
}
pub const fn max_objects(self) -> usize {
self.max_objects
}
pub const fn max_storage_bytes(self) -> usize {
self.max_storage_bytes
}
pub const fn max_mesh_cpu_bytes(self) -> usize {
self.max_mesh_cpu_bytes
}
pub const fn max_mesh_gpu_bytes(self) -> usize {
self.max_mesh_gpu_bytes
}
pub const fn with_texture_limits(mut self, cpu_bytes: usize, gpu_bytes: usize) -> Self {
self.max_texture_cpu_bytes = cpu_bytes;
self.max_texture_gpu_bytes = gpu_bytes;
self
}
pub const fn max_texture_cpu_bytes(self) -> usize {
self.max_texture_cpu_bytes
}
pub const fn max_texture_gpu_bytes(self) -> usize {
self.max_texture_gpu_bytes
}
}
impl Default for Scene3dBudget {
fn default() -> Self {
Self {
max_objects: 65_536,
max_storage_bytes: 64 * 1024 * 1024,
max_mesh_cpu_bytes: 256 * 1024 * 1024,
max_mesh_gpu_bytes: 256 * 1024 * 1024,
max_texture_cpu_bytes: 64 * 1024 * 1024,
max_texture_gpu_bytes: 64 * 1024 * 1024,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scene3dBudgetResource {
TextureCpuBytes,
TextureGpuBytes,
Objects,
StorageBytes,
MeshCpuBytes,
MeshGpuBytes,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dStatistics {
object_count: usize,
slot_capacity: usize,
storage_bytes: usize,
mesh_count: usize,
mesh_cpu_bytes: usize,
mesh_gpu_bytes: usize,
texture_count: usize,
texture_cpu_bytes: usize,
texture_gpu_bytes: usize,
}
impl Scene3dStatistics {
pub const fn texture_count(self) -> usize {
self.texture_count
}
pub const fn texture_cpu_bytes(self) -> usize {
self.texture_cpu_bytes
}
pub const fn texture_gpu_bytes(self) -> usize {
self.texture_gpu_bytes
}
pub const fn object_count(self) -> usize {
self.object_count
}
pub const fn slot_capacity(self) -> usize {
self.slot_capacity
}
pub const fn storage_bytes(self) -> usize {
self.storage_bytes
}
pub const fn mesh_count(self) -> usize {
self.mesh_count
}
pub const fn mesh_cpu_bytes(self) -> usize {
self.mesh_cpu_bytes
}
pub const fn mesh_gpu_bytes(self) -> usize {
self.mesh_gpu_bytes
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dMeshUpdateReport {
statistics: Scene3dStatistics,
peak_mesh_cpu_bytes: usize,
peak_mesh_gpu_bytes: usize,
peak_texture_cpu_bytes: usize,
peak_texture_gpu_bytes: usize,
}
impl Scene3dMeshUpdateReport {
pub const fn peak_texture_cpu_bytes(self) -> usize {
self.peak_texture_cpu_bytes
}
pub const fn peak_texture_gpu_bytes(self) -> usize {
self.peak_texture_gpu_bytes
}
pub const fn statistics(self) -> Scene3dStatistics {
self.statistics
}
pub const fn peak_mesh_cpu_bytes(self) -> usize {
self.peak_mesh_cpu_bytes
}
pub const fn peak_mesh_gpu_bytes(self) -> usize {
self.peak_mesh_gpu_bytes
}
}
impl Scene3d {
pub fn new(background: Color) -> Result<Self, Scene3dError> {
Self::with_budget(background, Scene3dBudget::default())
}
pub fn with_budget(background: Color, budget: Scene3dBudget) -> Result<Self, Scene3dError> {
if !background.is_normalized() || background.alpha() != 1.0 {
return Err(Scene3dError::InvalidBackground);
}
Self::with_alpha_background_and_budget(background, budget)
}
pub fn with_alpha_background(background: Color) -> Result<Self, Scene3dError> {
Self::with_alpha_background_and_budget(background, Scene3dBudget::default())
}
pub fn with_alpha_background_and_budget(
background: Color,
budget: Scene3dBudget,
) -> Result<Self, Scene3dError> {
if !background.is_normalized() {
return Err(Scene3dError::InvalidBackground);
}
let scene_id = NEXT_SCENE3D_ID
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
current.checked_add(1)
})
.map_err(|_| Scene3dError::SceneIdExhausted)?;
Ok(Self {
scene_id,
background,
lighting: Lighting3d::default(),
fog: None,
instances: Vec::new(),
next_object_id: 0,
renderer_identity: None,
slots: Vec::new(),
free_slot: None,
resources: Vec::new(),
resource_totals: ResourceTotals::default(),
visible_count: 0,
budget,
})
}
pub fn set_lighting(&mut self, lighting: Lighting3d) {
self.lighting = lighting;
}
pub const fn lighting(&self) -> Lighting3d {
self.lighting
}
pub fn set_fog(&mut self, fog: Option<Fog3d>) {
self.fog = fog;
}
pub const fn fog(&self) -> Option<Fog3d> {
self.fog
}
pub fn try_push(
&mut self,
mesh: &RetainedMesh3d,
transform: Transform3d,
style: MeshStyle3d,
) -> Result<Object3dId, Scene3dError> {
validate_mesh_style(mesh, style)?;
validate_scene3d_transform(transform)?;
self.validate_mesh_owner(mesh)?;
check_scene_limit(
Scene3dBudgetResource::Objects,
self.budget.max_objects,
self.instances.len().saturating_add(1),
)?;
let next_object_id = self
.next_object_id
.checked_add(1)
.ok_or(Scene3dError::ObjectIdExhausted)?;
let keys = mesh_resources(mesh);
self.validate_resource_change(&keys, None)?;
self.reserve_storage(
1,
usize::from(self.free_slot.is_none()),
self.missing_resources(&keys),
)?;
let slot = self.free_slot.unwrap_or(self.slots.len());
let id = Object3dId {
scene_id: self.scene_id,
object_id: self.next_object_id,
slot,
};
if let Some(free) = self.free_slot {
self.free_slot = self.slots[free].next_free;
self.slots[free] = ObjectSlot {
dense_index: Some(self.instances.len()),
next_free: None,
};
} else {
self.slots.push(ObjectSlot {
dense_index: Some(self.instances.len()),
next_free: None,
});
}
for resource in keys {
self.add_resource(resource);
}
self.renderer_identity = Some(Arc::clone(&mesh.renderer_identity));
self.instances
.push(Mesh3dInstance::new(id, mesh, transform, style));
self.visible_count += 1;
self.next_object_id = next_object_id;
Ok(id)
}
pub const fn background(&self) -> Color {
self.background
}
pub fn set_background(&mut self, background: Color) -> Result<(), Scene3dError> {
if !background.is_normalized() {
return Err(Scene3dError::InvalidBackground);
}
self.background = background;
Ok(())
}
pub fn instances(&self) -> &[Mesh3dInstance] {
&self.instances
}
pub fn object_count(&self) -> usize {
self.instances.len()
}
pub const fn budget(&self) -> Scene3dBudget {
self.budget
}
pub fn statistics(&self) -> Scene3dStatistics {
Scene3dStatistics {
texture_count: self.resource_totals.counts[3],
texture_cpu_bytes: self.resource_totals.bytes[2],
texture_gpu_bytes: self.resource_totals.bytes[3],
object_count: self.instances.len(),
slot_capacity: self.slots.capacity(),
storage_bytes: storage_bytes(
self.instances.capacity(),
self.slots.capacity(),
self.resources.capacity(),
),
mesh_count: self.resource_totals.counts[1],
mesh_cpu_bytes: self.resource_totals.bytes[0],
mesh_gpu_bytes: self.resource_totals.bytes[1],
}
}
pub fn instance(&self, object_id: Object3dId) -> Result<&Mesh3dInstance, Scene3dError> {
let index = self.instance_index(object_id)?;
Ok(&self.instances[index])
}
pub fn remove(&mut self, object_id: Object3dId) -> Result<Mesh3dInstance, Scene3dError> {
let index = self.instance_index(object_id)?;
let removed = self.instances.remove(index);
for instance in &self.instances[index..] {
if let Some(dense) = &mut self.slots[instance.id.slot].dense_index {
*dense -= 1;
}
}
self.slots[object_id.slot] = ObjectSlot {
dense_index: None,
next_free: self.free_slot,
};
self.free_slot = Some(object_id.slot);
for resource in mesh_resources(&removed.mesh) {
self.remove_resource(resource.key);
}
if removed.visible {
self.visible_count -= 1;
}
Ok(removed)
}
pub fn set_texture_material(
&mut self,
object_id: Object3dId,
material: Option<&TextureMaterial3d>,
) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
let mesh = self.instance(object_id)?.mesh();
let replacement = match material {
Some(material) => texture::attach_material(&mesh.renderer_identity, mesh, material)
.map_err(Scene3dError::Texture)?,
None => mesh.without_material(),
};
self.set_mesh(object_id, &replacement)
}
pub fn set_mesh(
&mut self,
object_id: Object3dId,
mesh: &RetainedMesh3d,
) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
let index = self.instance_index(object_id)?;
self.validate_mesh_owner(mesh)?;
validate_mesh_style(mesh, self.instances[index].style)?;
let incoming = mesh_resources(mesh);
let outgoing = mesh_resources(&self.instances[index].mesh);
let [
peak_mesh_cpu_bytes,
peak_mesh_gpu_bytes,
peak_texture_cpu_bytes,
peak_texture_gpu_bytes,
] = self.validate_resource_change(&incoming, Some(&outgoing))?;
let removed_keys = outgoing
.iter()
.filter(|resource| {
!incoming.iter().any(|r| r.key == resource.key)
&& self
.resources
.binary_search_by_key(&resource.key, |r| r.key)
.ok()
.is_some_and(|i| self.resources[i].references == 1)
})
.count();
self.reserve_storage(
0,
0,
self.missing_resources(&incoming)
.saturating_sub(removed_keys),
)?;
for resource in outgoing {
self.remove_resource(resource.key);
}
for resource in incoming {
self.add_resource(resource);
}
self.instances[index].mesh = mesh.clone();
Ok(Scene3dMeshUpdateReport {
statistics: self.statistics(),
peak_mesh_cpu_bytes,
peak_mesh_gpu_bytes,
peak_texture_cpu_bytes,
peak_texture_gpu_bytes,
})
}
pub(super) fn prepare_dynamic_mesh_change(
&self,
object_id: Object3dId,
source: &Mesh3d,
gpu_bytes: usize,
replace_buffers: bool,
) -> Result<DynamicSceneMeshChange, Scene3dError> {
let index = self.instance_index(object_id)?;
validate_mesh_source_style(source, self.instances[index].style)?;
let outgoing = mesh_resources(&self.instances[index].mesh);
let mut incoming = outgoing;
incoming[0].key.1 = source.vertices().as_ptr() as usize;
incoming[0].bytes = source.recovery_memory_bytes();
if replace_buffers {
incoming[1].key.1 = 0;
}
incoming[1].bytes = gpu_bytes;
self.prepare_resource_change(index, incoming, outgoing)
}
pub(super) fn prepare_dynamic_texture_change(
&self,
object_id: Object3dId,
cpu_bytes: usize,
gpu_bytes: usize,
detached: bool,
) -> Result<DynamicSceneMeshChange, Scene3dError> {
let index = self.instance_index(object_id)?;
let outgoing = mesh_resources(&self.instances[index].mesh);
let mut incoming = outgoing;
incoming[2].key.1 = 0;
incoming[2].bytes = cpu_bytes;
incoming[3].bytes = gpu_bytes;
if detached {
incoming[3].key.1 = 0;
}
self.prepare_resource_change(index, incoming, outgoing)
}
fn prepare_resource_change(
&self,
index: usize,
incoming: [ResourceUsage; 4],
outgoing: [ResourceUsage; 4],
) -> Result<DynamicSceneMeshChange, Scene3dError> {
self.validate_resource_change(&incoming, Some(&outgoing))?;
let retired = outgoing
.iter()
.filter(|resource| {
!incoming
.iter()
.any(|candidate| candidate.key == resource.key)
&& self
.resources
.binary_search_by_key(&resource.key, |entry| entry.key)
.ok()
.is_some_and(|index| self.resources[index].references == 1)
})
.count();
let additional = self.missing_resources(&incoming).saturating_sub(retired);
let mut capacity = planned_capacity(
&self.resources,
additional,
self.budget.max_objects.saturating_mul(4),
);
if storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity)
> self.budget.max_storage_bytes
{
capacity = self
.resources
.capacity()
.max(self.resources.len().saturating_add(additional));
}
check_scene_limit(
Scene3dBudgetResource::StorageBytes,
self.budget.max_storage_bytes,
storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity),
)?;
let resources = replacement_capacity(&self.resources, capacity)?;
check_scene_limit(
Scene3dBudgetResource::StorageBytes,
self.budget.max_storage_bytes,
storage_bytes(
self.instances.capacity(),
self.slots.capacity(),
resources
.as_ref()
.map_or(self.resources.capacity(), Vec::capacity),
),
)?;
Ok(DynamicSceneMeshChange {
index,
outgoing,
resources,
})
}
pub(super) fn commit_dynamic_mesh_change(
&mut self,
change: DynamicSceneMeshChange,
mesh: RetainedMesh3d,
) -> Scene3dStatistics {
if let Some(resources) = change.resources {
self.resources = resources;
}
for resource in change.outgoing {
self.remove_resource(resource.key);
}
for resource in mesh_resources(&mesh) {
self.add_resource(resource);
}
self.instances[change.index].mesh = mesh;
self.statistics()
}
pub(super) fn commit_dynamic_texture_change(&mut self, change: DynamicSceneMeshChange) {
if let Some(resources) = change.resources {
self.resources = resources;
}
for resource in change.outgoing {
self.remove_resource(resource.key);
}
for resource in mesh_resources(&self.instances[change.index].mesh) {
self.add_resource(resource);
}
}
pub fn visible_object_count(&self) -> usize {
self.visible_count
}
pub fn set_transform(
&mut self,
object_id: Object3dId,
transform: Transform3d,
) -> Result<(), Scene3dError> {
validate_scene3d_transform(transform)?;
let instance = self.instance_mut(object_id)?;
instance.transform = transform;
Ok(())
}
pub fn set_style(
&mut self,
object_id: Object3dId,
style: MeshStyle3d,
) -> Result<(), Scene3dError> {
let instance = self.instance_mut(object_id)?;
validate_mesh_style(&instance.mesh, style)?;
instance.style = style;
Ok(())
}
pub fn set_visible(
&mut self,
object_id: Object3dId,
visible: bool,
) -> Result<(), Scene3dError> {
let index = self.instance_index(object_id)?;
let instance = &mut self.instances[index];
if instance.visible != visible {
if visible {
self.visible_count += 1;
} else {
self.visible_count -= 1;
}
instance.visible = visible;
}
Ok(())
}
pub fn set_wireframe(
&mut self,
object_id: Object3dId,
wireframe: Option<WireframeStyle3d>,
) -> Result<(), Scene3dError> {
let instance = self.instance_mut(object_id)?;
let surface = instance.style.surface_style();
let style = match (surface, wireframe) {
(Some(surface), Some(wireframe)) => {
MeshStyle3d::surface(surface).with_wireframe(wireframe)
}
(Some(surface), None) => MeshStyle3d::surface(surface),
(None, Some(wireframe)) => MeshStyle3d::wireframe(wireframe),
(None, None) => return Err(Scene3dError::EmptyStyle),
};
validate_mesh_style(&instance.mesh, style)?;
instance.style = style;
Ok(())
}
fn instance_mut(&mut self, object_id: Object3dId) -> Result<&mut Mesh3dInstance, Scene3dError> {
let index = self.instance_index(object_id)?;
Ok(&mut self.instances[index])
}
fn instance_index(&self, object_id: Object3dId) -> Result<usize, Scene3dError> {
let index = (object_id.scene_id == self.scene_id)
.then_some(())
.and_then(|()| self.slots.get(object_id.slot))
.and_then(|slot| slot.dense_index)
.filter(|&index| {
self.instances
.get(index)
.is_some_and(|instance| instance.id == object_id)
});
index.ok_or(Scene3dError::ObjectNotFound { object_id })
}
fn validate_mesh_owner(&self, mesh: &RetainedMesh3d) -> Result<(), Scene3dError> {
if mesh
.material()
.is_some_and(|material| !material.texture().belongs_to(&mesh.renderer_identity))
{
return Err(Scene3dError::RendererMismatch);
}
if self
.renderer_identity
.as_ref()
.is_some_and(|identity| !Arc::ptr_eq(identity, &mesh.renderer_identity))
{
Err(Scene3dError::RendererMismatch)
} else {
Ok(())
}
}
fn missing_resources(&self, incoming: &[ResourceUsage]) -> usize {
incoming
.iter()
.filter(|r| {
r.bytes > 0
&& self
.resources
.binary_search_by_key(&r.key, |r| r.key)
.is_err()
})
.count()
}
fn add_resource(&mut self, resource: ResourceUsage) {
if resource.bytes == 0 {
return;
}
match self
.resources
.binary_search_by_key(&resource.key, |r| r.key)
{
Ok(index) => self.resources[index].references += 1,
Err(index) => {
self.resources.insert(index, resource);
let category = resource.key.0 as usize;
self.resource_totals.bytes[category] += resource.bytes;
self.resource_totals.counts[category] += 1;
}
}
}
fn remove_resource(&mut self, key: (u8, usize)) {
if let Ok(index) = self.resources.binary_search_by_key(&key, |r| r.key) {
self.resources[index].references -= 1;
if self.resources[index].references == 0 {
let removed = self.resources.remove(index);
let category = removed.key.0 as usize;
self.resource_totals.bytes[category] -= removed.bytes;
self.resource_totals.counts[category] -= 1;
}
}
}
fn validate_resource_change(
&self,
incoming: &[ResourceUsage],
outgoing: Option<&[ResourceUsage]>,
) -> Result<[usize; 4], Scene3dError> {
let mut bytes = self.resource_totals.bytes;
for resource in incoming {
if self
.resources
.binary_search_by_key(&resource.key, |r| r.key)
.is_err()
{
bytes[resource.key.0 as usize] =
bytes[resource.key.0 as usize].saturating_add(resource.bytes);
}
}
let peak = bytes;
for resource in outgoing.into_iter().flatten() {
if !incoming.iter().any(|r| r.key == resource.key)
&& self
.resources
.binary_search_by_key(&resource.key, |r| r.key)
.ok()
.is_some_and(|i| self.resources[i].references == 1)
{
bytes[resource.key.0 as usize] -= resource.bytes;
}
}
check_scene_limit(
Scene3dBudgetResource::MeshCpuBytes,
self.budget.max_mesh_cpu_bytes,
bytes[0],
)?;
check_scene_limit(
Scene3dBudgetResource::MeshGpuBytes,
self.budget.max_mesh_gpu_bytes,
bytes[1],
)?;
check_scene_limit(
Scene3dBudgetResource::TextureCpuBytes,
self.budget.max_texture_cpu_bytes,
bytes[2],
)?;
check_scene_limit(
Scene3dBudgetResource::TextureGpuBytes,
self.budget.max_texture_gpu_bytes,
bytes[3],
)?;
Ok(peak)
}
fn reserve_storage(
&mut self,
instances: usize,
slots: usize,
resources: usize,
) -> Result<(), Scene3dError> {
let mut capacities = [
planned_capacity(&self.instances, instances, self.budget.max_objects),
planned_capacity(&self.slots, slots, self.budget.max_objects),
planned_capacity(
&self.resources,
resources,
self.budget.max_objects.saturating_mul(4),
),
];
if storage_bytes(capacities[0], capacities[1], capacities[2])
> self.budget.max_storage_bytes
{
capacities = [
self.instances
.capacity()
.max(self.instances.len().saturating_add(instances)),
self.slots
.capacity()
.max(self.slots.len().saturating_add(slots)),
self.resources
.capacity()
.max(self.resources.len().saturating_add(resources)),
];
}
let planned_bytes = storage_bytes(capacities[0], capacities[1], capacities[2]);
check_scene_limit(
Scene3dBudgetResource::StorageBytes,
self.budget.max_storage_bytes,
planned_bytes,
)?;
let new_instances = replacement_capacity(&self.instances, capacities[0])?;
let new_slots = replacement_capacity(&self.slots, capacities[1])?;
let new_resources = replacement_capacity(&self.resources, capacities[2])?;
let bytes = storage_bytes(
new_instances
.as_ref()
.map_or(self.instances.capacity(), Vec::capacity),
new_slots
.as_ref()
.map_or(self.slots.capacity(), Vec::capacity),
new_resources
.as_ref()
.map_or(self.resources.capacity(), Vec::capacity),
);
check_scene_limit(
Scene3dBudgetResource::StorageBytes,
self.budget.max_storage_bytes,
bytes,
)?;
if let Some(values) = new_instances {
self.instances = values;
}
if let Some(values) = new_slots {
self.slots = values;
}
if let Some(values) = new_resources {
self.resources = values;
}
Ok(())
}
pub(super) fn rebuild_resource_keys(&mut self) {
self.resources.clear();
self.resource_totals = ResourceTotals::default();
self.visible_count = 0;
for index in 0..self.instances.len() {
for resource in mesh_resources(&self.instances[index].mesh) {
self.add_resource(resource);
}
if self.instances[index].visible {
self.visible_count += 1;
}
}
}
}
fn mesh_resources(mesh: &RetainedMesh3d) -> [ResourceUsage; 4] {
[
ResourceUsage {
key: (0, mesh.source.vertices().as_ptr() as usize),
references: 1,
bytes: mesh.recovery_memory_bytes(),
},
ResourceUsage {
key: (1, Arc::as_ptr(&mesh.vertex_buffer) as usize),
references: 1,
bytes: mesh.gpu_allocation_bytes(),
},
ResourceUsage {
key: (
2,
mesh.material()
.map_or(0, |material| material.texture().identity_key()),
),
references: 1,
bytes: mesh
.material()
.map_or(0, |material| material.texture().recovery_memory_bytes()),
},
ResourceUsage {
key: (
3,
mesh.material()
.map_or(0, |material| material.texture().identity_key()),
),
references: 1,
bytes: mesh
.material()
.map_or(0, |material| material.texture().gpu_allocation_bytes()),
},
]
}
fn check_scene_limit(
resource: Scene3dBudgetResource,
limit: usize,
actual: usize,
) -> Result<(), Scene3dError> {
if actual > limit {
Err(Scene3dError::BudgetExceeded {
resource,
limit,
actual,
})
} else {
Ok(())
}
}
fn storage_bytes(instances: usize, slots: usize, resources: usize) -> usize {
instances
.saturating_mul(std::mem::size_of::<Mesh3dInstance>())
.saturating_add(slots.saturating_mul(std::mem::size_of::<ObjectSlot>()))
.saturating_add(resources.saturating_mul(std::mem::size_of::<ResourceUsage>()))
}
fn replacement_capacity<T: Clone>(
current: &Vec<T>,
capacity: usize,
) -> Result<Option<Vec<T>>, Scene3dError> {
if capacity <= current.capacity() {
return Ok(None);
}
let mut values = Vec::new();
values
.try_reserve_exact(capacity)
.map_err(|_| Scene3dError::AllocationFailed {
requested_bytes: capacity.saturating_mul(std::mem::size_of::<T>()),
})?;
values.extend_from_slice(current);
Ok(Some(values))
}
fn planned_capacity<T>(current: &Vec<T>, additional: usize, maximum: usize) -> usize {
let needed = current.len().saturating_add(additional);
if needed <= current.capacity() {
current.capacity()
} else {
needed
.max(current.capacity().saturating_mul(2))
.min(maximum)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scene3dError {
Texture(Texture3dError),
MissingNormals,
InvalidBudget,
RendererMismatch,
BudgetExceeded {
resource: Scene3dBudgetResource,
limit: usize,
actual: usize,
},
InvalidBackground,
EmptyStyle,
StyleHasNoMatchingGeometry,
InvalidTransform,
SceneIdExhausted,
ObjectIdExhausted,
AllocationFailed {
requested_bytes: usize,
},
ObjectNotFound {
object_id: Object3dId,
},
}
impl fmt::Display for Scene3dError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Texture(error) => write!(formatter, "3D scene material: {error}"),
Self::MissingNormals => write!(
formatter,
"Lambert surface requires application-supplied model normals"
),
Self::InvalidBudget => write!(formatter, "3D scene budget limits must be nonzero"),
Self::RendererMismatch => {
write!(formatter, "3D mesh belongs to another renderer generation")
}
Self::BudgetExceeded {
resource,
limit,
actual,
} => write!(
formatter,
"3D scene {resource:?} budget exceeded: {actual} > {limit}"
),
Self::InvalidBackground => write!(
formatter,
"3D scene background must be normalized; legacy constructors also require opaque alpha"
),
Self::EmptyStyle => write!(formatter, "3D object requires a surface or wireframe"),
Self::StyleHasNoMatchingGeometry => write!(
formatter,
"3D object style has no matching triangles or display edges"
),
Self::InvalidTransform => {
write!(
formatter,
"3D model transform is outside the portable shader envelope"
)
}
Self::SceneIdExhausted => write!(formatter, "3D scene identifiers exhausted"),
Self::ObjectIdExhausted => write!(formatter, "3D scene object identifiers exhausted"),
Self::AllocationFailed { requested_bytes } => write!(
formatter,
"could not reserve {requested_bytes} bytes for another 3D scene object"
),
Self::ObjectNotFound { object_id } => write!(
formatter,
"3D scene object {} does not exist in this scene",
object_id.get()
),
}
}
}
impl Error for Scene3dError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Texture(error) => Some(error),
_ => None,
}
}
}