-
Notifications
You must be signed in to change notification settings - Fork 434
/
main.rs
472 lines (412 loc) · 17.5 KB
/
main.rs
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
// Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://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.
//
// This example demonstrates one way of preparing data structures and loading
// SPIRV shaders from external source (file system).
//
// Note that you will need to do all correctness checking by yourself.
//
// vert.glsl and frag.glsl must be built by yourself.
// One way of building them is to build Khronos' glslang and use
// glslangValidator tool:
// $ glslangValidator vert.glsl -V -S vert -o vert.spv
// $ glslangValidator frag.glsl -V -S frag -o frag.spv
// Vulkano uses glslangValidator to build your shaders internally.
use vulkano as vk;
use vulkano::buffer::BufferUsage;
use vulkano::buffer::cpu_access::CpuAccessibleBuffer;
use vulkano::command_buffer::AutoCommandBufferBuilder;
use vulkano::command_buffer::DynamicState;
use vulkano::descriptor::descriptor::DescriptorDesc;
use vulkano::descriptor::descriptor::ShaderStages;
use vulkano::descriptor::pipeline_layout::PipelineLayoutDesc;
use vulkano::descriptor::pipeline_layout::PipelineLayoutDescPcRange;
use vulkano::device::Device;
use vulkano::device::DeviceExtensions;
use vulkano::format::Format;
use vulkano::framebuffer::{Framebuffer, FramebufferAbstract, Subpass, RenderPassAbstract};
use vulkano::image::SwapchainImage;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::shader::{GraphicsShaderType, ShaderInterfaceDef, ShaderInterfaceDefEntry, ShaderModule};
use vulkano::pipeline::vertex::SingleBufferDefinition;
use vulkano::pipeline::viewport::Viewport;
use vulkano::swapchain::{AcquireError, PresentMode, SurfaceTransform, Swapchain, SwapchainCreationError, ColorSpace};
use vulkano::swapchain;
use vulkano::sync::{GpuFuture, FlushError};
use vulkano::sync;
use vulkano::instance::Instance;
use vulkano_win::VkSurfaceBuild;
use winit::window::{WindowBuilder, Window};
use winit::event_loop::{EventLoop, ControlFlow};
use winit::event::{Event, WindowEvent};
use std::borrow::Cow;
use std::ffi::CStr;
use std::fs::File;
use std::io::Read;
use std::sync::Arc;
#[derive(Default, Copy, Clone)]
pub struct Vertex {
pub position: [f32; 2],
pub color: [f32; 3],
}
vulkano::impl_vertex!(Vertex, position, color);
fn main() {
let required_extensions = vulkano_win::required_extensions();
let instance = Instance::new(None, &required_extensions, None).unwrap();
let physical = vk::instance::PhysicalDevice::enumerate(&instance).next().unwrap();
let event_loop = EventLoop::new();
let surface = WindowBuilder::new().build_vk_surface(&event_loop, instance.clone()).unwrap();
let queue_family = physical.queue_families().find(|&q| {
q.supports_graphics() && surface.is_supported(q).unwrap_or(false)
}).unwrap();
let (device, mut queues) = {
let device_ext = DeviceExtensions { khr_swapchain: true, .. DeviceExtensions::none() };
Device::new(physical, physical.supported_features(), &device_ext,
[(queue_family, 0.5)].iter().cloned()).unwrap()
};
let queue = queues.next().unwrap();
let (mut swapchain, images) = {
let caps = surface.capabilities(physical).unwrap();
let usage = caps.supported_usage_flags;
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
let format = caps.supported_formats[0].0;
let dimensions: [u32; 2] = surface.window().inner_size().into();
Swapchain::new(device.clone(), surface.clone(), caps.min_image_count, format, dimensions,
1, usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, true, ColorSpace::SrgbNonLinear).unwrap()
};
let render_pass = Arc::new(vulkano::single_pass_renderpass!(
device.clone(),
attachments: {
color: {
load: Clear,
store: Store,
format: swapchain.format(),
samples: 1,
}
},
pass: {
color: [color],
depth_stencil: {}
}
).unwrap());
let vs = {
let mut f = File::open("src/bin/runtime-shader/vert.spv")
.expect("Can't find file src/bin/runtime-shader/vert.spv This example needs to be run from the root of the example crate.");
let mut v = vec![];
f.read_to_end(&mut v).unwrap();
// Create a ShaderModule on a device the same Shader::load does it.
// NOTE: You will have to verify correctness of the data by yourself!
unsafe { ShaderModule::new(device.clone(), &v) }.unwrap()
};
let fs = {
let mut f = File::open("src/bin/runtime-shader/frag.spv")
.expect("Can't find file src/bin/runtime-shader/frag.spv");
let mut v = vec![];
f.read_to_end(&mut v).unwrap();
unsafe { ShaderModule::new(device.clone(), &v) }.unwrap()
};
// This structure will tell Vulkan how input entries of our vertex shader look like
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct VertInput;
unsafe impl ShaderInterfaceDef for VertInput {
type Iter = VertInputIter;
fn elements(&self) -> VertInputIter {
VertInputIter(0)
}
}
#[derive(Debug, Copy, Clone)]
struct VertInputIter(u16);
impl Iterator for VertInputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// There are things to consider when giving out entries:
// * There must be only one entry per one location, you can't have
// `color' and `position' entries both at 0..1 locations. They also
// should not overlap.
// * Format of each element must be no larger than 128 bits.
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 1..2,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("color"))
})
}
if self.0 == 1 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32Sfloat,
name: Some(Cow::Borrowed("position"))
})
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
// We must return exact number of entries left in iterator.
let len = (2 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for VertInputIter { }
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct VertOutput;
unsafe impl ShaderInterfaceDef for VertOutput {
type Iter = VertOutputIter;
fn elements(&self) -> VertOutputIter {
VertOutputIter(0)
}
}
// This structure will tell Vulkan how output entries (those passed to next
// stage) of our vertex shader look like.
#[derive(Debug, Copy, Clone)]
struct VertOutputIter(u16);
impl Iterator for VertOutputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("v_color"))
})
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for VertOutputIter { }
// This structure describes layout of this stage.
#[derive(Debug, Copy, Clone)]
struct VertLayout(ShaderStages);
unsafe impl PipelineLayoutDesc for VertLayout {
// Number of descriptor sets it takes.
fn num_sets(&self) -> usize { 0 }
// Number of entries (bindings) in each set.
fn num_bindings_in_set(&self, _set: usize) -> Option<usize> { None }
// Descriptor descriptions.
fn descriptor(&self, _set: usize, _binding: usize) -> Option<DescriptorDesc> { None }
// Number of push constants ranges (think: number of push constants).
fn num_push_constants_ranges(&self) -> usize { 0 }
// Each push constant range in memory.
fn push_constants_range(&self, _num: usize) -> Option<PipelineLayoutDescPcRange> { None }
}
// Same as with our vertex shader, but for fragment one instead.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct FragInput;
unsafe impl ShaderInterfaceDef for FragInput {
type Iter = FragInputIter;
fn elements(&self) -> FragInputIter {
FragInputIter(0)
}
}
#[derive(Debug, Copy, Clone)]
struct FragInputIter(u16);
impl Iterator for FragInputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("v_color"))
})
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for FragInputIter { }
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct FragOutput;
unsafe impl ShaderInterfaceDef for FragOutput {
type Iter = FragOutputIter;
fn elements(&self) -> FragOutputIter {
FragOutputIter(0)
}
}
#[derive(Debug, Copy, Clone)]
struct FragOutputIter(u16);
impl Iterator for FragOutputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// Note that color fragment color entry will be determined
// automatically by Vulkano.
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32A32Sfloat,
name: Some(Cow::Borrowed("f_color"))
})
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for FragOutputIter { }
// Layout same as with vertex shader.
#[derive(Debug, Copy, Clone)]
struct FragLayout(ShaderStages);
unsafe impl PipelineLayoutDesc for FragLayout {
fn num_sets(&self) -> usize { 0 }
fn num_bindings_in_set(&self, _set: usize) -> Option<usize> { None }
fn descriptor(&self, _set: usize, _binding: usize) -> Option<DescriptorDesc> { None }
fn num_push_constants_ranges(&self) -> usize { 0 }
fn push_constants_range(&self, _num: usize) -> Option<PipelineLayoutDescPcRange> { None }
}
// NOTE: ShaderModule::*_shader_entry_point calls do not do any error
// checking and you have to verify correctness of what you are doing by
// yourself.
//
// You must be extra careful to specify correct entry point, or program will
// crash at runtime outside of rust and you will get NO meaningful error
// information!
let vert_main = unsafe { vs.graphics_entry_point(
CStr::from_bytes_with_nul_unchecked(b"main\0"),
VertInput,
VertOutput,
VertLayout(ShaderStages { vertex: true, ..ShaderStages::none() }),
GraphicsShaderType::Vertex
) };
let frag_main = unsafe { fs.graphics_entry_point(
CStr::from_bytes_with_nul_unchecked(b"main\0"),
FragInput,
FragOutput,
FragLayout(ShaderStages { fragment: true, ..ShaderStages::none() }),
GraphicsShaderType::Fragment
) };
let graphics_pipeline = Arc::new(
GraphicsPipeline::start()
.vertex_input(SingleBufferDefinition::<Vertex>::new())
.vertex_shader(vert_main, ())
.triangle_list()
.viewports_dynamic_scissors_irrelevant(1)
.fragment_shader(frag_main, ())
.cull_mode_front()
.front_face_counter_clockwise()
.depth_stencil_disabled()
.render_pass(Subpass::from(render_pass.clone(), 0).unwrap())
.build(device.clone())
.unwrap(),
);
let mut recreate_swapchain = false;
let vertex_buffer = CpuAccessibleBuffer::from_iter(
device.clone(),
BufferUsage::all(),
[
Vertex { position: [-1.0, 1.0], color: [1.0, 0.0, 0.0] },
Vertex { position: [ 0.0, -1.0], color: [0.0, 1.0, 0.0] },
Vertex { position: [ 1.0, 1.0], color: [0.0, 0.0, 1.0] },
].iter().cloned()
).unwrap();
// NOTE: We don't create any descriptor sets in this example, but you should
// note that passing wrong types, providing sets at wrong indexes will cause
// descriptor set builder to return Err!
let mut dynamic_state = DynamicState { line_width: None, viewports: None, scissors: None, compare_mask: None, write_mask: None, reference: None };
let mut framebuffers = window_size_dependent_setup(&images, render_pass.clone(), &mut dynamic_state);
let mut previous_frame_end = Some(Box::new(sync::now(device.clone())) as Box<dyn GpuFuture>);
event_loop.run(move |event, _, control_flow| {
match event {
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
*control_flow = ControlFlow::Exit;
},
Event::WindowEvent { event: WindowEvent::Resized(_), .. } => {
recreate_swapchain = true;
},
Event::RedrawEventsCleared => {
previous_frame_end.as_mut().unwrap().cleanup_finished();
if recreate_swapchain {
let dimensions: [u32; 2] = surface.window().inner_size().into();
let (new_swapchain, new_images) = match swapchain.recreate_with_dimension(dimensions) {
Ok(r) => r,
Err(SwapchainCreationError::UnsupportedDimensions) => return,
Err(e) => panic!("Failed to recreate swapchain: {:?}", e)
};
swapchain = new_swapchain;
framebuffers = window_size_dependent_setup(&new_images, render_pass.clone(), &mut dynamic_state);
recreate_swapchain = false;
}
let (image_num, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None) {
Ok(r) => r,
Err(AcquireError::OutOfDate) => {
recreate_swapchain = true;
return;
},
Err(e) => panic!("Failed to acquire next image: {:?}", e)
};
let clear_values = vec!([0.0, 0.0, 0.0, 1.0].into());
let command_buffer = AutoCommandBufferBuilder::new(device.clone(), queue.family()).unwrap()
.begin_render_pass(framebuffers[image_num].clone(), false, clear_values).unwrap()
.draw(graphics_pipeline.clone(), &dynamic_state, vertex_buffer.clone(), (), ()).unwrap()
.end_render_pass().unwrap()
.build().unwrap();
let future = previous_frame_end.take().unwrap()
.join(acquire_future)
.then_execute(queue.clone(), command_buffer).unwrap()
.then_swapchain_present(queue.clone(), swapchain.clone(), image_num)
.then_signal_fence_and_flush();
match future {
Ok(future) => {
previous_frame_end = Some(Box::new(future) as Box<_>);
},
Err(FlushError::OutOfDate) => {
recreate_swapchain = true;
previous_frame_end = Some(Box::new(sync::now(device.clone())) as Box<_>);
}
Err(e) => {
println!("Failed to flush future: {:?}", e);
previous_frame_end = Some(Box::new(sync::now(device.clone())) as Box<_>);
}
}
},
_ => ()
}
});
}
/// This method is called once during initialization, then again whenever the window is resized
fn window_size_dependent_setup(
images: &[Arc<SwapchainImage<Window>>],
render_pass: Arc<dyn RenderPassAbstract + Send + Sync>,
dynamic_state: &mut DynamicState
) -> Vec<Arc<dyn FramebufferAbstract + Send + Sync>> {
let dimensions = images[0].dimensions();
let viewport = Viewport {
origin: [0.0, 0.0],
dimensions: [dimensions[0] as f32, dimensions[1] as f32],
depth_range: 0.0 .. 1.0,
};
dynamic_state.viewports = Some(vec!(viewport));
images.iter().map(|image| {
Arc::new(
Framebuffer::start(render_pass.clone())
.add(image.clone()).unwrap()
.build().unwrap()
) as Arc<dyn FramebufferAbstract + Send + Sync>
}).collect::<Vec<_>>()
}