Skip to main content

voxel_framework/generator/
systems.rs

1//! Systems that implement the two-stage async chunk generation pipeline.
2//!
3//! # Pipeline overview
4//!
5//! Stage 1 — **[`chunk_request_system`]**: runs first in [`super::GeneratorSystems`].
6//! It drains [`ChunkLoadRequest`] messages and for each one:
7//!
8//! - Attempts a synchronous disk restore when [`PersistenceConfig`] is present.
9//!   On success the entity is spawned and [`ChunkModified`] is emitted
10//!   immediately — no async task is needed.
11//! - On a cache miss (or when persistence is absent) it clones the
12//!   [`super::GeneratorResource`]'s `Arc`, spawns a new bare entity, and
13//!   offloads the [`super::ChunkGenerator::generate`] call to
14//!   [`AsyncComputeTaskPool`].  The returned [`bevy::tasks::Task`] is stored
15//!   as a [`ChunkTask<V>`] component.
16//!
17//! Stage 2 — **[`chunk_task_poll_system`]**: runs second, chained after stage 1.
18//! It iterates every entity with a [`ChunkTask<V>`] component and calls
19//! `poll_once` — a non-blocking single-frame check.  When a task resolves:
20//!
21//! - The [`ChunkTask<V>`] component is removed.
22//! - The generated [`Chunk<V>`] and [`ChunkCoordComp`] are inserted.
23//! - [`ChunkManager::register`] is called to make the chunk queryable.
24//! - [`ChunkModified`] is emitted so [`crate::mesh::systems::chunk_mesh_system`]
25//!   builds geometry on the same frame.
26//!
27//! The two-stage design keeps the main thread free: generation work happens
28//! entirely on worker threads, and the main thread only pays a `poll_once` cost
29//! per in-flight task per frame.
30
31use bevy::prelude::*;
32use bevy::tasks::{AsyncComputeTaskPool, Task, block_on, poll_once};
33
34use crate::chunk::{Chunk, ChunkCoord, ChunkCoordComp};
35use crate::voxel::VoxelType;
36use crate::world::{
37    ChunkLoadRequest, ChunkManager, ChunkModified, PersistenceConfig, try_load_chunk,
38};
39
40use super::GeneratorResource;
41
42// ─── ChunkTask ────────────────────────────────────────────────────────────────
43
44/// ECS component that tracks an in-flight async chunk generation task.
45///
46/// [`chunk_request_system`] attaches this component to the chunk entity when
47/// it offloads generation to [`AsyncComputeTaskPool`].  The entity has no other
48/// meaningful components until [`chunk_task_poll_system`] resolves the task and
49/// replaces this component with the fully populated [`Chunk<V>`].
50///
51/// The inner [`Task`] yields `(ChunkCoord, Chunk<V>)` so the coord is
52/// available after the task completes without requiring an additional query.
53#[derive(Component)]
54pub struct ChunkTask<V: VoxelType> {
55    /// The async task producing a fully populated [`Chunk<V>`].
56    pub task: Task<(ChunkCoord, Chunk<V>)>,
57}
58
59// ─── chunk_request_system ────────────────────────────────────────────────────
60
61/// Responds to [`ChunkLoadRequest`] messages by either loading from disk or
62/// spawning async generation tasks.
63///
64/// For each incoming request this system:
65/// 1. If [`PersistenceConfig`] is present, attempts to load the chunk from
66///    disk via [`try_load_chunk`].  On success the chunk entity is spawned
67///    immediately (no async task), the manager is updated, and a
68///    [`ChunkModified`] message is emitted so the mesh system builds geometry.
69/// 2. If no saved file exists (or [`PersistenceConfig`] is absent), the
70///    original async generation path is used:
71///    a. Spawns a new Bevy entity.
72///    b. Clones the generator `Arc` so the task owns it without holding the `World`.
73///    c. Offloads chunk generation to [`AsyncComputeTaskPool`], attaching the
74///    returned [`Task`] as a [`ChunkTask<V>`] component.
75///
76/// The entity produced by the async path has no other components until
77/// [`chunk_task_poll_system`] completes the task and attaches the real
78/// [`Chunk<V>`] data.
79pub fn chunk_request_system<V: VoxelType>(
80    mut commands: Commands,
81    mut load_reader: MessageReader<ChunkLoadRequest>,
82    generator_res: Option<Res<GeneratorResource<V>>>,
83    persistence_config: Option<Res<PersistenceConfig>>,
84    mut manager: ResMut<ChunkManager>,
85    mut modified_writer: MessageWriter<ChunkModified>,
86) {
87    crate::profile_span!("voxel::generator::dispatch");
88    let pool = AsyncComputeTaskPool::get();
89
90    for &ChunkLoadRequest(coord) in load_reader.read() {
91        // ── 1. Try loading from disk first ───────────────────────────────
92        if let Some(ref cfg) = persistence_config
93            && let Some(chunk) = try_load_chunk::<V>(coord, &cfg.save_dir)
94        {
95            // Disk hit — spawn entity directly without an async task.
96            let entity = commands.spawn((chunk, ChunkCoordComp(coord))).id();
97            manager.register(coord, entity);
98            modified_writer.write(ChunkModified(coord));
99            continue;
100        }
101
102        // ── 2. Fall back to async generation ─────────────────────────────
103        let Some(ref generator_res) = generator_res else {
104            // No generator registered — silently skip (framework-only mode).
105            continue;
106        };
107
108        // Clone the Arc — cheap, no allocation of the generator itself.
109        let generator = generator_res.generator.clone();
110
111        let task = pool.spawn(async move {
112            let mut chunk = Chunk::<V>::new();
113            generator.generate(coord, &mut chunk);
114            (coord, chunk)
115        });
116
117        commands.spawn(ChunkTask::<V> { task });
118    }
119}
120
121// ─── chunk_task_poll_system ───────────────────────────────────────────────────
122
123/// Polls all in-flight [`ChunkTask<V>`] components.
124///
125/// When a task is ready this system:
126/// 1. Removes the [`ChunkTask`] component from the entity.
127/// 2. Inserts the generated [`Chunk<V>`] and a [`ChunkCoordComp`] component.
128/// 3. Calls [`ChunkManager::register`] so the streaming system knows the chunk
129///    is fully loaded.
130/// 4. Emits a [`ChunkModified`] message to trigger mesh generation.
131pub fn chunk_task_poll_system<V: VoxelType>(
132    mut commands: Commands,
133    mut tasks: Query<(Entity, &mut ChunkTask<V>)>,
134    mut manager: ResMut<ChunkManager>,
135    mut modified_writer: MessageWriter<ChunkModified>,
136) {
137    crate::profile_span!("voxel::generator::poll");
138    for (entity, mut chunk_task) in tasks.iter_mut() {
139        // Poll the task exactly once — non-blocking.
140        if let Some((coord, chunk)) = block_on(poll_once(&mut chunk_task.task)) {
141            // Remove the task component; insert the real chunk data.
142            commands
143                .entity(entity)
144                .remove::<ChunkTask<V>>()
145                .insert(chunk)
146                .insert(ChunkCoordComp(coord));
147
148            // Register in the manager and notify the mesh system.
149            manager.register(coord, entity);
150            modified_writer.write(ChunkModified(coord));
151        }
152    }
153}