vulkano 0.34.0

Safe wrapper for the Vulkan graphics API
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
478
479
480
481
482
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! Configures the area of the framebuffer that pixels will be written to.
//!
//! There are two different concepts to determine where things will be drawn:
//!
//! - The viewport is the region of the image which corresponds to the vertex coordinates `-1.0` to
//!   `1.0`.
//! - Any pixel outside of the scissor box will be discarded.
//!
//! In other words, modifying the viewport will stretch the image, while modifying the scissor
//! box acts like a filter.
//!
//! It is legal and sensible to use a viewport that is larger than the target image or that
//! only partially overlaps the target image.
//!
//! # Multiple viewports
//!
//! In most situations, you only need a single viewport and a single scissor box.
//!
//! If, however, you use a geometry shader, you can specify multiple viewports and scissor boxes.
//! Then in your geometry shader you can specify in which viewport and scissor box the primitive
//! should be written to. In GLSL this is done by writing to the special variable
//! `gl_ViewportIndex`.
//!
//! If you don't use a geometry shader or use a geometry shader where don't set which viewport to
//! use, then the first viewport and scissor box will be used.
//!
//! # Dynamic and fixed
//!
//! Vulkan allows four different setups:
//!
//! - The state of both the viewports and scissor boxes is known at pipeline creation.
//! - The state of viewports is known at pipeline creation, but the state of scissor boxes is
//!   only known when submitting the draw command.
//! - The state of scissor boxes is known at pipeline creation, but the state of viewports is
//!   only known when submitting the draw command.
//! - The state of both the viewports and scissor boxes is only known when submitting the
//!   draw command.
//!
//! In all cases the number of viewports and scissor boxes must be the same.
//!

use crate::{device::Device, Requires, RequiresAllOf, RequiresOneOf, ValidationError, Version};
use smallvec::{smallvec, SmallVec};
use std::ops::RangeInclusive;

/// List of viewports and scissors that are used when creating a graphics pipeline object.
///
/// Note that the number of viewports and scissors must be the same.
#[derive(Clone, Debug)]
pub struct ViewportState {
    /// Specifies the viewport transforms.
    ///
    /// When [`DynamicState::Viewport`] is used, the values of each viewport are ignored
    /// and must be set dynamically, but the number of viewports is fixed and
    /// must be matched when setting the dynamic value.
    /// When [`DynamicState::ViewportWithCount`] is used, the number of viewports is also dynamic,
    /// and `viewports` must be empty.
    ///
    /// If neither the number of viewports nor the number of scissors is dynamic, then the
    /// number of both must be identical.
    ///
    /// The default value is a single element of `Viewport::default()`.
    ///
    /// [`DynamicState::Viewport`]: crate::pipeline::DynamicState::Viewport
    /// [`DynamicState::ViewportWithCount`]: crate::pipeline::DynamicState::ViewportWithCount
    pub viewports: SmallVec<[Viewport; 1]>,

    /// Specifies the scissor rectangles.
    ///
    /// When [`DynamicState::Scissor`] is used, the values of each scissor are ignored
    /// and must be set dynamically, but the number of scissors is fixed and
    /// must be matched when setting the dynamic value.
    /// When [`DynamicState::ScissorWithCount`] is used, the number of scissors is also dynamic,
    /// and `scissors` must be empty.
    ///
    /// If neither the number of viewports nor the number of scissors is dynamic, then the
    /// number of both must be identical.
    ///
    /// The default value is a single element of `Scissor::default()`.
    ///
    /// [`DynamicState::Scissor`]: crate::pipeline::DynamicState::Scissor
    /// [`DynamicState::ScissorWithCount`]: crate::pipeline::DynamicState::ScissorWithCount
    pub scissors: SmallVec<[Scissor; 1]>,

    pub _ne: crate::NonExhaustive,
}

impl Default for ViewportState {
    #[inline]
    fn default() -> Self {
        Self {
            viewports: smallvec![Viewport::default()],
            scissors: smallvec![Scissor::default()],
            _ne: crate::NonExhaustive(()),
        }
    }
}

impl ViewportState {
    /// Creates a `ViewportState` with fixed state and no viewports or scissors.
    #[deprecated(since = "0.34.0")]
    #[inline]
    pub fn new() -> Self {
        Self {
            viewports: SmallVec::new(),
            scissors: SmallVec::new(),
            _ne: crate::NonExhaustive(()),
        }
    }

    /// Creates a `ViewportState` with fixed state from the given viewports and scissors.
    #[deprecated(since = "0.34.0")]
    pub fn viewport_fixed_scissor_fixed(
        data: impl IntoIterator<Item = (Viewport, Scissor)>,
    ) -> Self {
        let (viewports, scissors) = data.into_iter().unzip();
        Self {
            viewports,
            scissors,
            _ne: crate::NonExhaustive(()),
        }
    }

    /// Creates a `ViewportState` with fixed state from the given viewports, and matching scissors
    /// that cover the whole viewport.
    #[deprecated(since = "0.34.0")]
    pub fn viewport_fixed_scissor_irrelevant(data: impl IntoIterator<Item = Viewport>) -> Self {
        let viewports: SmallVec<_> = data.into_iter().collect();
        let scissors = smallvec![Scissor::default(); viewports.len()];
        Self {
            viewports,
            scissors,
            _ne: crate::NonExhaustive(()),
        }
    }

    pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
        let Self {
            viewports,
            scissors,
            _ne: _,
        } = self;

        let properties = device.physical_device().properties();

        for (index, viewport) in viewports.iter().enumerate() {
            viewport
                .validate(device)
                .map_err(|err| err.add_context(format!("viewports[{}].0", index)))?;
        }

        for (index, scissor) in scissors.iter().enumerate() {
            let &Scissor { offset, extent } = scissor;

            // VUID-VkPipelineViewportStateCreateInfo-x-02821
            // Ensured by the use of an unsigned integer.

            if (i32::try_from(offset[0]).ok())
                .zip(i32::try_from(extent[0]).ok())
                .and_then(|(o, e)| o.checked_add(e))
                .is_none()
            {
                return Err(Box::new(ValidationError {
                    context: format!("scissors[{}]", index).into(),
                    problem: "`offset[0] + extent[0]` is greater than `i32::MAX`".into(),
                    vuids: &["VUID-VkPipelineViewportStateCreateInfo-offset-02822"],
                    ..Default::default()
                }));
            }

            if (i32::try_from(offset[1]).ok())
                .zip(i32::try_from(extent[1]).ok())
                .and_then(|(o, e)| o.checked_add(e))
                .is_none()
            {
                return Err(Box::new(ValidationError {
                    context: format!("scissors[{}]", index).into(),
                    problem: "`offset[1] + extent[1]` is greater than `i32::MAX`".into(),
                    vuids: &["VUID-VkPipelineViewportStateCreateInfo-offset-02823"],
                    ..Default::default()
                }));
            }
        }

        if viewports.len() > 1 && !device.enabled_features().multi_viewport {
            return Err(Box::new(ValidationError {
                context: "viewports".into(),
                problem: "the length is greater than 1".into(),
                requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::Feature(
                    "multi_viewport",
                )])]),
                vuids: &["VUID-VkPipelineViewportStateCreateInfo-viewportCount-01216"],
            }));
        }

        if scissors.len() > 1 && !device.enabled_features().multi_viewport {
            return Err(Box::new(ValidationError {
                context: "scissors".into(),
                problem: "the length is greater than 1".into(),
                requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::Feature(
                    "multi_viewport",
                )])]),
                vuids: &["VUID-VkPipelineViewportStateCreateInfo-scissorCount-01217"],
            }));
        }

        if viewports.len() > properties.max_viewports as usize {
            return Err(Box::new(ValidationError {
                context: "viewports".into(),
                problem: "the length exceeds the `max_viewports` limit".into(),
                vuids: &["VUID-VkPipelineViewportStateCreateInfo-viewportCount-01218"],
                ..Default::default()
            }));
        }

        if scissors.len() > properties.max_viewports as usize {
            return Err(Box::new(ValidationError {
                context: "scissors".into(),
                problem: "the length exceeds the `max_viewports` limit".into(),
                vuids: &["VUID-VkPipelineViewportStateCreateInfo-scissorCount-01219"],
                ..Default::default()
            }));
        }

        Ok(())
    }
}

/// State of a single viewport.
#[derive(Debug, Clone, PartialEq)]
pub struct Viewport {
    /// Coordinates in pixels of the top-left hand corner of the viewport.
    ///
    /// The default value is `[0.0; 2]`.
    pub offset: [f32; 2],

    /// Dimensions in pixels of the viewport.
    ///
    /// The default value is `[1.0; 2]`, which you probably want to override if you are not
    /// using dynamic state.
    pub extent: [f32; 2],

    /// Minimum and maximum values of the depth.
    ///
    /// The values `0.0` to `1.0` of each vertex's Z coordinate will be mapped to this
    /// `depth_range` before being compared to the existing depth value.
    ///
    /// This is equivalents to `glDepthRange` in OpenGL, except that OpenGL uses the Z coordinate
    /// range from `-1.0` to `1.0` instead.
    ///
    /// The default value is `0.0..=1.0`.
    pub depth_range: RangeInclusive<f32>,
}

impl Default for Viewport {
    #[inline]
    fn default() -> Self {
        Self {
            offset: [0.0; 2],
            extent: [1.0; 2],
            depth_range: 0.0..=1.0,
        }
    }
}

impl Viewport {
    pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
        let &Self {
            offset,
            extent,
            ref depth_range,
        } = self;

        let properties = device.physical_device().properties();

        if extent[0] <= 0.0 {
            return Err(Box::new(ValidationError {
                context: "extent[0]".into(),
                problem: "is not greater than zero".into(),
                vuids: &["VUID-VkViewport-width-01770"],
                ..Default::default()
            }));
        }

        if extent[0] > properties.max_viewport_dimensions[0] as f32 {
            return Err(Box::new(ValidationError {
                context: "extent[0]".into(),
                problem: "exceeds the `max_viewport_dimensions[0]` limit".into(),
                vuids: &["VUID-VkViewport-width-01771"],
                ..Default::default()
            }));
        }

        if extent[1] <= 0.0
            && !(device.api_version() >= Version::V1_1
                || device.enabled_extensions().khr_maintenance1)
        {
            return Err(Box::new(ValidationError {
                context: "extent[1]".into(),
                problem: "is not greater than zero".into(),
                requires_one_of: RequiresOneOf(&[
                    RequiresAllOf(&[Requires::APIVersion(Version::V1_1)]),
                    RequiresAllOf(&[Requires::DeviceExtension("khr_maintenance1")]),
                ]),
                vuids: &["VUID-VkViewport-apiVersion-07917"],
            }));
        }

        if extent[1].abs() > properties.max_viewport_dimensions[1] as f32 {
            return Err(Box::new(ValidationError {
                context: "extent[1]".into(),
                problem: "exceeds the `max_viewport_dimensions[1]` limit".into(),
                vuids: &["VUID-VkViewport-height-01773"],
                ..Default::default()
            }));
        }

        if offset[0] < properties.viewport_bounds_range[0] {
            return Err(Box::new(ValidationError {
                problem: "`offset[0]` is less than the `viewport_bounds_range[0]` property".into(),
                vuids: &["VUID-VkViewport-x-01774"],
                ..Default::default()
            }));
        }

        if offset[0] + extent[0] > properties.viewport_bounds_range[1] {
            return Err(Box::new(ValidationError {
                problem: "`offset[0] + extent[0]` is greater than the \
                    `viewport_bounds_range[1]` property"
                    .into(),
                vuids: &["VUID-VkViewport-x-01232"],
                ..Default::default()
            }));
        }

        if offset[1] < properties.viewport_bounds_range[0] {
            return Err(Box::new(ValidationError {
                problem: "`offset[1]` is less than the `viewport_bounds_range[0]` property".into(),
                vuids: &["VUID-VkViewport-y-01775"],
                ..Default::default()
            }));
        }

        if offset[1] > properties.viewport_bounds_range[1] {
            return Err(Box::new(ValidationError {
                problem: "`offset[1]` is greater than the `viewport_bounds_range[1]` property"
                    .into(),
                vuids: &["VUID-VkViewport-y-01776"],
                ..Default::default()
            }));
        }

        if offset[1] + extent[1] < properties.viewport_bounds_range[0] {
            return Err(Box::new(ValidationError {
                problem: "`offset[1] + extent[1]` is less than the \
                    `viewport_bounds_range[0]` property"
                    .into(),
                vuids: &["VUID-VkViewport-y-01777"],
                ..Default::default()
            }));
        }

        if offset[1] + extent[1] > properties.viewport_bounds_range[1] {
            return Err(Box::new(ValidationError {
                problem: "`offset[1] + extent[1]` is greater than the \
                    `viewport_bounds_range[1]` property"
                    .into(),
                vuids: &["VUID-VkViewport-y-01233"],
                ..Default::default()
            }));
        }

        if !device.enabled_extensions().ext_depth_range_unrestricted {
            if *depth_range.start() < 0.0 || *depth_range.start() > 1.0 {
                return Err(Box::new(ValidationError {
                    problem: "`depth_range.start` is not between 0.0 and 1.0 inclusive".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_depth_range_unrestricted",
                    )])]),
                    vuids: &["VUID-VkViewport-minDepth-01234"],
                    ..Default::default()
                }));
            }

            if *depth_range.end() < 0.0 || *depth_range.end() > 1.0 {
                return Err(Box::new(ValidationError {
                    problem: "`depth_range.end` is not between 0.0 and 1.0 inclusive".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_depth_range_unrestricted",
                    )])]),
                    vuids: &["VUID-VkViewport-maxDepth-01235"],
                    ..Default::default()
                }));
            }
        }

        Ok(())
    }
}

impl From<&Viewport> for ash::vk::Viewport {
    #[inline]
    fn from(val: &Viewport) -> Self {
        ash::vk::Viewport {
            x: val.offset[0],
            y: val.offset[1],
            width: val.extent[0],
            height: val.extent[1],
            min_depth: *val.depth_range.start(),
            max_depth: *val.depth_range.end(),
        }
    }
}

/// A two-dimensional subregion.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scissor {
    /// Coordinates of the top-left hand corner of the box.
    ///
    /// The default value is `[0; 2]`.
    pub offset: [u32; 2],

    /// Dimensions of the box.
    ///
    /// The default value is `[i32::MAX; 2]`.
    pub extent: [u32; 2],
}

impl Default for Scissor {
    #[inline]
    fn default() -> Scissor {
        Self {
            offset: [0; 2],
            extent: [i32::MAX as u32; 2],
        }
    }
}

impl Scissor {
    /// Returns a scissor that, when used, will instruct the pipeline to draw to the entire
    /// framebuffer no matter its size.
    #[deprecated(since = "0.34.0", note = "use `Scissor::default` instead")]
    #[inline]
    pub fn irrelevant() -> Scissor {
        Self::default()
    }
}

impl From<&Scissor> for ash::vk::Rect2D {
    #[inline]
    fn from(val: &Scissor) -> Self {
        ash::vk::Rect2D {
            offset: ash::vk::Offset2D {
                x: val.offset[0] as i32,
                y: val.offset[1] as i32,
            },
            extent: ash::vk::Extent2D {
                width: val.extent[0],
                height: val.extent[1],
            },
        }
    }
}

impl From<ash::vk::Rect2D> for Scissor {
    #[inline]
    fn from(val: ash::vk::Rect2D) -> Self {
        Scissor {
            offset: [val.offset.x as u32, val.offset.y as u32],
            extent: [val.extent.width, val.extent.height],
        }
    }
}