gigs 0.1.1

on-demand graphics jobs for the Bevy Game Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use core::marker::PhantomData;

use bevy_app::{App, Plugin};
use bevy_ecs::{
    component::Component,
    entity::Entity,
    query::{Changed, QueryItem, ReadOnlyQueryData, WorldQuery},
    schedule::IntoSystemConfigs,
    system::{lifetimeless::Read, Commands, Query, Res, ResMut, Resource, StaticSystemParam},
    world::{FromWorld, World},
};
use bevy_utils::all_tuples;

use bevy_render::{
    extract_component::{ExtractComponent, ExtractComponentPlugin},
    render_resource::{
        AsBindGroup, BindGroupLayout, CachedComputePipelineId, CachedPipelineState,
        CachedRenderPipelineId, ComputePipeline, PipelineCache, PreparedBindGroup, RenderPipeline,
        SpecializedComputePipeline, SpecializedComputePipelines, SpecializedRenderPipeline,
        SpecializedRenderPipelines,
    },
    renderer::RenderDevice,
    sync_world::MainEntity,
    Render, RenderApp, RenderSet,
};

use super::GraphicsJob;

/// The status of a job input
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum JobInputStatus {
    /// Signals that input is ready
    Ready,
    /// Signals that input is not ready, but should be awaited
    Wait,
    /// Signals that input is not ready, and shouldn't be awaited
    Fail,
}

impl JobInputStatus {
    fn combine(self, rhs: Self) -> Self {
        match (self, rhs) {
            (JobInputStatus::Fail, _) | (_, JobInputStatus::Fail) => JobInputStatus::Fail,
            (JobInputStatus::Ready, JobInputStatus::Ready) => JobInputStatus::Ready,
            _ => JobInputStatus::Wait,
        }
    }
}

pub type JobInputItem<'a, J, In> = <In as JobInput<J>>::Item<'a>;

/// A trait describing input to a graphics job.
///
/// This trait may be thought of as similar to [`QueryData`](bevy_ecs::query::QueryData),
/// but which also sets more things up behind the scenes. For example,
/// an implementor may prepare a bind group using data from the job
/// entity and the [`World`].
///
/// Note: while there is no blanket impl for [`JobInput`] for all
/// [`ReadOnlyQueryData`] types, it *is* implemented for all single
/// components, [`Entity`], [`MainEntity`], and [`Option`].
pub trait JobInput<J: GraphicsJob> {
    type Data: ReadOnlyQueryData;
    type Item<'a>;

    /// a plugin to register on the app, to setup behind the scenes processing
    /// for this implementor.
    fn plugin() -> impl Plugin {
        |_: &mut App| {}
    }

    /// the status of the resources needed by this job input. For example,
    /// an implementor may check the status of a queued pipeline, and wait
    /// until it's done compiling.
    fn status(data: QueryItem<Self::Data>, world: &World) -> JobInputStatus;

    /// returns the actual job input item.
    fn get<'a>(data: QueryItem<'a, Self::Data>, world: &'a World) -> Self::Item<'a>;
}

macro_rules! impl_job_input_tuple {
    ($(($T: ident, $t: ident)),*) => {
        impl <J: GraphicsJob, $($T: JobInput<J>),*> JobInput<J> for ($($T,)*) {
            type Data = ($(<$T as JobInput<J>>::Data,)*);
            type Item<'a> = ($(<$T as JobInput<J>>::Item<'a>,)*);


            fn plugin() -> impl Plugin {
                |app: &mut App| {
                    app.add_plugins(($(<$T as JobInput<J>>::plugin()),*));
                }
            }

            #[allow(unused_variables)]
            fn status(data: QueryItem<Self::Data>, world: &World) -> JobInputStatus {
                let ($($t,)*) = data;
                JobInputStatus::Ready
                    $(.combine(<$T as JobInput<J>>::status($t, world)))*
            }

            #[allow(unused_variables, clippy::unused_unit)]
            fn get<'a>(data: QueryItem<'a, Self::Data>, world: &'a World) -> Self::Item<'a> {
                let ($($t,)*) = data;
                ($(<$T as JobInput<J>>::get($t, world),)*)
            }
        }
    }
}

all_tuples!(impl_job_input_tuple, 0, 15, T, t);

impl<J: GraphicsJob> JobInput<J> for Entity {
    type Data = Entity;

    type Item<'a> = Entity;

    fn status(_data: QueryItem<Self::Data>, _world: &World) -> JobInputStatus {
        JobInputStatus::Ready
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, _world: &'a World) -> Self::Item<'a> {
        data
    }
}

impl<J: GraphicsJob> JobInput<J> for MainEntity {
    type Data = MainEntity;

    type Item<'a> = Entity;

    fn status(_data: QueryItem<Self::Data>, _world: &World) -> JobInputStatus {
        JobInputStatus::Ready
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, _world: &'a World) -> Self::Item<'a> {
        data
    }
}

impl<'t, T: Component, J: GraphicsJob> JobInput<J> for &'t T {
    type Data = &'t T;

    type Item<'a> = &'a T;

    fn status(_data: QueryItem<Self::Data>, _world: &World) -> JobInputStatus {
        JobInputStatus::Ready
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, _world: &'a World) -> Self::Item<'a> {
        data
    }
}

impl<T: ReadOnlyQueryData, J: GraphicsJob> JobInput<J> for Option<T> {
    type Data = Option<T>;

    type Item<'a> = Option<<T as WorldQuery>::Item<'a>>;

    fn status(_data: QueryItem<Self::Data>, _world: &World) -> JobInputStatus {
        JobInputStatus::Ready
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, _world: &'a World) -> Self::Item<'a> {
        data
    }
}

pub struct JobAsBindGroup;

impl<J: GraphicsJob + AsBindGroup> JobInput<J> for JobAsBindGroup {
    type Data = Option<Read<PreparedJobBindGroup<J>>>;

    type Item<'a> = &'a PreparedBindGroup<<J as AsBindGroup>::Data>;

    fn plugin() -> impl Plugin {
        JobAsBindGroupPlugin::<J>(PhantomData)
    }

    fn status(data: QueryItem<Self::Data>, _world: &World) -> JobInputStatus {
        match data {
            Some(_) => JobInputStatus::Ready,
            None => JobInputStatus::Wait,
        }
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, _world: &'a World) -> Self::Item<'a> {
        &data.unwrap().0
    }
}

struct JobAsBindGroupPlugin<J>(PhantomData<J>);

impl<J: GraphicsJob + AsBindGroup> Plugin for JobAsBindGroupPlugin<J> {
    fn build(&self, app: &mut App) {
        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app.add_systems(
                Render,
                prepare_job_bind_group::<J>.in_set(RenderSet::PrepareBindGroups),
            );
        }
    }

    fn finish(&self, app: &mut App) {
        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app.init_resource::<JobBindGroupLayout<J>>();
        }
    }
}

/// A [`JobInput`] type that prepares the graphics job type *itself* as a bind group,
/// using its [`AsBindGroup`] implementation.
#[derive(Component)]
pub struct PreparedJobBindGroup<J: GraphicsJob + AsBindGroup>(
    PreparedBindGroup<<J as AsBindGroup>::Data>,
);

#[derive(Resource)]
struct JobBindGroupLayout<J: GraphicsJob + AsBindGroup>(BindGroupLayout, PhantomData<J>);

impl<J: GraphicsJob + AsBindGroup> FromWorld for JobBindGroupLayout<J> {
    fn from_world(world: &mut World) -> Self {
        let render_device = world.resource::<RenderDevice>();
        Self(J::bind_group_layout(render_device), PhantomData)
    }
}

fn prepare_job_bind_group<J: GraphicsJob + AsBindGroup>(
    jobs: Query<(Entity, &J)>,
    layout: Res<JobBindGroupLayout<J>>,
    render_device: Res<RenderDevice>,
    mut param: StaticSystemParam<<J as AsBindGroup>::Param>,
    mut commands: Commands,
) {
    for (entity, job) in &jobs {
        if let Ok(bind_group) = job.as_bind_group(&layout.0, &render_device, &mut param) {
            commands
                .entity(entity)
                .insert(PreparedJobBindGroup::<J>(bind_group));
        }
    }
}

#[doc(hidden)]
pub trait SpecializedJobRenderPipeline:
    SpecializedRenderPipeline<Key: Send + Sync> + Resource + FromWorld
{
}
impl<P: SpecializedRenderPipeline<Key: Send + Sync> + Resource + FromWorld>
    SpecializedJobRenderPipeline for P
{
}

/// A [`JobInput`] type that sets up a [`RenderPipeline`] for a job. This component must be
/// added to a job as it is spawned in order to setup the pipeline.
#[derive(Component)]
pub struct JobRenderPipeline<P: SpecializedJobRenderPipeline>(pub P::Key);

impl<P: SpecializedJobRenderPipeline<Key: Default>> Default for JobRenderPipeline<P> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<J: GraphicsJob, P: SpecializedJobRenderPipeline> JobInput<J> for JobRenderPipeline<P> {
    type Data = Option<Read<JobRenderPipelineId<P>>>;

    type Item<'a> = &'a RenderPipeline;

    fn plugin() -> impl Plugin {
        JobRenderPipelinePlugin::<P>(PhantomData)
    }

    fn status(data: QueryItem<Self::Data>, world: &World) -> JobInputStatus {
        let Some(JobRenderPipelineId(id, _)) = data else {
            return JobInputStatus::Wait;
        };
        if matches!(
            world
                .resource::<PipelineCache>()
                .get_render_pipeline_state(*id),
            CachedPipelineState::Ok(_)
        ) {
            JobInputStatus::Ready
        } else {
            JobInputStatus::Wait
        }
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, world: &'a World) -> Self::Item<'a> {
        let id = data.unwrap().0;
        world
            .resource::<PipelineCache>()
            .get_render_pipeline(id)
            .expect("pipeline should be ready by this point")
    }
}

impl<P: SpecializedJobRenderPipeline> Clone for JobRenderPipeline<P> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<P: SpecializedJobRenderPipeline> ExtractComponent for JobRenderPipeline<P> {
    type QueryData = Read<JobRenderPipeline<P>>;

    type QueryFilter = ();

    type Out = JobRenderPipeline<P>;

    fn extract_component(item: QueryItem<'_, Self::QueryData>) -> Option<Self::Out> {
        Some(item.clone())
    }
}

#[derive(Component)]
#[doc(hidden)]
pub struct JobRenderPipelineId<P: SpecializedJobRenderPipeline>(
    CachedRenderPipelineId,
    PhantomData<P>,
);

struct JobRenderPipelinePlugin<P: SpecializedJobRenderPipeline>(PhantomData<P>);

impl<P: SpecializedJobRenderPipeline> Plugin for JobRenderPipelinePlugin<P> {
    fn build(&self, app: &mut App) {
        app.add_plugins(ExtractComponentPlugin::<JobRenderPipeline<P>>::default());

        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app
                .init_resource::<SpecializedRenderPipelines<P>>()
                .add_systems(
                    Render,
                    queue_job_render_pipelines::<P>.in_set(RenderSet::Queue),
                );
        }
    }

    fn finish(&self, app: &mut App) {
        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app.init_resource::<P>();
        }
    }
}

fn queue_job_render_pipelines<P: SpecializedJobRenderPipeline>(
    job_pipelines: Query<(Entity, &JobRenderPipeline<P>), Changed<JobRenderPipeline<P>>>,
    pipeline_cache: Res<PipelineCache>,
    base_pipeline: Res<P>,
    mut specializer: ResMut<SpecializedRenderPipelines<P>>,
    mut commands: Commands,
) {
    for (entity, job_pipeline) in &job_pipelines {
        let id = specializer.specialize(&pipeline_cache, &base_pipeline, job_pipeline.0.clone());
        commands
            .entity(entity)
            .insert(JobRenderPipelineId::<P>(id, PhantomData));
    }
}

#[doc(hidden)]
pub trait SpecializedJobComputePipeline:
    SpecializedComputePipeline<Key: Send + Sync> + Resource + FromWorld
{
}
impl<P: SpecializedComputePipeline<Key: Send + Sync> + Resource + FromWorld>
    SpecializedJobComputePipeline for P
{
}

/// A [`JobInput`] type that sets up a [`ComputePipeline`] for a job. This component must be
/// added to a job as it is spawned in order to setup the pipeline.
#[derive(Component)]
pub struct JobComputePipeline<P: SpecializedJobComputePipeline>(P::Key);

impl<P: SpecializedJobComputePipeline<Key: Default>> Default for JobComputePipeline<P> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<J: GraphicsJob, P: SpecializedJobComputePipeline> JobInput<J> for JobComputePipeline<P> {
    type Data = Option<Read<JobComputePipelineId<P>>>;

    type Item<'a> = &'a ComputePipeline;

    fn plugin() -> impl Plugin {
        JobComputePipelinePlugin::<P>(PhantomData)
    }

    fn status(data: QueryItem<Self::Data>, world: &World) -> JobInputStatus {
        let Some(JobComputePipelineId(id, _)) = data else {
            return JobInputStatus::Wait;
        };
        if matches!(
            world
                .resource::<PipelineCache>()
                .get_compute_pipeline_state(*id),
            CachedPipelineState::Ok(_)
        ) {
            JobInputStatus::Ready
        } else {
            JobInputStatus::Wait
        }
    }

    fn get<'a>(data: QueryItem<'a, Self::Data>, world: &'a World) -> Self::Item<'a> {
        let id = data.unwrap().0;
        world
            .resource::<PipelineCache>()
            .get_compute_pipeline(id)
            .expect("pipeline should be ready by this point")
    }
}

impl<P: SpecializedJobComputePipeline> Clone for JobComputePipeline<P> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<P: SpecializedJobComputePipeline> ExtractComponent for JobComputePipeline<P> {
    type QueryData = Read<JobComputePipeline<P>>;

    type QueryFilter = ();

    type Out = JobComputePipeline<P>;

    fn extract_component(item: QueryItem<'_, Self::QueryData>) -> Option<Self::Out> {
        Some(item.clone())
    }
}

#[derive(Component)]
#[doc(hidden)]
pub struct JobComputePipelineId<P: SpecializedJobComputePipeline>(
    CachedComputePipelineId,
    PhantomData<P>,
);

struct JobComputePipelinePlugin<P: SpecializedJobComputePipeline>(PhantomData<P>);

impl<P: SpecializedJobComputePipeline> Plugin for JobComputePipelinePlugin<P> {
    fn build(&self, app: &mut App) {
        app.add_plugins(ExtractComponentPlugin::<JobComputePipeline<P>>::default());

        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app
                .init_resource::<SpecializedComputePipelines<P>>()
                .add_systems(
                    Render,
                    queue_job_compute_pipelines::<P>.in_set(RenderSet::Queue),
                );
        }
    }

    fn finish(&self, app: &mut App) {
        if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app.init_resource::<P>();
        }
    }
}

fn queue_job_compute_pipelines<P: SpecializedJobComputePipeline>(
    job_pipelines: Query<(Entity, &JobComputePipeline<P>), Changed<JobComputePipeline<P>>>,
    pipeline_cache: Res<PipelineCache>,
    base_pipeline: Res<P>,
    mut specializer: ResMut<SpecializedComputePipelines<P>>,
    mut commands: Commands,
) {
    for (entity, job_pipeline) in &job_pipelines {
        let id = specializer.specialize(&pipeline_cache, &base_pipeline, job_pipeline.0.clone());
        commands
            .entity(entity)
            .insert(JobComputePipelineId::<P>(id, PhantomData));
    }
}