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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
// 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.
//! Low level implementation of buffers.
//!
//! This module contains low-level wrappers around the Vulkan buffer types. All
//! other buffer types of this library, and all custom buffer types
//! that you create must wrap around the types in this module.
use super::{Buffer, BufferCreateFlags, BufferMemory, BufferUsage};
use crate::{
buffer::ExternalBufferInfo,
device::{Device, DeviceOwned},
instance::InstanceOwnedDebugWrapper,
macros::impl_id_counter,
memory::{
allocator::{AllocationType, DeviceLayout},
is_aligned, DedicatedTo, ExternalMemoryHandleTypes, MemoryAllocateFlags,
MemoryPropertyFlags, MemoryRequirements, ResourceMemory,
},
sync::Sharing,
DeviceSize, Requires, RequiresAllOf, RequiresOneOf, Validated, ValidationError, Version,
VulkanError, VulkanObject,
};
use smallvec::SmallVec;
use std::{mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
/// A raw buffer, with no memory backing it.
///
/// This is the basic buffer type, a direct translation of a `VkBuffer` object, but it is mostly
/// useless in this form. After creating a raw buffer, you must call `bind_memory` to make a
/// complete buffer object.
#[derive(Debug)]
pub struct RawBuffer {
handle: ash::vk::Buffer,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
flags: BufferCreateFlags,
size: DeviceSize,
usage: BufferUsage,
sharing: Sharing<SmallVec<[u32; 4]>>,
external_memory_handle_types: ExternalMemoryHandleTypes,
memory_requirements: MemoryRequirements,
}
impl RawBuffer {
/// Creates a new `RawBuffer`.
///
/// # Panics
///
/// - Panics if `create_info.sharing` is [`Concurrent`](Sharing::Concurrent) with less than 2
/// items.
/// - Panics if `create_info.size` is zero.
/// - Panics if `create_info.usage` is empty.
#[inline]
pub fn new(
device: Arc<Device>,
create_info: BufferCreateInfo,
) -> Result<Self, Validated<VulkanError>> {
Self::validate_new(&device, &create_info)?;
unsafe { Ok(Self::new_unchecked(device, create_info)?) }
}
fn validate_new(
device: &Device,
create_info: &BufferCreateInfo,
) -> Result<(), Box<ValidationError>> {
create_info
.validate(device)
.map_err(|err| err.add_context("create_info"))?;
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
pub unsafe fn new_unchecked(
device: Arc<Device>,
create_info: BufferCreateInfo,
) -> Result<Self, VulkanError> {
let &BufferCreateInfo {
flags,
ref sharing,
size,
usage,
external_memory_handle_types,
_ne: _,
} = &create_info;
let (sharing_mode, queue_family_index_count, p_queue_family_indices) = match sharing {
Sharing::Exclusive => (ash::vk::SharingMode::EXCLUSIVE, 0, &[] as _),
Sharing::Concurrent(queue_family_indices) => (
ash::vk::SharingMode::CONCURRENT,
queue_family_indices.len() as u32,
queue_family_indices.as_ptr(),
),
};
let mut create_info_vk = ash::vk::BufferCreateInfo {
flags: flags.into(),
size,
usage: usage.into(),
sharing_mode,
queue_family_index_count,
p_queue_family_indices,
..Default::default()
};
let mut external_memory_info_vk = None;
if !external_memory_handle_types.is_empty() {
let _ = external_memory_info_vk.insert(ash::vk::ExternalMemoryBufferCreateInfo {
handle_types: external_memory_handle_types.into(),
..Default::default()
});
}
if let Some(next) = external_memory_info_vk.as_mut() {
next.p_next = create_info_vk.p_next;
create_info_vk.p_next = next as *const _ as *const _;
}
let handle = {
let fns = device.fns();
let mut output = MaybeUninit::uninit();
(fns.v1_0.create_buffer)(
device.handle(),
&create_info_vk,
ptr::null(),
output.as_mut_ptr(),
)
.result()
.map_err(VulkanError::from)?;
output.assume_init()
};
Ok(Self::from_handle(device, handle, create_info))
}
/// Creates a new `RawBuffer` from a raw object handle.
///
/// # Safety
///
/// - `handle` must be a valid Vulkan object handle created from `device`.
/// - `handle` must refer to a buffer that has not yet had memory bound to it.
/// - `create_info` must match the info used to create the object.
#[inline]
pub unsafe fn from_handle(
device: Arc<Device>,
handle: ash::vk::Buffer,
create_info: BufferCreateInfo,
) -> Self {
let BufferCreateInfo {
flags,
size,
usage,
sharing,
external_memory_handle_types,
_ne: _,
} = create_info;
let mut memory_requirements = Self::get_memory_requirements(&device, handle);
debug_assert!(memory_requirements.layout.size() >= size);
debug_assert!(memory_requirements.memory_type_bits != 0);
// We have to manually enforce some additional requirements for some buffer types.
let properties = device.physical_device().properties();
if usage.intersects(BufferUsage::UNIFORM_TEXEL_BUFFER | BufferUsage::STORAGE_TEXEL_BUFFER) {
memory_requirements.layout = memory_requirements
.layout
.align_to(properties.min_texel_buffer_offset_alignment)
.unwrap();
}
if usage.intersects(BufferUsage::STORAGE_BUFFER) {
memory_requirements.layout = memory_requirements
.layout
.align_to(properties.min_storage_buffer_offset_alignment)
.unwrap();
}
if usage.intersects(BufferUsage::UNIFORM_BUFFER) {
memory_requirements.layout = memory_requirements
.layout
.align_to(properties.min_uniform_buffer_offset_alignment)
.unwrap();
}
RawBuffer {
handle,
device: InstanceOwnedDebugWrapper(device),
id: Self::next_id(),
flags,
size,
usage,
sharing,
external_memory_handle_types,
memory_requirements,
}
}
fn get_memory_requirements(device: &Device, handle: ash::vk::Buffer) -> MemoryRequirements {
let info_vk = ash::vk::BufferMemoryRequirementsInfo2 {
buffer: handle,
..Default::default()
};
let mut memory_requirements2_vk = ash::vk::MemoryRequirements2::default();
let mut memory_dedicated_requirements_vk = None;
if device.api_version() >= Version::V1_1
|| device.enabled_extensions().khr_dedicated_allocation
{
debug_assert!(
device.api_version() >= Version::V1_1
|| device.enabled_extensions().khr_get_memory_requirements2
);
let next = memory_dedicated_requirements_vk
.insert(ash::vk::MemoryDedicatedRequirements::default());
next.p_next = memory_requirements2_vk.p_next;
memory_requirements2_vk.p_next = next as *mut _ as *mut _;
}
unsafe {
let fns = device.fns();
if device.api_version() >= Version::V1_1
|| device.enabled_extensions().khr_get_memory_requirements2
{
if device.api_version() >= Version::V1_1 {
(fns.v1_1.get_buffer_memory_requirements2)(
device.handle(),
&info_vk,
&mut memory_requirements2_vk,
);
} else {
(fns.khr_get_memory_requirements2
.get_buffer_memory_requirements2_khr)(
device.handle(),
&info_vk,
&mut memory_requirements2_vk,
);
}
} else {
(fns.v1_0.get_buffer_memory_requirements)(
device.handle(),
handle,
&mut memory_requirements2_vk.memory_requirements,
);
}
}
MemoryRequirements {
layout: DeviceLayout::from_size_alignment(
memory_requirements2_vk.memory_requirements.size,
memory_requirements2_vk.memory_requirements.alignment,
)
.unwrap(),
memory_type_bits: memory_requirements2_vk.memory_requirements.memory_type_bits,
prefers_dedicated_allocation: memory_dedicated_requirements_vk
.map_or(false, |dreqs| dreqs.prefers_dedicated_allocation != 0),
requires_dedicated_allocation: memory_dedicated_requirements_vk
.map_or(false, |dreqs| dreqs.requires_dedicated_allocation != 0),
}
}
/// Binds device memory to this buffer.
pub fn bind_memory(
self,
allocation: ResourceMemory,
) -> Result<Buffer, (Validated<VulkanError>, RawBuffer, ResourceMemory)> {
if let Err(err) = self.validate_bind_memory(&allocation) {
return Err((err.into(), self, allocation));
}
unsafe { self.bind_memory_unchecked(allocation) }
.map_err(|(err, buffer, allocation)| (err.into(), buffer, allocation))
}
fn validate_bind_memory(
&self,
allocation: &ResourceMemory,
) -> Result<(), Box<ValidationError>> {
assert_ne!(allocation.allocation_type(), AllocationType::NonLinear);
let physical_device = self.device().physical_device();
let memory_requirements = &self.memory_requirements;
let memory = allocation.device_memory();
let memory_offset = allocation.offset();
let memory_type =
&physical_device.memory_properties().memory_types[memory.memory_type_index() as usize];
// VUID-VkBindBufferMemoryInfo-commonparent
assert_eq!(self.device(), memory.device());
// VUID-VkBindBufferMemoryInfo-buffer-07459
// Ensured by taking ownership of `RawBuffer`.
// VUID-VkBindBufferMemoryInfo-buffer-01030
// Currently ensured by not having sparse binding flags, but this needs to be checked once
// those are enabled.
// VUID-VkBindBufferMemoryInfo-memoryOffset-01031
// Assume that `allocation` was created correctly.
if memory_requirements.memory_type_bits & (1 << memory.memory_type_index()) == 0 {
return Err(Box::new(ValidationError {
problem: "`allocation.device_memory().memory_type_index()` is not a bit set in \
`self.memory_requirements().memory_type_bits`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-memory-01035"],
..Default::default()
}));
}
if !is_aligned(memory_offset, memory_requirements.layout.alignment()) {
return Err(Box::new(ValidationError {
problem: "`allocation.offset()` is not aligned according to \
`self.memory_requirements().layout.alignment()`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-memoryOffset-01036"],
..Default::default()
}));
}
if allocation.size() < memory_requirements.layout.size() {
return Err(Box::new(ValidationError {
problem: "`allocation.size()` is less than \
`self.memory_requirements().layout.size()`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-size-01037"],
..Default::default()
}));
}
if let Some(dedicated_to) = memory.dedicated_to() {
match dedicated_to {
DedicatedTo::Buffer(id) if id == self.id => {}
_ => {
return Err(Box::new(ValidationError {
problem: "`allocation.device_memory()` is a dedicated allocation, but \
it is not dedicated to this buffer"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-memory-01508"],
..Default::default()
}));
}
}
debug_assert!(memory_offset == 0); // This should be ensured by the allocator
} else {
if memory_requirements.requires_dedicated_allocation {
return Err(Box::new(ValidationError {
problem: "`self.memory_requirements().requires_dedicated_allocation` is \
`true`, but `allocation.device_memory()` is not a dedicated allocation"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-buffer-01444"],
..Default::default()
}));
}
}
if memory_type
.property_flags
.intersects(MemoryPropertyFlags::PROTECTED)
{
return Err(Box::new(ValidationError {
problem: "the `property_flags` of the memory type of \
`allocation.device_memory()` contains `MemoryPropertyFlags::PROTECTED`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-None-01899"],
..Default::default()
}));
}
if !memory.export_handle_types().is_empty() {
if !self
.external_memory_handle_types
.intersects(memory.export_handle_types())
{
return Err(Box::new(ValidationError {
problem:
"`allocation.device_memory().export_handle_types()` is not empty, but \
it does not share at least one handle type with \
`self.external_memory_handle_types()`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-memory-02726"],
..Default::default()
}));
}
for handle_type in memory.export_handle_types() {
let external_buffer_properties = unsafe {
physical_device.external_buffer_properties_unchecked(ExternalBufferInfo {
flags: self.flags,
usage: self.usage,
handle_type,
_ne: crate::NonExhaustive(()),
})
};
if external_buffer_properties
.external_memory_properties
.dedicated_only
&& !memory.is_dedicated()
{
return Err(Box::new(ValidationError {
problem: format!(
"`allocation.device_memory().export_handle_types()` has the `{:?}` \
flag set, which requires a dedicated allocation as returned by \
`PhysicalDevice::external_buffer_properties`, but \
`allocation.device_memory()` is not a dedicated allocation",
handle_type,
)
.into(),
vuids: &["VUID-VkMemoryAllocateInfo-pNext-00639"],
..Default::default()
}));
}
if !external_buffer_properties
.external_memory_properties
.exportable
{
return Err(Box::new(ValidationError {
problem: format!(
"`allocation.device_memory().export_handle_types()` has the `{:?}` \
flag set, but the flag is not supported for exporting, as returned by \
`PhysicalDevice::external_buffer_properties`",
handle_type,
)
.into(),
vuids: &["VUID-VkExportMemoryAllocateInfo-handleTypes-00656"],
..Default::default()
}));
}
if !external_buffer_properties
.external_memory_properties
.compatible_handle_types
.contains(memory.export_handle_types())
{
return Err(Box::new(ValidationError {
problem: format!(
"`allocation.device_memory().export_handle_types()` has the `{:?}` \
flag set, but the flag is not compatible with the other flags set, as \
returned by `PhysicalDevice::external_buffer_properties`",
handle_type,
)
.into(),
vuids: &["VUID-VkExportMemoryAllocateInfo-handleTypes-00656"],
..Default::default()
}));
}
}
}
if let Some(handle_type) = memory.imported_handle_type() {
if !self.external_memory_handle_types.contains_enum(handle_type) {
return Err(Box::new(ValidationError {
problem: "`allocation.device_memory()` is imported, but \
`self.external_memory_handle_types()` does not contain the imported \
handle type"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-memory-02985"],
..Default::default()
}));
}
}
if !self.device.enabled_extensions().ext_buffer_device_address
&& self.usage.intersects(BufferUsage::SHADER_DEVICE_ADDRESS)
&& !memory
.flags()
.intersects(MemoryAllocateFlags::DEVICE_ADDRESS)
{
return Err(Box::new(ValidationError {
problem: "`self.usage()` contains `BufferUsage::SHADER_DEVICE_ADDRESS`, but \
`allocation.device_memory().flags()` does not contain \
`MemoryAllocateFlags::DEVICE_ADDRESS`"
.into(),
vuids: &["VUID-VkBindBufferMemoryInfo-bufferDeviceAddress-03339"],
..Default::default()
}));
}
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
pub unsafe fn bind_memory_unchecked(
self,
allocation: ResourceMemory,
) -> Result<Buffer, (VulkanError, RawBuffer, ResourceMemory)> {
let memory = allocation.device_memory();
let memory_offset = allocation.offset();
let fns = self.device.fns();
let result = if self.device.api_version() >= Version::V1_1
|| self.device.enabled_extensions().khr_bind_memory2
{
let bind_infos_vk = [ash::vk::BindBufferMemoryInfo {
buffer: self.handle,
memory: memory.handle(),
memory_offset,
..Default::default()
}];
if self.device.api_version() >= Version::V1_1 {
(fns.v1_1.bind_buffer_memory2)(
self.device.handle(),
bind_infos_vk.len() as u32,
bind_infos_vk.as_ptr(),
)
} else {
(fns.khr_bind_memory2.bind_buffer_memory2_khr)(
self.device.handle(),
bind_infos_vk.len() as u32,
bind_infos_vk.as_ptr(),
)
}
} else {
(fns.v1_0.bind_buffer_memory)(
self.device.handle(),
self.handle,
memory.handle(),
memory_offset,
)
}
.result();
if let Err(err) = result {
return Err((VulkanError::from(err), self, allocation));
}
Ok(Buffer::from_raw(self, BufferMemory::Normal(allocation)))
}
/// Returns the memory requirements for this buffer.
pub fn memory_requirements(&self) -> &MemoryRequirements {
&self.memory_requirements
}
/// Returns the flags the buffer was created with.
#[inline]
pub fn flags(&self) -> BufferCreateFlags {
self.flags
}
/// Returns the size of the buffer in bytes.
#[inline]
pub fn size(&self) -> DeviceSize {
self.size
}
/// Returns the usage the buffer was created with.
#[inline]
pub fn usage(&self) -> BufferUsage {
self.usage
}
/// Returns the sharing the buffer was created with.
#[inline]
pub fn sharing(&self) -> &Sharing<SmallVec<[u32; 4]>> {
&self.sharing
}
/// Returns the external memory handle types that are supported with this buffer.
#[inline]
pub fn external_memory_handle_types(&self) -> ExternalMemoryHandleTypes {
self.external_memory_handle_types
}
}
impl Drop for RawBuffer {
#[inline]
fn drop(&mut self) {
unsafe {
let fns = self.device.fns();
(fns.v1_0.destroy_buffer)(self.device.handle(), self.handle, ptr::null());
}
}
}
unsafe impl VulkanObject for RawBuffer {
type Handle = ash::vk::Buffer;
#[inline]
fn handle(&self) -> Self::Handle {
self.handle
}
}
unsafe impl DeviceOwned for RawBuffer {
#[inline]
fn device(&self) -> &Arc<Device> {
&self.device
}
}
impl_id_counter!(RawBuffer);
/// Parameters to create a new [`Buffer`].
#[derive(Clone, Debug)]
pub struct BufferCreateInfo {
/// Additional properties of the buffer.
///
/// The default value is empty.
pub flags: BufferCreateFlags,
/// Whether the buffer can be shared across multiple queues, or is limited to a single queue.
///
/// The default value is [`Sharing::Exclusive`].
pub sharing: Sharing<SmallVec<[u32; 4]>>,
/// The size in bytes of the buffer.
///
/// When using the [`Buffer`] constructors, you must leave this at `0`. They fill this field
/// based on the data type of the contents and the other parameters you provide, and then pass
/// this create-info to [`RawBuffer::new`]. You must override the default when constructing
/// [`RawBuffer`] directly.
///
/// The default value is `0`.
pub size: DeviceSize,
/// How the buffer is going to be used.
///
/// The default value is [`BufferUsage::empty()`], which must be overridden.
pub usage: BufferUsage,
/// The external memory handle types that are going to be used with the buffer.
///
/// If this value is not empty, then the device API version must be at least 1.1, or the
/// [`khr_external_memory`] extension must be enabled on the device.
///
/// The default value is [`ExternalMemoryHandleTypes::empty()`].
///
/// [`khr_external_memory`]: crate::device::DeviceExtensions::khr_external_memory
pub external_memory_handle_types: ExternalMemoryHandleTypes,
pub _ne: crate::NonExhaustive,
}
impl Default for BufferCreateInfo {
#[inline]
fn default() -> Self {
Self {
flags: BufferCreateFlags::empty(),
sharing: Sharing::Exclusive,
size: 0,
usage: BufferUsage::empty(),
external_memory_handle_types: ExternalMemoryHandleTypes::empty(),
_ne: crate::NonExhaustive(()),
}
}
}
impl BufferCreateInfo {
pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
let &Self {
flags,
ref sharing,
size,
usage,
external_memory_handle_types,
_ne: _,
} = self;
flags.validate_device(device).map_err(|err| {
err.add_context("flags")
.set_vuids(&["VUID-VkBufferCreateInfo-flags-parameter"])
})?;
usage.validate_device(device).map_err(|err| {
err.add_context("usage")
.set_vuids(&["VUID-VkBufferCreateInfo-usage-parameter"])
})?;
if usage.is_empty() {
return Err(Box::new(ValidationError {
context: "usage".into(),
problem: "is empty".into(),
vuids: &["VUID-VkBufferCreateInfo-usage-requiredbitmask"],
..Default::default()
}));
}
if size == 0 {
return Err(Box::new(ValidationError {
context: "size".into(),
problem: "is zero".into(),
vuids: &["VUID-VkBufferCreateInfo-size-00912"],
..Default::default()
}));
}
/* Enable when sparse binding is properly handled
if let Some(sparse_level) = sparse {
if !device.enabled_features().sparse_binding {
return Err(Box::new(ValidationError {
context: "sparse".into(),
problem: "is `Some`".into(),
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::Feature(
"sparse_binding",
)])]),
vuids: &["VUID-VkBufferCreateInfo-flags-00915"],
}));
}
if sparse_level.sparse_residency && !device.enabled_features().sparse_residency_buffer {
return Err(Box::new(ValidationError {
context: "sparse".into(),
problem: "contains `BufferCreateFlags::SPARSE_RESIDENCY`".into(),
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::Feature(
"sparse_residency_buffer",
)])]),
vuids: &["VUID-VkBufferCreateInfo-flags-00916"],
}));
}
if sparse_level.sparse_aliased && !device.enabled_features().sparse_residency_aliased {
return Err(Box::new(ValidationError {
context: "sparse".into(),
problem: "contains `BufferCreateFlags::SPARSE_ALIASED`".into(),
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::Feature(
"sparse_residency_aliased",
)])]),
vuids: &["VUID-VkBufferCreateInfo-flags-00917"],
}));
}
// TODO:
// VUID-VkBufferCreateInfo-flags-00918
}*/
match sharing {
Sharing::Exclusive => (),
Sharing::Concurrent(queue_family_indices) => {
if queue_family_indices.len() < 2 {
return Err(Box::new(ValidationError {
context: "sharing".into(),
problem: "is `Sharing::Concurrent`, but contains less than 2 elements"
.into(),
vuids: &["VUID-VkBufferCreateInfo-sharingMode-00914"],
..Default::default()
}));
}
let queue_family_count =
device.physical_device().queue_family_properties().len() as u32;
for (index, &queue_family_index) in queue_family_indices.iter().enumerate() {
if queue_family_indices[..index].contains(&queue_family_index) {
return Err(Box::new(ValidationError {
context: "queue_family_indices".into(),
problem: format!(
"the queue family index in the list at index {} is contained in \
the list more than once",
index,
)
.into(),
vuids: &["VUID-VkBufferCreateInfo-sharingMode-01419"],
..Default::default()
}));
}
if queue_family_index >= queue_family_count {
return Err(Box::new(ValidationError {
context: format!("sharing[{}]", index).into(),
problem: "is not less than the number of queue families in the device"
.into(),
vuids: &["VUID-VkBufferCreateInfo-sharingMode-01419"],
..Default::default()
}));
}
}
}
}
if let Some(max_buffer_size) = device.physical_device().properties().max_buffer_size {
if size > max_buffer_size {
return Err(Box::new(ValidationError {
context: "size".into(),
problem: "exceeds the `max_buffer_size` limit".into(),
vuids: &["VUID-VkBufferCreateInfo-size-06409"],
..Default::default()
}));
}
}
if !external_memory_handle_types.is_empty() {
if !(device.api_version() >= Version::V1_1
|| device.enabled_extensions().khr_external_memory)
{
return Err(Box::new(ValidationError {
context: "external_memory_handle_types".into(),
problem: "is not empty".into(),
requires_one_of: RequiresOneOf(&[
RequiresAllOf(&[Requires::APIVersion(Version::V1_1)]),
RequiresAllOf(&[Requires::DeviceExtension("khr_external_memory")]),
]),
..Default::default()
}));
}
external_memory_handle_types
.validate_device(device)
.map_err(|err| {
err.add_context("external_memory_handle_types")
.set_vuids(&["VUID-VkExternalMemoryBufferCreateInfo-handleTypes-parameter"])
})?;
// TODO:
// VUID-VkBufferCreateInfo-pNext-00920
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{BufferCreateInfo, BufferUsage, RawBuffer};
use crate::device::{Device, DeviceOwned};
#[test]
fn create() {
let (device, _) = gfx_dev_and_queue!();
let buf = RawBuffer::new(
device.clone(),
BufferCreateInfo {
size: 128,
usage: BufferUsage::TRANSFER_DST,
..Default::default()
},
)
.unwrap();
let reqs = buf.memory_requirements();
assert!(reqs.layout.size() >= 128);
assert_eq!(buf.size(), 128);
assert_eq!(&**buf.device() as *const Device, &*device as *const Device);
}
/* Re-enable when sparse binding is properly implemented
#[test]
fn missing_feature_sparse_binding() {
let (device, _) = gfx_dev_and_queue!();
match RawBuffer::new(
device,
BufferCreateInfo {
size: 128,
sparse: Some(BufferCreateFlags::empty()),
usage: BufferUsage::transfer_dst,
..Default::default()
},
) {
Err(BufferError::RequirementNotMet {
requires_one_of: RequiresOneOf { features, .. },
..
}) if features.contains(&"sparse_binding") => (),
_ => panic!(),
}
}
#[test]
fn missing_feature_sparse_residency() {
let (device, _) = gfx_dev_and_queue!(sparse_binding);
match RawBuffer::new(
device,
BufferCreateInfo {
size: 128,
sparse: Some(BufferCreateFlags {
sparse_residency: true,
sparse_aliased: false,
..Default::default()
}),
usage: BufferUsage::transfer_dst,
..Default::default()
},
) {
Err(BufferError::RequirementNotMet {
requires_one_of: RequiresOneOf { features, .. },
..
}) if features.contains(&"sparse_residency_buffer") => (),
_ => panic!(),
}
}
#[test]
fn missing_feature_sparse_aliased() {
let (device, _) = gfx_dev_and_queue!(sparse_binding);
match RawBuffer::new(
device,
BufferCreateInfo {
size: 128,
sparse: Some(BufferCreateFlags {
sparse_residency: false,
sparse_aliased: true,
..Default::default()
}),
usage: BufferUsage::transfer_dst,
..Default::default()
},
) {
Err(BufferError::RequirementNotMet {
requires_one_of: RequiresOneOf { features, .. },
..
}) if features.contains(&"sparse_residency_aliased") => (),
_ => panic!(),
}
}
*/
#[test]
fn create_empty_buffer() {
let (device, _) = gfx_dev_and_queue!();
if RawBuffer::new(
device,
BufferCreateInfo {
size: 0,
usage: BufferUsage::TRANSFER_DST,
..Default::default()
},
)
.is_ok()
{
panic!()
}
}
}