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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use {
    crate::{
        barriers::Barriers,
        command::{
            CommandBuffer, CommandPool, Encoder, Families, Family, Graphics, IndividualReset,
            InitialState, Level, OneShot, PendingOnceState, PrimaryLevel, QueueId, RecordingState,
            Submission, Supports,
        },
        resource::{Handle, Image},
        upload::ImageState,
        util::Device,
    },
    gfx_hal::Device as _,
    smallvec::SmallVec,
    std::{collections::VecDeque, iter::once, ops::DerefMut, ops::Range},
};

/// Manages blitting images across families and queues.
#[derive(Debug)]
pub struct Blitter<B: gfx_hal::Backend> {
    family_ops: Vec<Option<parking_lot::Mutex<FamilyGraphicsOps<B>>>>,
}

fn subresource_to_range(
    sub: &gfx_hal::image::SubresourceLayers,
) -> gfx_hal::image::SubresourceRange {
    gfx_hal::image::SubresourceRange {
        aspects: sub.aspects,
        levels: sub.level..sub.level + 1,
        layers: sub.layers.clone(),
    }
}

/// A region to be blitted including the source and destination images and states,
#[derive(Debug, Clone)]
pub struct BlitRegion {
    /// Region to blit from
    pub src: BlitImageState,
    /// Region to blit to
    pub dst: BlitImageState,
}

impl BlitRegion {
    /// Get the blit regions needed to fill the mip levels of an image
    ///
    /// # Safety
    ///
    /// `last` state must be valid for corresponding image layer at the time of command execution (after memory transfers).
    /// `last` and `next` should contain at least `image.levels()` elements.
    /// `image.levels()` must be greater than 1
    pub fn mip_blits_for_image<B: gfx_hal::Backend>(
        image: &Handle<Image<B>>,
        last: impl IntoIterator<Item = ImageState>,
        next: impl IntoIterator<Item = ImageState>,
    ) -> (QueueId, Vec<BlitRegion>) {
        assert!(image.levels() > 1);

        let aspects = image.format().surface_desc().aspects;

        let transfer = gfx_hal::pso::PipelineStage::TRANSFER;
        let src_optimal = gfx_hal::image::Layout::TransferSrcOptimal;
        let read = gfx_hal::image::Access::TRANSFER_READ;
        let write = gfx_hal::image::Access::TRANSFER_WRITE;

        let mut last_iter = last.into_iter();
        let mut next_iter = next.into_iter();

        let mut src_last = last_iter.next().unwrap();
        let mut src_next = next_iter.next().unwrap();
        assert_eq!(src_last.queue, src_next.queue);

        let queue = src_last.queue;

        let mut blits = Vec::with_capacity(image.levels() as usize - 1);

        for (level, (dst_last, dst_next)) in (1..image.levels())
            .into_iter()
            .zip(last_iter.zip(next_iter))
        {
            assert_eq!(dst_last.queue, dst_next.queue);

            let begin = level == 1;
            let end = level == image.levels() - 1;

            blits.push(BlitRegion {
                src: BlitImageState {
                    subresource: gfx_hal::image::SubresourceLayers {
                        aspects,
                        level: level - 1,
                        layers: 0..image.layers(),
                    },
                    bounds: gfx_hal::image::Offset::ZERO
                        .into_bounds(&image.kind().level_extent(level - 1)),
                    last_stage: if begin { src_last.stage } else { transfer },
                    last_access: if begin { src_last.access } else { write },
                    last_layout: if begin { src_last.layout } else { src_optimal },
                    next_stage: src_next.stage,
                    next_access: src_next.access,
                    next_layout: src_next.layout,
                },
                dst: BlitImageState {
                    subresource: gfx_hal::image::SubresourceLayers {
                        aspects,
                        level,
                        layers: 0..image.layers(),
                    },
                    bounds: gfx_hal::image::Offset::ZERO
                        .into_bounds(&image.kind().level_extent(level)),
                    last_stage: dst_last.stage,
                    last_access: gfx_hal::image::Access::empty(),
                    last_layout: gfx_hal::image::Layout::Undefined,
                    next_stage: if end { dst_next.stage } else { transfer },
                    next_access: if end { dst_next.access } else { read },
                    next_layout: if end { dst_next.layout } else { src_optimal },
                },
            });

            src_last = dst_last;
            src_next = dst_next;
        }

        (queue, blits)
    }
}

impl From<BlitRegion> for gfx_hal::command::ImageBlit {
    fn from(blit: BlitRegion) -> Self {
        gfx_hal::command::ImageBlit {
            src_subresource: blit.src.subresource,
            src_bounds: blit.src.bounds,
            dst_subresource: blit.dst.subresource,
            dst_bounds: blit.dst.bounds,
        }
    }
}

/// A region and image states for one image in a blit.
#[derive(Debug, Clone)]
pub struct BlitImageState {
    subresource: gfx_hal::image::SubresourceLayers,
    bounds: Range<gfx_hal::image::Offset>,
    last_stage: gfx_hal::pso::PipelineStage,
    last_access: gfx_hal::image::Access,
    last_layout: gfx_hal::image::Layout,
    next_stage: gfx_hal::pso::PipelineStage,
    next_access: gfx_hal::image::Access,
    next_layout: gfx_hal::image::Layout,
}

impl<B> Blitter<B>
where
    B: gfx_hal::Backend,
{
    /// # Safety
    ///
    /// `families` must belong to the `device`
    pub(crate) unsafe fn new(
        device: &Device<B>,
        families: &Families<B>,
    ) -> Result<Self, gfx_hal::device::OutOfMemory> {
        let mut family_ops = Vec::new();
        for family in families.as_slice() {
            while family_ops.len() <= family.id().index {
                family_ops.push(None);
            }

            family_ops[family.id().index] = Some(parking_lot::Mutex::new(FamilyGraphicsOps {
                pool: family
                    .create_pool(device)
                    .map(|pool| pool.with_capability().unwrap())?,
                initial: Vec::new(),
                next: Vec::new(),
                pending: VecDeque::new(),
                read_barriers: Barriers::new(
                    gfx_hal::pso::PipelineStage::TRANSFER,
                    gfx_hal::buffer::Access::TRANSFER_READ,
                    gfx_hal::image::Access::TRANSFER_READ,
                ),
                write_barriers: Barriers::new(
                    gfx_hal::pso::PipelineStage::TRANSFER,
                    gfx_hal::buffer::Access::TRANSFER_WRITE,
                    gfx_hal::image::Access::TRANSFER_WRITE,
                ),
            }));
        }

        Ok(Blitter { family_ops })
    }
    /// Fill all mip levels from the first level of provided image.
    ///
    /// # Safety
    ///
    /// `device` must be the same that was used to create this `Blitter`.
    /// `image` must belong to the `device`.
    /// `last` state must be valid for corresponding image layer at the time of command execution (after memory transfers).
    /// `last` and `next` should contain at least `image.levels()` elements.
    /// `image.levels()` must be greater than 1
    pub unsafe fn fill_mips(
        &self,
        device: &Device<B>,
        image: Handle<Image<B>>,
        filter: gfx_hal::image::Filter,
        last: impl IntoIterator<Item = ImageState>,
        next: impl IntoIterator<Item = ImageState>,
    ) -> Result<(), failure::Error> {
        let (queue, blits) = BlitRegion::mip_blits_for_image(&image, last, next);
        for blit in blits {
            log::trace!("Blit: {:#?}", blit);
            self.blit_image(device, queue, &image, &image, filter, Some(blit))?;
        }
        Ok(())
    }

    /// Blit provided regions of `src_image` to `dst_image`.
    ///
    /// # Safety
    ///
    /// `device` must be the same that was used to create this `Blitter`.
    /// `src` and `dst` must belong to the `device`.
    /// regions' `last_*` states must be valid at the time of command execution (after memory transfers).
    /// All regions must have distinct subresource layer and level combination.
    ///
    pub unsafe fn blit_image(
        &self,
        device: &Device<B>,
        queue_id: QueueId,
        src_image: &Handle<Image<B>>,
        dst_image: &Handle<Image<B>>,
        filter: gfx_hal::image::Filter,
        regions: impl IntoIterator<Item = BlitRegion>,
    ) -> Result<(), failure::Error> {
        let mut family_ops = self.family_ops[queue_id.family.index]
            .as_ref()
            .unwrap()
            .lock();

        family_ops.next_ops(device, queue_id.index)?;

        let FamilyGraphicsOps { next, .. } = family_ops.deref_mut();

        let next_ops = next[queue_id.index].as_mut().unwrap();
        let mut encoder = next_ops.command_buffer.encoder();

        blit_image(&mut encoder, src_image, dst_image, filter, regions)
    }

    /// Cleanup pending updates.
    ///
    /// # Safety
    ///
    /// `device` must be the same that was used to create this `Blitter`.
    ///
    pub(crate) unsafe fn cleanup(&mut self, device: &Device<B>) {
        for blitter in self.family_ops.iter_mut() {
            if let Some(blitter) = blitter {
                blitter.get_mut().cleanup(device);
            }
        }
    }

    /// Flush new updates.
    ///
    /// # Safety
    ///
    /// `families` must be the same that was used to create this `Blitter`.
    ///
    pub(crate) unsafe fn flush(&mut self, families: &mut Families<B>) {
        for family in families.as_slice_mut() {
            let blitter = self.family_ops[family.id().index]
                .as_mut()
                .expect("Blitter must be initialized for all families");
            blitter.get_mut().flush(family);
        }
    }

    /// # Safety
    ///
    /// `device` must be the same that was used to create this `Blitter`.
    /// `device` must be idle.
    ///
    pub(crate) unsafe fn dispose(&mut self, device: &Device<B>) {
        self.family_ops.drain(..).for_each(|fu| {
            fu.map(|fu| fu.into_inner().dispose(device));
        });
    }
}

/// Blits one or more regions from src_image into dst_image using
/// specified Filter
///
/// # Safety
///
/// * `src_image` and `dst_image` must have been created from the same `Device`
/// as `encoder`
pub unsafe fn blit_image<B, C, L>(
    encoder: &mut Encoder<'_, B, C, L>,
    src_image: &Handle<Image<B>>,
    dst_image: &Handle<Image<B>>,
    filter: gfx_hal::image::Filter,
    regions: impl IntoIterator<Item = BlitRegion>,
) -> Result<(), failure::Error>
where
    B: gfx_hal::Backend,
    C: Supports<Graphics>,
    L: Level,
{
    let mut read_barriers = Barriers::new(
        gfx_hal::pso::PipelineStage::TRANSFER,
        gfx_hal::buffer::Access::TRANSFER_READ,
        gfx_hal::image::Access::TRANSFER_READ,
    );

    let mut write_barriers = Barriers::new(
        gfx_hal::pso::PipelineStage::TRANSFER,
        gfx_hal::buffer::Access::TRANSFER_WRITE,
        gfx_hal::image::Access::TRANSFER_WRITE,
    );

    let regions = regions
        .into_iter()
        .map(|reg| {
            read_barriers.add_image(
                src_image.clone(),
                subresource_to_range(&reg.src.subresource),
                reg.src.last_stage,
                reg.src.last_access,
                reg.src.last_layout,
                gfx_hal::image::Layout::TransferSrcOptimal,
                reg.src.next_stage,
                reg.src.next_access,
                reg.src.next_layout,
            );

            write_barriers.add_image(
                dst_image.clone(),
                subresource_to_range(&reg.dst.subresource),
                reg.dst.last_stage,
                reg.dst.last_access,
                reg.dst.last_layout,
                gfx_hal::image::Layout::TransferDstOptimal,
                reg.dst.next_stage,
                reg.dst.next_access,
                reg.dst.next_layout,
            );

            reg.into()
        })
        .collect::<SmallVec<[_; 1]>>();

    // TODO: synchronize whatever possible on flush.
    // Currently all barriers are inlined due to dependencies between blits.

    read_barriers.encode_before(encoder);
    write_barriers.encode_before(encoder);

    encoder.blit_image(
        src_image.raw(),
        gfx_hal::image::Layout::TransferSrcOptimal,
        dst_image.raw(),
        gfx_hal::image::Layout::TransferDstOptimal,
        filter,
        regions,
    );

    read_barriers.encode_after(encoder);
    write_barriers.encode_after(encoder);
    Ok(())
}

#[derive(Debug)]
pub(crate) struct FamilyGraphicsOps<B: gfx_hal::Backend> {
    pool: CommandPool<B, Graphics, IndividualReset>,
    initial: Vec<GraphicsOps<B, InitialState>>,
    next: Vec<Option<GraphicsOps<B, RecordingState<OneShot>>>>,
    pending: VecDeque<GraphicsOps<B, PendingOnceState>>,
    read_barriers: Barriers<B>,
    write_barriers: Barriers<B>,
}

#[derive(Debug)]
struct GraphicsOps<B: gfx_hal::Backend, S> {
    command_buffer: CommandBuffer<B, Graphics, S, PrimaryLevel, IndividualReset>,
    fence: B::Fence,
}

impl<B> FamilyGraphicsOps<B>
where
    B: gfx_hal::Backend,
{
    unsafe fn flush(&mut self, family: &mut Family<B>) {
        for (queue, next) in self
            .next
            .drain(..)
            .enumerate()
            .filter_map(|(i, x)| x.map(|x| (i, x)))
        {
            log::trace!("Flush blitter");
            let (submit, command_buffer) = next.command_buffer.finish().submit_once();

            family.queue_mut(queue).submit_raw_fence(
                Some(Submission::new().submits(once(submit))),
                Some(&next.fence),
            );

            self.pending.push_back(GraphicsOps {
                command_buffer,
                fence: next.fence,
            });
        }
    }

    unsafe fn next_ops(
        &mut self,
        device: &Device<B>,
        queue: usize,
    ) -> Result<&mut GraphicsOps<B, RecordingState<OneShot>>, failure::Error> {
        while self.next.len() <= queue {
            self.next.push(None);
        }

        let pool = &mut self.pool;

        match &mut self.next[queue] {
            Some(next) => Ok(next),
            slot @ None => {
                let initial: Result<_, failure::Error> = self.initial.pop().map_or_else(
                    || {
                        Ok(GraphicsOps {
                            command_buffer: pool.allocate_buffers(1).remove(0),
                            fence: device.create_fence(false)?,
                        })
                    },
                    Ok,
                );
                let initial = initial?;

                *slot = Some(GraphicsOps {
                    command_buffer: initial.command_buffer.begin(OneShot, ()),
                    fence: initial.fence,
                });

                Ok(slot.as_mut().unwrap())
            }
        }
    }

    /// Cleanup pending updates.
    ///
    /// # Safety
    ///
    /// `device` must be the same that was used with other methods of this instance.
    ///
    unsafe fn cleanup(&mut self, device: &Device<B>) {
        while let Some(pending) = self.pending.pop_front() {
            match device.get_fence_status(&pending.fence) {
                Ok(false) => {
                    self.pending.push_front(pending);
                    return;
                }
                Err(gfx_hal::device::DeviceLost) => {
                    panic!("Device lost error is not handled yet");
                }
                Ok(true) => {
                    device
                        .reset_fence(&pending.fence)
                        .expect("Can always reset signalled fence");
                    self.initial.push(GraphicsOps {
                        command_buffer: pending.command_buffer.mark_complete().reset(),
                        fence: pending.fence,
                    })
                }
            }
        }
    }

    /// # Safety
    ///
    /// Device must be idle.
    ///
    unsafe fn dispose(mut self, device: &Device<B>) {
        let pool = &mut self.pool;
        self.pending.drain(..).for_each(|pending| {
            device.destroy_fence(pending.fence);
            pool.free_buffers(once(pending.command_buffer.mark_complete()));
        });
        self.initial.drain(..).for_each(|initial| {
            device.destroy_fence(initial.fence);
            pool.free_buffers(once(initial.command_buffer));
        });
        self.next.drain(..).filter_map(|n| n).for_each(|next| {
            device.destroy_fence(next.fence);
            pool.free_buffers(once(next.command_buffer));
        });
        drop(pool);
        self.pool.dispose(device);
    }
}