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
use {
super::{Device, DriverError},
archery::{SharedPointer, SharedPointerKind},
ash::vk,
derive_builder::Builder,
gpu_allocator::{
vulkan::{Allocation, AllocationCreateDesc},
MemoryLocation,
},
log::trace,
log::warn,
std::{
fmt::{Debug, Formatter},
ops::{Deref, Range},
thread::panicking,
},
};
pub struct Buffer<P>
where
P: SharedPointerKind,
{
allocation: Option<Allocation>,
buffer: vk::Buffer,
device: SharedPointer<Device<P>, P>,
pub info: BufferInfo,
pub name: Option<String>,
}
impl<P> Buffer<P>
where
P: SharedPointerKind,
{
pub fn create(
device: &SharedPointer<Device<P>, P>,
info: impl Into<BufferInfo>,
) -> Result<Self, DriverError> {
let info = info.into();
trace!("create: {:?}", info);
let device = SharedPointer::clone(device);
let buffer_info = vk::BufferCreateInfo {
size: info.size,
usage: info.usage,
sharing_mode: vk::SharingMode::EXCLUSIVE,
..Default::default()
};
let buffer = unsafe {
device.create_buffer(&buffer_info, None).map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?
};
let mut requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
if info
.usage
.contains(vk::BufferUsageFlags::SHADER_BINDING_TABLE_KHR)
{
requirements.alignment = requirements.alignment.max(64);
}
let memory_location = if info.can_map {
MemoryLocation::CpuToGpu
} else {
MemoryLocation::GpuOnly
};
let allocation = device
.allocator
.as_ref()
.unwrap()
.lock()
.allocate(&AllocationCreateDesc {
name: "buffer",
requirements,
location: memory_location,
linear: true,
})
.map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?;
unsafe {
device
.bind_buffer_memory(buffer, allocation.memory(), allocation.offset())
.map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?
};
Ok(Self {
allocation: Some(allocation),
buffer,
device,
info,
name: None,
})
}
pub fn copy_from_slice(this: &mut Self, offset: vk::DeviceSize, slice: &[u8]) {
Self::mapped_slice_mut(this)[offset as _..offset as usize + slice.len()]
.copy_from_slice(slice);
}
pub fn device_address(this: &Self) -> vk::DeviceAddress {
unsafe {
this.device.get_buffer_device_address(
&vk::BufferDeviceAddressInfo::builder().buffer(this.buffer),
)
}
}
pub fn mapped_ptr<T>(this: &Self) -> *mut T {
this.allocation
.as_ref()
.unwrap()
.mapped_ptr()
.unwrap()
.as_ptr() as *mut _
}
pub fn mapped_slice(this: &Self) -> &[u8] {
&this.allocation.as_ref().unwrap().mapped_slice().unwrap()[0..this.info.size as usize]
}
pub fn mapped_slice_mut(this: &mut Self) -> &mut [u8] {
&mut this
.allocation
.as_mut()
.unwrap()
.mapped_slice_mut()
.unwrap()[0..this.info.size as usize]
}
}
impl<P> Debug for Buffer<P>
where
P: SharedPointerKind,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(name) = &self.name {
write!(f, "{} ({:?})", name, self.buffer)
} else {
write!(f, "{:?}", self.buffer)
}
}
}
impl<P> Deref for Buffer<P>
where
P: SharedPointerKind,
{
type Target = vk::Buffer;
fn deref(&self) -> &Self::Target {
&self.buffer
}
}
impl<P> Drop for Buffer<P>
where
P: SharedPointerKind,
{
fn drop(&mut self) {
if panicking() {
return;
}
self.device
.allocator
.as_ref()
.unwrap()
.lock()
.free(self.allocation.take().unwrap())
.unwrap_or_else(|_| warn!("Unable to free buffer allocation"));
unsafe {
self.device.destroy_buffer(self.buffer, None);
}
}
}
#[derive(Builder, Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[builder(
build_fn(private, name = "fallible_build"),
derive(Debug),
pattern = "owned"
)]
pub struct BufferInfo {
pub size: vk::DeviceSize,
pub usage: vk::BufferUsageFlags,
#[builder(default)]
pub can_map: bool,
}
impl BufferInfo {
#[allow(clippy::new_ret_no_self)]
pub fn new(size: vk::DeviceSize, usage: vk::BufferUsageFlags) -> BufferInfoBuilder {
BufferInfoBuilder::default().size(size).usage(usage)
}
pub fn new_mappable(size: vk::DeviceSize, usage: vk::BufferUsageFlags) -> BufferInfoBuilder {
Self::new(
size,
usage | vk::BufferUsageFlags::TRANSFER_DST | vk::BufferUsageFlags::TRANSFER_SRC,
)
.can_map(true)
}
}
impl BufferInfoBuilder {
pub fn new(size: vk::DeviceSize, usage: vk::BufferUsageFlags) -> Self {
Self::default().size(size).usage(usage)
}
pub fn build(self) -> BufferInfo {
self.fallible_build()
.expect("All required fields set at initialization")
}
}
impl From<BufferInfoBuilder> for BufferInfo {
fn from(info: BufferInfoBuilder) -> Self {
info.build()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BufferSubresource {
pub start: vk::DeviceSize,
pub end: vk::DeviceSize,
}
impl From<BufferInfo> for BufferSubresource {
fn from(info: BufferInfo) -> Self {
Self {
start: 0,
end: info.size,
}
}
}
impl From<Range<vk::DeviceSize>> for BufferSubresource {
fn from(range: Range<vk::DeviceSize>) -> Self {
Self {
start: range.start,
end: range.end,
}
}
}
impl From<Option<Range<vk::DeviceSize>>> for BufferSubresource {
fn from(range: Option<Range<vk::DeviceSize>>) -> Self {
range.unwrap_or(0..vk::WHOLE_SIZE).into()
}
}
impl From<BufferSubresource> for Range<vk::DeviceSize> {
fn from(subresource: BufferSubresource) -> Self {
subresource.start..subresource.end
}
}