Skip to main content

khora_data/ecs/systems/
asset_eviction.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! GPU asset eviction — reclaims orphaned GPU meshes/materials each frame.
16//!
17//! The insert-only projection never removes a `GpuMesh`/`GpuMaterial` once
18//! uploaded, so despawns and inline material edits leak GPU memory. This system
19//! runs the [`AssetEviction`] pass in [`TickPhase::Maintenance`] — after
20//! `ecs_maintenance` compacts orphan rows — to diff the cache against live
21//! entity references and free the orphans. The [`AssetEviction`] state and the
22//! [`AssetStore`] both live in the [`ServiceRegistry`], so the system fetches
23//! and ticks them without any manual wiring.
24
25use std::sync::{Arc, Mutex};
26
27use khora_core::lane::OutputDeck;
28use khora_core::renderer::GraphicsDevice;
29use khora_core::Runtime;
30
31use crate::ecs::{DataSystemRegistration, TickPhase, World};
32use crate::gpu::{AssetEviction, AssetStore};
33
34fn asset_eviction_system(world: &mut World, runtime: &Runtime, _deck: &mut OutputDeck) {
35    let Some(eviction) = runtime.resources.get::<Arc<Mutex<AssetEviction>>>() else {
36        return;
37    };
38    let Some(store) = runtime.resources.get::<AssetStore>() else {
39        return;
40    };
41    // No graphics device (e.g. headless tick) → nothing to reclaim yet.
42    let Some(device) = runtime.backends.get::<Arc<dyn GraphicsDevice>>() else {
43        return;
44    };
45    if let Ok(mut guard) = eviction.lock() {
46        guard.tick(store, world, device.as_ref());
47    }
48}
49
50inventory::submit! {
51    DataSystemRegistration {
52        name: "asset_eviction",
53        phase: TickPhase::Maintenance,
54        run: asset_eviction_system,
55        // After `ecs_maintenance` (order_hint 0) so orphan rows are compacted
56        // first; either order is correct since the query skips orphan rows.
57        order_hint: 1,
58        runs_after: &["ecs_maintenance"],
59    }
60}