forked from EngoDev/bevy_app_compute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.rs
419 lines (354 loc) · 13.4 KB
/
worker.rs
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
use core::panic;
use std::{marker::PhantomData, ops::Deref};
use bevy::{
prelude::{Res, ResMut, Resource},
render::{
render_resource::{Buffer, ComputePipeline},
renderer::{RenderDevice, RenderQueue},
},
utils::{HashMap, Uuid},
};
use bytemuck::{bytes_of, cast_slice, from_bytes, AnyBitPattern, NoUninit};
use wgpu::{
BindGroupDescriptor, BindGroupEntry, CommandEncoder, CommandEncoderDescriptor,
ComputePassDescriptor,
};
use crate::{
error::{Error, Result},
pipeline_cache::{AppPipelineCache, CachedAppComputePipelineId},
traits::ComputeWorker,
worker_builder::AppComputeWorkerBuilder,
};
#[derive(PartialEq, Clone, Copy)]
pub enum RunMode {
Continuous,
OneShot(bool),
}
#[derive(PartialEq)]
pub enum WorkerState {
Created,
Available,
Working,
FinishedWorking,
}
#[derive(Clone, Debug)]
pub(crate) enum Step {
ComputePass(ComputePass),
Swap(String, String),
}
#[derive(Clone, Debug)]
pub(crate) struct ComputePass {
pub(crate) workgroups: [u32; 3],
pub(crate) vars: Vec<String>,
pub(crate) shader_uuid: Uuid,
}
#[derive(Clone, Debug)]
pub(crate) struct StagingBuffer {
pub(crate) mapped: bool,
pub(crate) buffer: Buffer,
}
/// Struct to manage data transfers from/to the GPU
/// it also handles the logic of your compute work.
/// By default, the run mode of the workers is set to continuous,
/// meaning it will run every frames. If you want to run it deterministically
/// use the function `one_shot()` in the builder
#[derive(Resource)]
pub struct AppComputeWorker<W: ComputeWorker> {
pub(crate) state: WorkerState,
render_device: RenderDevice,
render_queue: RenderQueue,
cached_pipeline_ids: HashMap<Uuid, CachedAppComputePipelineId>,
pipelines: HashMap<Uuid, Option<ComputePipeline>>,
buffers: HashMap<String, Buffer>,
staging_buffers: HashMap<String, StagingBuffer>,
steps: Vec<Step>,
command_encoder: Option<CommandEncoder>,
run_mode: RunMode,
_phantom: PhantomData<W>,
}
impl<W: ComputeWorker> From<&AppComputeWorkerBuilder<'_, W>> for AppComputeWorker<W> {
/// Create a new [`AppComputeWorker<W>`].
fn from(builder: &AppComputeWorkerBuilder<W>) -> Self {
let render_device = builder.world.resource::<RenderDevice>().clone();
let render_queue = builder.world.resource::<RenderQueue>().clone();
let pipelines = builder
.cached_pipeline_ids
.iter()
.map(|(uuid, _)| (*uuid, None))
.collect();
let command_encoder =
Some(render_device.create_command_encoder(&CommandEncoderDescriptor { label: None }));
Self {
state: WorkerState::Created,
render_device,
render_queue,
cached_pipeline_ids: builder.cached_pipeline_ids.clone(),
pipelines,
buffers: builder.buffers.clone(),
staging_buffers: builder.staging_buffers.clone(),
steps: builder.steps.clone(),
command_encoder,
run_mode: builder.run_mode,
_phantom: PhantomData::default(),
}
}
}
impl<W: ComputeWorker> AppComputeWorker<W> {
#[inline]
fn dispatch(&mut self, index: usize) -> Result<()> {
let compute_pass = match &self.steps[index] {
Step::ComputePass(compute_pass) => compute_pass,
Step::Swap(_, _) => return Err(Error::InvalidStep(format!("{:?}", self.steps[index]))),
};
let mut entries = vec![];
for (index, var) in compute_pass.vars.iter().enumerate() {
let Some(buffer) = self
.buffers
.get(var)
else { return Err(Error::BufferNotFound(var.to_owned())) };
let entry = BindGroupEntry {
binding: index as u32,
resource: buffer.as_entire_binding(),
};
entries.push(entry);
}
let Some(maybe_pipeline) = self
.pipelines
.get(&compute_pass.shader_uuid)
else { return Err(Error::PipelinesEmpty) };
let Some(pipeline) = maybe_pipeline else {
return Err(Error::PipelineNotReady);
};
let bind_group_layout = pipeline.get_bind_group_layout(0);
let bind_group = self.render_device.create_bind_group(&BindGroupDescriptor {
label: None,
layout: &bind_group_layout,
entries: &entries,
});
let Some(encoder) = &mut self.command_encoder else { return Err(Error::EncoderIsNone) };
{
let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor { label: None });
cpass.set_pipeline(&pipeline);
cpass.set_bind_group(0, &bind_group, &[]);
cpass.dispatch_workgroups(
compute_pass.workgroups[0],
compute_pass.workgroups[1],
compute_pass.workgroups[2],
)
}
Ok(())
}
#[inline]
fn swap(&mut self, index: usize) -> Result<()> {
let (buf_a_name, buf_b_name) = match &self.steps[index] {
Step::ComputePass(_) => {
return Err(Error::InvalidStep(format!("{:?}", self.steps[index])))
}
Step::Swap(a, b) => (a.as_str(), b.as_str()),
};
if !self.buffers.contains_key(buf_a_name) {
return Err(Error::BufferNotFound(buf_a_name.to_owned()));
}
if !self.buffers.contains_key(buf_b_name) {
return Err(Error::BufferNotFound(buf_b_name.to_owned()));
}
let [buffer_a, buffer_b] = self.buffers.get_many_mut([buf_a_name, buf_b_name]).unwrap();
std::mem::swap(buffer_a, buffer_b);
Ok(())
}
#[inline]
fn read_staging_buffers(&mut self) -> Result<&mut Self> {
for (name, staging_buffer) in &self.staging_buffers {
let Some(encoder) = &mut self.command_encoder else { return Err(Error::EncoderIsNone); };
let Some(buffer) = self
.buffers
.get(name)
else { return Err(Error::BufferNotFound(name.to_owned()))};
encoder.copy_buffer_to_buffer(
&buffer,
0,
&staging_buffer.buffer,
0,
staging_buffer.buffer.size(),
);
}
Ok(self)
}
#[inline]
fn map_staging_buffers(&mut self) -> &mut Self {
for (_, staging_buffer) in self.staging_buffers.iter_mut() {
let read_buffer_slice = staging_buffer.buffer.slice(..);
read_buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
let err = result.err();
if err.is_some() {
let some_err = err.unwrap();
panic!("{}", some_err.to_string());
}
});
staging_buffer.mapped = true;
}
self
}
/// Read data from `target` staging buffer, return raw bytes
#[inline]
pub fn try_read_raw<'a>(&'a self, target: &str) -> Result<(impl Deref<Target = [u8]> + 'a)> {
let Some(staging_buffer) = &self
.staging_buffers
.get(target)
else { return Err(Error::StagingBufferNotFound(target.to_owned()))};
let result = staging_buffer.buffer.slice(..).get_mapped_range();
Ok(result)
}
/// Read data from `target` staging buffer, return raw bytes
/// Panics on error.
#[inline]
pub fn read_raw<'a>(&'a self, target: &str) -> (impl Deref<Target = [u8]> + 'a) {
self.try_read_raw(target).unwrap()
}
/// Try Read data from `target` staging buffer, return a single `B: Pod`
#[inline]
pub fn try_read<'a, B: AnyBitPattern>(&'a self, target: &str) -> Result<B> {
let result = from_bytes::<B>(&self.try_read_raw(target)?).clone();
Ok(result)
}
/// Try Read data from `target` staging buffer, return a single `B: Pod`
/// In case of error, this function will panic.
#[inline]
pub fn read<B: AnyBitPattern>(&self, target: &str) -> B {
self.try_read(target).unwrap()
}
/// Try Read data from `target` staging buffer, return a vector of `B: Pod`
#[inline]
pub fn try_read_vec<B: AnyBitPattern>(&self, target: &str) -> Result<Vec<B>> {
let bytes = self.try_read_raw(target)?;
Ok(cast_slice::<u8, B>(&bytes).to_vec())
}
/// Try Read data from `target` staging buffer, return a vector of `B: Pod`
/// In case of error, this function will panic.
#[inline]
pub fn read_vec<B: AnyBitPattern>(&self, target: &str) -> Vec<B> {
self.try_read_vec(target).unwrap()
}
/// Write data to `target` buffer.
#[inline]
pub fn try_write<T: NoUninit>(&mut self, target: &str, data: &T) -> Result<()> {
let Some(buffer) = &self
.buffers
.get(target)
else { return Err(Error::BufferNotFound(target.to_owned())) };
let bytes = bytes_of(data);
self.render_queue.write_buffer(buffer, 0, bytes);
Ok(())
}
/// Write data to `target` buffer.
/// In case of error, this function will panic.
#[inline]
pub fn write<T: NoUninit>(&mut self, target: &str, data: &T) {
self.try_write(target, data).unwrap()
}
/// Write data to `target` buffer.
#[inline]
pub fn try_write_slice<T: NoUninit>(&mut self, target: &str, data: &[T]) -> Result<()> {
let Some(buffer) = &self
.buffers
.get(target)
else { return Err(Error::BufferNotFound(target.to_owned())) };
let bytes = cast_slice(data);
self.render_queue.write_buffer(buffer, 0, bytes);
Ok(())
}
/// Write data to `target` buffer.
/// In case of error, this function will panic.
#[inline]
pub fn write_slice<T: NoUninit>(&mut self, target: &str, data: &[T]) {
self.try_write_slice(target, data).unwrap()
}
fn submit(&mut self) -> &mut Self {
let encoder = self.command_encoder.take().unwrap();
self.render_queue.submit(Some(encoder.finish()));
self.state = WorkerState::Working;
self
}
#[inline]
fn poll(&self) -> bool {
self.render_device
.wgpu_device()
.poll(wgpu::MaintainBase::Wait)
}
/// Check if the worker is ready to be read from.
#[inline]
pub fn ready(&self) -> bool {
self.state == WorkerState::FinishedWorking
}
/// Tell the worker to execute the compute shader at the end of the current frame
#[inline]
pub fn execute(&mut self) {
match self.run_mode {
RunMode::Continuous => {}
RunMode::OneShot(_) => self.run_mode = RunMode::OneShot(true),
}
}
#[inline]
fn ready_to_execute(&self) -> bool {
(self.state != WorkerState::Working) && (self.run_mode != RunMode::OneShot(false))
}
pub(crate) fn run(mut worker: ResMut<Self>) {
if worker.ready() {
worker.state = WorkerState::Available;
}
if worker.ready_to_execute() {
// Workaround for interior mutability
for i in 0..worker.steps.len() {
let result = match worker.steps[i] {
Step::ComputePass(_) => worker.dispatch(i),
Step::Swap(_, _) => worker.swap(i),
};
if let Err(err) = result {
match err {
Error::PipelineNotReady => return,
_ => panic!("{:?}", err),
}
}
}
worker.read_staging_buffers().unwrap();
worker.submit();
worker.map_staging_buffers();
}
if worker.run_mode != RunMode::OneShot(false) && worker.poll() {
worker.state = WorkerState::FinishedWorking;
worker.command_encoder = Some(
worker
.render_device
.create_command_encoder(&CommandEncoderDescriptor { label: None }),
);
match worker.run_mode {
RunMode::Continuous => {}
RunMode::OneShot(_) => worker.run_mode = RunMode::OneShot(false),
};
}
}
pub(crate) fn unmap_all(mut worker: ResMut<Self>) {
for (_, staging_buffer) in &mut worker.staging_buffers {
if staging_buffer.mapped {
staging_buffer.buffer.unmap();
staging_buffer.mapped = false;
}
}
}
pub(crate) fn extract_pipelines(
mut worker: ResMut<Self>,
pipeline_cache: Res<AppPipelineCache>,
) {
for (uuid, cached_id) in &worker.cached_pipeline_ids.clone() {
let Some(pipeline) = worker.pipelines.get(&uuid) else { continue; };
if pipeline.is_some() {
continue;
};
let cached_id = cached_id.clone();
worker.pipelines.insert(
*uuid,
pipeline_cache.get_compute_pipeline(cached_id).cloned(),
);
}
}
}