vulkano/examples/src/bin/image/main.rs

275 lines
10 KiB
Rust
Raw Normal View History

2016-03-26 09:17:37 +00:00
// Copyright (c) 2016 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.
2016-02-24 09:47:58 +00:00
extern crate cgmath;
2016-02-24 14:00:06 +00:00
extern crate image;
2016-02-24 09:47:58 +00:00
extern crate winit;
#[macro_use]
extern crate vulkano;
extern crate vulkano_shaders;
2016-04-23 11:32:31 +00:00
extern crate vulkano_win;
use vulkano_win::VkSurfaceBuild;
2017-04-04 07:00:11 +00:00
use vulkano::sync::GpuFuture;
use vulkano_shaders::vulkano_shader;
2016-02-24 09:47:58 +00:00
2017-04-04 07:00:11 +00:00
use std::sync::Arc;
2016-02-24 09:47:58 +00:00
fn main() {
// The start of this example is exactly the same as `triangle`. You should read the
// `triangle` example if you haven't done so yet.
2016-05-04 05:10:00 +00:00
let extensions = vulkano_win::required_extensions();
2018-08-11 06:48:03 +00:00
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
2016-02-24 09:47:58 +00:00
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
.next().expect("no device available");
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
2017-07-04 11:53:32 +00:00
let mut events_loop = winit::EventsLoop::new();
let surface = winit::WindowBuilder::new().build_vk_surface(&events_loop, instance.clone()).unwrap();
2016-02-24 09:47:58 +00:00
let mut dimensions;
let queue_family = physical.queue_families().find(|&q| q.supports_graphics() &&
surface.is_supported(q).unwrap_or(false))
2016-02-24 09:47:58 +00:00
.expect("couldn't find a graphical queue family");
2016-03-12 08:08:06 +00:00
let device_ext = vulkano::device::DeviceExtensions {
khr_swapchain: true,
2016-03-30 11:44:13 +00:00
.. vulkano::device::DeviceExtensions::none()
2016-03-12 08:08:06 +00:00
};
2017-07-02 03:52:18 +00:00
let (device, mut queues) = vulkano::device::Device::new(physical, physical.supported_features(),
&device_ext, [(queue_family, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
2016-02-24 09:47:58 +00:00
let (mut swapchain, mut images) = {
let caps = surface.capabilities(physical).expect("failed to get surface capabilities");
2016-02-24 09:47:58 +00:00
dimensions = caps.current_extent.unwrap_or([1024, 768]);
2016-02-24 09:47:58 +00:00
let usage = caps.supported_usage_flags;
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
let format = caps.supported_formats[0].0;
2016-02-24 09:47:58 +00:00
vulkano::swapchain::Swapchain::new(device.clone(), surface.clone(), caps.min_image_count,
format, dimensions, 1,
2017-05-20 12:06:19 +00:00
usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
alpha,
2017-06-11 17:01:00 +00:00
vulkano::swapchain::PresentMode::Fifo, true, None).expect("failed to create swapchain")
2016-02-24 09:47:58 +00:00
};
#[derive(Debug, Clone)]
2016-02-24 09:47:58 +00:00
struct Vertex { position: [f32; 2] }
impl_vertex!(Vertex, position);
let vertex_buffer = vulkano::buffer::cpu_access::CpuAccessibleBuffer::<[Vertex]>
::from_iter(device.clone(), vulkano::buffer::BufferUsage::all(),
[
Vertex { position: [-0.5, -0.5 ] },
Vertex { position: [-0.5, 0.5 ] },
Vertex { position: [ 0.5, -0.5 ] },
Vertex { position: [ 0.5, 0.5 ] },
].iter().cloned()).expect("failed to create buffer");
2016-02-24 09:47:58 +00:00
let vs = vs::Shader::load(device.clone()).expect("failed to create shader module");
let fs = fs::Shader::load(device.clone()).expect("failed to create shader module");
2016-02-24 09:47:58 +00:00
2017-04-04 07:00:11 +00:00
let renderpass = Arc::new(
single_pass_renderpass!(device.clone(),
attachments: {
color: {
load: Clear,
store: Store,
2017-05-26 11:12:21 +00:00
format: swapchain.format(),
2017-04-04 07:00:11 +00:00
samples: 1,
}
},
pass: {
color: [color],
depth_stencil: {}
}
2017-04-04 07:00:11 +00:00
).unwrap()
);
2016-02-24 09:47:58 +00:00
let (texture, tex_future) = {
2016-02-24 14:00:06 +00:00
let image = image::load_from_memory_with_format(include_bytes!("image_img.png"),
image::ImageFormat::PNG).unwrap().to_rgba();
let image_data = image.into_raw().clone();
vulkano::image::immutable::ImmutableImage::from_iter(
image_data.iter().cloned(),
vulkano::image::Dimensions::Dim2d { width: 93, height: 93 },
vulkano::format::R8G8B8A8Srgb,
queue.clone()).unwrap()
2016-02-24 14:00:06 +00:00
};
let sampler = vulkano::sampler::Sampler::new(device.clone(), vulkano::sampler::Filter::Linear,
2016-02-24 14:00:06 +00:00
vulkano::sampler::Filter::Linear, vulkano::sampler::MipmapMode::Nearest,
2016-02-24 09:47:58 +00:00
vulkano::sampler::SamplerAddressMode::Repeat,
vulkano::sampler::SamplerAddressMode::Repeat,
vulkano::sampler::SamplerAddressMode::Repeat,
0.0, 1.0, 0.0, 0.0).unwrap();
2017-06-10 16:55:05 +00:00
let pipeline = Arc::new(vulkano::pipeline::GraphicsPipeline::start()
.vertex_input_single_buffer::<Vertex>()
.vertex_shader(vs.main_entry_point(), ())
2017-06-10 16:55:05 +00:00
.triangle_strip()
.viewports_dynamic_scissors_irrelevant(1)
.fragment_shader(fs.main_entry_point(), ())
.blend_alpha_blending()
2017-06-10 16:55:05 +00:00
.render_pass(vulkano::framebuffer::Subpass::from(renderpass.clone(), 0).unwrap())
.build(device.clone())
.unwrap());
2017-04-04 07:00:11 +00:00
let set = Arc::new(vulkano::descriptor::descriptor_set::PersistentDescriptorSet::start(pipeline.clone(), 0)
.add_sampled_image(texture.clone(), sampler.clone()).unwrap()
.build().unwrap()
);
2016-02-24 09:47:58 +00:00
let mut framebuffers: Option<Vec<Arc<vulkano::framebuffer::Framebuffer<_,_>>>> = None;
let mut recreate_swapchain = false;
2016-02-24 09:47:58 +00:00
let mut previous_frame_end = Box::new(tex_future) as Box<GpuFuture>;
2016-02-24 09:47:58 +00:00
let mut dynamic_state = vulkano::command_buffer::DynamicState {
line_width: None,
viewports: Some(vec![vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
dimensions: [dimensions[0] as f32, dimensions[1] as f32],
depth_range: 0.0 .. 1.0,
}]),
scissors: None,
};
2016-02-24 09:47:58 +00:00
loop {
previous_frame_end.cleanup_finished();
if recreate_swapchain {
dimensions = surface.capabilities(physical)
.expect("failed to get surface capabilities")
.current_extent.unwrap_or([1024, 768]);
2018-08-11 06:48:03 +00:00
let (new_swapchain, new_images) = match swapchain.recreate_with_dimension(dimensions) {
Ok(r) => r,
Err(vulkano::swapchain::SwapchainCreationError::UnsupportedDimensions) => {
continue;
},
Err(err) => panic!("{:?}", err)
};
swapchain = new_swapchain;
images = new_images;
framebuffers = None;
dynamic_state.viewports = Some(vec![vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
dimensions: [dimensions[0] as f32, dimensions[1] as f32],
depth_range: 0.0 .. 1.0,
}]);
recreate_swapchain = false;
}
if framebuffers.is_none() {
framebuffers = Some(images.iter().map(|image| {
Arc::new(vulkano::framebuffer::Framebuffer::start(renderpass.clone())
.add(image.clone()).unwrap()
.build().unwrap())
}).collect::<Vec<_>>());
}
let (image_num, future) = match vulkano::swapchain::acquire_next_image(swapchain.clone(),
None) {
Ok(r) => r,
Err(vulkano::swapchain::AcquireError::OutOfDate) => {
recreate_swapchain = true;
continue;
},
Err(err) => panic!("{:?}", err)
};
2017-04-04 07:00:11 +00:00
2017-07-11 09:33:35 +00:00
let cb = vulkano::command_buffer::AutoCommandBufferBuilder::primary_one_time_submit(device.clone(), queue.family())
2017-04-04 07:00:11 +00:00
.unwrap()
.begin_render_pass(
framebuffers.as_ref().unwrap()[image_num].clone(), false,
vec![[0.0, 0.0, 1.0, 1.0].into()]).unwrap()
.draw(pipeline.clone(),
&dynamic_state,
vertex_buffer.clone(),
set.clone(), ()).unwrap()
.end_render_pass().unwrap()
.build().unwrap();
2017-04-04 07:00:11 +00:00
let future = previous_frame_end.join(future)
2017-05-15 09:02:00 +00:00
.then_execute(queue.clone(), cb).unwrap()
2017-04-04 07:00:11 +00:00
.then_swapchain_present(queue.clone(), swapchain.clone(), image_num)
.then_signal_fence_and_flush();
match future {
Ok(future) => {
previous_frame_end = Box::new(future) as Box<_>;
}
Err(vulkano::sync::FlushError::OutOfDate) => {
recreate_swapchain = true;
previous_frame_end = Box::new(vulkano::sync::now(device.clone())) as Box<_>;
}
Err(e) => {
println!("{:?}", e);
previous_frame_end = Box::new(vulkano::sync::now(device.clone())) as Box<_>;
}
}
2016-02-24 09:47:58 +00:00
let mut done = false;
events_loop.poll_events(|ev| {
2016-02-24 09:47:58 +00:00
match ev {
2018-06-05 10:58:59 +00:00
winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => done = true,
2016-02-24 09:47:58 +00:00
_ => ()
}
});
if done { return; }
2016-02-24 09:47:58 +00:00
}
}
vulkano_shader!{
mod_name: vs,
ty: "vertex",
src: "
#version 450
layout(location = 0) in vec2 position;
layout(location = 0) out vec2 tex_coords;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
tex_coords = position + vec2(0.5);
}"
}
vulkano_shader!{
mod_name: fs,
ty: "fragment",
src: "
#version 450
layout(location = 0) in vec2 tex_coords;
layout(location = 0) out vec4 f_color;
layout(set = 0, binding = 0) uniform sampler2D tex;
void main() {
f_color = texture(tex, tex_coords);
}"
}