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
use std::borrow::{Borrow, BorrowMut};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut, Range};

use super::{
    AttachmentClear, ClearValue, ClearValueRaw, CommandBuffer, CommandBufferFlags,
    CommandBufferInheritanceInfo, DescriptorSetOffset, IntoRawCommandBuffer, MultiShot, OneShot,
    Primary, RawCommandBuffer, Secondary, Shot, Submittable,
};
use crate::queue::{Capability, Graphics, Supports};
use crate::{buffer, pass, pso, query};
use crate::{Backend, DrawCount, IndexCount, InstanceCount, VertexCount, VertexOffset};

/// Specifies how commands for the following renderpasses will be recorded.
#[derive(Debug)]
pub enum SubpassContents {
    /// Contents of the subpass will be inline in the command buffer,
    /// NOT in secondary command buffers.
    Inline,
    /// Contents of the subpass will be in secondary command buffers, and
    /// the primary command buffer will only contain `execute_command()` calls
    /// until the subpass or render pass is complete.
    SecondaryBuffers,
}

/// This struct contains all methods for all commands submittable during a subpass.
/// It is used to implement the identical portions of RenderPassInlineEncoder and SubpassCommandBuffer.
///
/// Where methods are undocumented, they are identical to the methods on the `RawCommandBuffer`
/// trait with the same names.
#[derive(Debug)]
pub struct RenderSubpassCommon<B, C> {
    cmb: C,
    _marker: PhantomData<B>,
}

impl<B: Backend, C: BorrowMut<B::CommandBuffer>> RenderSubpassCommon<B, C> {
    unsafe fn new(cmb: C) -> Self {
        RenderSubpassCommon {
            cmb,
            _marker: PhantomData,
        }
    }

    ///
    pub unsafe fn clear_attachments<T, U>(&mut self, clears: T, rects: U)
    where
        T: IntoIterator,
        T::Item: Borrow<AttachmentClear>,
        U: IntoIterator,
        U::Item: Borrow<pso::ClearRect>,
    {
        self.cmb.borrow_mut().clear_attachments(clears, rects)
    }

    ///
    pub unsafe fn draw(&mut self, vertices: Range<VertexCount>, instances: Range<InstanceCount>) {
        self.cmb.borrow_mut().draw(vertices, instances)
    }

    ///
    pub unsafe fn draw_indexed(
        &mut self,
        indices: Range<IndexCount>,
        base_vertex: VertexOffset,
        instances: Range<InstanceCount>,
    ) {
        self.cmb
            .borrow_mut()
            .draw_indexed(indices, base_vertex, instances)
    }

    ///
    pub unsafe fn draw_indirect(
        &mut self,
        buffer: &B::Buffer,
        offset: buffer::Offset,
        draw_count: DrawCount,
        stride: u32,
    ) {
        self.cmb
            .borrow_mut()
            .draw_indirect(buffer, offset, draw_count, stride)
    }
    ///
    pub unsafe fn draw_indexed_indirect(
        &mut self,
        buffer: &B::Buffer,
        offset: buffer::Offset,
        draw_count: DrawCount,
        stride: u32,
    ) {
        self.cmb
            .borrow_mut()
            .draw_indexed_indirect(buffer, offset, draw_count, stride)
    }

    ///
    pub unsafe fn bind_index_buffer(&mut self, ibv: buffer::IndexBufferView<B>) {
        self.cmb.borrow_mut().bind_index_buffer(ibv)
    }

    ///
    pub unsafe fn bind_vertex_buffers<I, T>(&mut self, first_binding: pso::BufferIndex, buffers: I)
    where
        I: IntoIterator<Item = (T, buffer::Offset)>,
        T: Borrow<B::Buffer>,
    {
        self.cmb
            .borrow_mut()
            .bind_vertex_buffers(first_binding, buffers);
    }

    ///
    pub unsafe fn bind_graphics_pipeline(&mut self, pipeline: &B::GraphicsPipeline) {
        self.cmb.borrow_mut().bind_graphics_pipeline(pipeline)
    }

    ///
    pub unsafe fn bind_graphics_descriptor_sets<I, J>(
        &mut self,
        layout: &B::PipelineLayout,
        first_set: usize,
        sets: I,
        offsets: J,
    ) where
        I: IntoIterator,
        I::Item: Borrow<B::DescriptorSet>,
        J: IntoIterator,
        J::Item: Borrow<DescriptorSetOffset>,
    {
        self.cmb
            .borrow_mut()
            .bind_graphics_descriptor_sets(layout, first_set, sets, offsets)
    }

    ///
    pub unsafe fn set_viewports<T>(&mut self, first_viewport: u32, viewports: T)
    where
        T: IntoIterator,
        T::Item: Borrow<pso::Viewport>,
    {
        self.cmb
            .borrow_mut()
            .set_viewports(first_viewport, viewports)
    }

    ///
    pub unsafe fn set_scissors<T>(&mut self, first_scissor: u32, scissors: T)
    where
        T: IntoIterator,
        T::Item: Borrow<pso::Rect>,
    {
        self.cmb.borrow_mut().set_scissors(first_scissor, scissors)
    }

    ///
    pub unsafe fn set_stencil_reference(&mut self, faces: pso::Face, value: pso::StencilValue) {
        self.cmb.borrow_mut().set_stencil_reference(faces, value);
    }

    ///
    pub unsafe fn set_stencil_read_mask(&mut self, faces: pso::Face, value: pso::StencilValue) {
        self.cmb.borrow_mut().set_stencil_read_mask(faces, value);
    }

    ///
    pub unsafe fn set_stencil_write_mask(&mut self, faces: pso::Face, value: pso::StencilValue) {
        self.cmb.borrow_mut().set_stencil_write_mask(faces, value);
    }

    ///
    pub unsafe fn set_blend_constants(&mut self, cv: pso::ColorValue) {
        self.cmb.borrow_mut().set_blend_constants(cv)
    }

    ///
    pub unsafe fn set_depth_bounds(&mut self, bounds: Range<f32>) {
        self.cmb.borrow_mut().set_depth_bounds(bounds)
    }

    ///
    pub unsafe fn push_graphics_constants(
        &mut self,
        layout: &B::PipelineLayout,
        stages: pso::ShaderStageFlags,
        offset: u32,
        constants: &[u32],
    ) {
        self.cmb
            .borrow_mut()
            .push_graphics_constants(layout, stages, offset, constants);
    }

    ///
    pub unsafe fn set_line_width(&mut self, width: f32) {
        self.cmb.borrow_mut().set_line_width(width);
    }

    ///
    pub unsafe fn set_depth_bias(&mut self, depth_bias: pso::DepthBias) {
        self.cmb.borrow_mut().set_depth_bias(depth_bias);
    }

    // TODO: pipeline barrier (postponed)

    ///
    pub unsafe fn begin_query(&mut self, query: query::Query<B>, flags: query::ControlFlags) {
        self.cmb.borrow_mut().begin_query(query, flags)
    }

    ///
    pub unsafe fn end_query(&mut self, query: query::Query<B>) {
        self.cmb.borrow_mut().end_query(query)
    }

    ///
    pub unsafe fn write_timestamp(&mut self, stage: pso::PipelineStage, query: query::Query<B>) {
        self.cmb.borrow_mut().write_timestamp(stage, query)
    }
}

/// An object that records commands into a command buffer inline, that is,
/// without secondary command buffers.
#[derive(Debug)]
pub struct RenderPassInlineEncoder<'a, B: Backend>(
    RenderSubpassCommon<B, &'a mut B::CommandBuffer>,
)
where
    B::CommandBuffer: 'a;

impl<'a, B: Backend> RenderPassInlineEncoder<'a, B> {
    /// Creates a new `RenderPassInlineEncoder`, starting a new render
    /// pass in the given `CommandBuffer`.
    pub unsafe fn new<C, T, S: Shot>(
        cmd_buffer: &'a mut CommandBuffer<B, C, S, Primary>,
        render_pass: &B::RenderPass,
        frame_buffer: &B::Framebuffer,
        render_area: pso::Rect,
        clear_values: T,
    ) -> Self
    where
        C: Supports<Graphics>,
        T: IntoIterator,
        T::Item: Borrow<ClearValue>,
    {
        let clear_values = clear_values
            .into_iter()
            .map(|cv| ClearValueRaw::from(*cv.borrow()));

        cmd_buffer.raw.begin_render_pass(
            render_pass,
            frame_buffer,
            render_area,
            clear_values,
            SubpassContents::Inline,
        );

        RenderPassInlineEncoder(RenderSubpassCommon::new(&mut cmd_buffer.raw))
    }

    /// Start the next subpass.
    pub fn next_subpass_inline(self) -> Self {
        unsafe {
            self.0.cmb.next_subpass(SubpassContents::Inline);
        }
        self
    }

    /// Begins recording a new subpass with secondary buffers.
    pub fn next_subpass_secondary(mut self) -> RenderPassSecondaryEncoder<'a, B> {
        unsafe {
            self.0.cmb.next_subpass(SubpassContents::SecondaryBuffers);
            let cmb = std::ptr::read(&mut self.0.cmb);
            std::mem::forget(self); // Prevent `end_render_pass`
            RenderPassSecondaryEncoder(cmb)
        }
    }
}

impl<'a, B: Backend> Deref for RenderPassInlineEncoder<'a, B> {
    type Target = RenderSubpassCommon<B, &'a mut B::CommandBuffer>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a, B: Backend> DerefMut for RenderPassInlineEncoder<'a, B> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a, B: Backend> Drop for RenderPassInlineEncoder<'a, B> {
    fn drop(&mut self) {
        unsafe {
            self.0.cmb.end_render_pass();
        }
    }
}

/// An object that records commands into a command buffer where each command must
/// be a call to execute a secondary command buffer.
#[derive(Debug)]
pub struct RenderPassSecondaryEncoder<'a, B: Backend>(&'a mut B::CommandBuffer)
where
    B::CommandBuffer: 'a;

impl<'a, B: Backend> RenderPassSecondaryEncoder<'a, B> {
    /// Wraps the given `CommandBuffer` in a `RenderPassSecondaryEncoder`,
    /// starting a new render pass where the actual commands are contained in
    /// secondary command buffers.
    pub unsafe fn new<C, T, S: Shot>(
        cmd_buffer: &'a mut CommandBuffer<B, C, S, Primary>,
        render_pass: &B::RenderPass,
        frame_buffer: &B::Framebuffer,
        render_area: pso::Rect,
        clear_values: T,
    ) -> Self
    where
        C: Supports<Graphics>,
        T: IntoIterator,
        T::Item: Borrow<ClearValue>,
    {
        let clear_values = clear_values
            .into_iter()
            .map(|cv| ClearValueRaw::from(*cv.borrow()));

        cmd_buffer.raw.begin_render_pass(
            render_pass,
            frame_buffer,
            render_area,
            clear_values,
            SubpassContents::SecondaryBuffers,
        );

        RenderPassSecondaryEncoder(&mut cmd_buffer.raw)
    }

    /// Executes the given commands as a secondary command buffer.
    pub unsafe fn execute_commands<'b, T, I>(&mut self, cmd_buffers: I)
    where
        T: 'b + Submittable<B, Graphics, Secondary>,
        I: IntoIterator<Item = &'b T>,
    {
        self.0.execute_commands(cmd_buffers)
    }

    /// Starts a new subpass with inline commands.
    pub fn next_subpass_inline(mut self) -> RenderPassInlineEncoder<'a, B> {
        unsafe {
            self.0.next_subpass(SubpassContents::Inline);
            let cmb = std::ptr::read(&mut self.0);
            std::mem::forget(self); // Prevent `end_render_pass`
            RenderPassInlineEncoder(RenderSubpassCommon::new(cmb))
        }
    }

    /// Starts a new subpass with secondary command buffers.
    pub fn next_subpass_secondary(self) -> Self {
        unsafe {
            self.0.next_subpass(SubpassContents::SecondaryBuffers);
        }
        self
    }
}

impl<'a, B: Backend> Drop for RenderPassSecondaryEncoder<'a, B> {
    fn drop(&mut self) {
        unsafe {
            self.0.end_render_pass();
        }
    }
}

/// A secondary command buffer recorded entirely within a subpass.
#[derive(Debug)]
pub struct SubpassCommandBuffer<B: Backend, S: Shot, R = <B as Backend>::CommandBuffer>(
    RenderSubpassCommon<B, R>,
    PhantomData<S>,
);
impl<B: Backend, S: Shot> SubpassCommandBuffer<B, S> {
    /// Wraps the given `CommandBuffer` in a `SubpassCommandBuffer`, starting
    /// to record a new subpass.
    pub unsafe fn new(raw: B::CommandBuffer) -> Self {
        SubpassCommandBuffer(RenderSubpassCommon::new(raw), PhantomData)
    }

    /// Finish recording commands to the command buffer.
    ///
    /// The command pool must be reset to able to re-record commands.
    pub unsafe fn finish(&mut self) {
        self.0.cmb.finish();
    }
}

impl<B: Backend> SubpassCommandBuffer<B, OneShot> {
    /// Begin recording a one-shot sub-pass command buffer.
    pub unsafe fn begin<'a>(
        &mut self,
        subpass: pass::Subpass<'a, B>,
        framebuffer: Option<&'a B::Framebuffer>,
    ) {
        let flags = CommandBufferFlags::RENDER_PASS_CONTINUE | CommandBufferFlags::ONE_TIME_SUBMIT;
        let inheritance_info = CommandBufferInheritanceInfo {
            subpass: Some(subpass),
            framebuffer,
            ..CommandBufferInheritanceInfo::default()
        };
        self.0.cmb.begin(flags, inheritance_info);
    }
}

impl<B: Backend> SubpassCommandBuffer<B, MultiShot> {
    /// Begin recording a one-shot sub-pass command buffer.
    pub unsafe fn begin<'a>(
        &mut self,
        allow_pending_resubmit: bool,
        subpass: pass::Subpass<'a, B>,
        framebuffer: Option<&'a B::Framebuffer>,
    ) {
        let mut flags = CommandBufferFlags::RENDER_PASS_CONTINUE;
        if allow_pending_resubmit {
            flags |= CommandBufferFlags::SIMULTANEOUS_USE;
        }
        let inheritance_info = CommandBufferInheritanceInfo {
            subpass: Some(subpass),
            framebuffer,
            ..CommandBufferInheritanceInfo::default()
        };
        self.0.cmb.begin(flags, inheritance_info);
    }
}

impl<B: Backend, S: Shot> Deref for SubpassCommandBuffer<B, S> {
    type Target = RenderSubpassCommon<B, B::CommandBuffer>;
    fn deref(&self) -> &RenderSubpassCommon<B, B::CommandBuffer> {
        &self.0
    }
}

impl<B: Backend, S: Shot> DerefMut for SubpassCommandBuffer<B, S> {
    fn deref_mut(&mut self) -> &mut RenderSubpassCommon<B, B::CommandBuffer> {
        &mut self.0
    }
}

impl<B, S, R> Borrow<R> for SubpassCommandBuffer<B, S, R>
where
    B: Backend<CommandBuffer = R>,
    S: Shot,
    R: RawCommandBuffer<B>,
{
    fn borrow(&self) -> &R {
        &self.0.cmb
    }
}

impl<B, C, S> Submittable<B, C, Secondary> for SubpassCommandBuffer<B, S>
where
    B: Backend,
    C: Capability + Supports<Graphics>,
    S: Shot,
{
}

impl<B, S> IntoRawCommandBuffer<B, Graphics> for SubpassCommandBuffer<B, S>
where
    B: Backend,
    S: Shot,
{
    fn into_raw(self) -> B::CommandBuffer {
        self.0.cmb
    }
}