mirror of
https://github.com/vulkano-rs/vulkano.git
synced 2024-11-22 06:45:23 +00:00
Add image example
This commit is contained in:
parent
be083d2af8
commit
01d9302d32
@ -47,4 +47,16 @@ fn write_examples() {
|
||||
let content = glsl_to_spirv::compile(include_str!("examples/teapot_fs.glsl"), glsl_to_spirv::ShaderType::Fragment).unwrap();
|
||||
let output = vulkano_shaders::reflect("TeapotShader", content).unwrap();
|
||||
write!(file_output, "{}", output).unwrap();
|
||||
|
||||
let mut file_output = File::create(&dest.join("examples-image_vs.rs")).unwrap();
|
||||
println!("cargo:rerun-if-changed=examples/image_vs.glsl");
|
||||
let content = glsl_to_spirv::compile(include_str!("examples/image_vs.glsl"), glsl_to_spirv::ShaderType::Vertex).unwrap();
|
||||
let output = vulkano_shaders::reflect("ImageShader", content).unwrap();
|
||||
write!(file_output, "{}", output).unwrap();
|
||||
|
||||
let mut file_output = File::create(&dest.join("examples-image_fs.rs")).unwrap();
|
||||
println!("cargo:rerun-if-changed=examples/image_fs.glsl");
|
||||
let content = glsl_to_spirv::compile(include_str!("examples/image_fs.glsl"), glsl_to_spirv::ShaderType::Fragment).unwrap();
|
||||
let output = vulkano_shaders::reflect("ImageShader", content).unwrap();
|
||||
write!(file_output, "{}", output).unwrap();
|
||||
}
|
||||
|
196
vulkano/examples/image.rs
Normal file
196
vulkano/examples/image.rs
Normal file
@ -0,0 +1,196 @@
|
||||
extern crate cgmath;
|
||||
extern crate winit;
|
||||
|
||||
#[cfg(windows)]
|
||||
use winit::os::windows::WindowExt;
|
||||
|
||||
#[macro_use]
|
||||
extern crate vulkano;
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
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.
|
||||
|
||||
// TODO: for the moment the AMD driver crashes if you don't pass an ApplicationInfo, but in theory it's optional
|
||||
let app = vulkano::instance::ApplicationInfo { application_name: "test", application_version: 1, engine_name: "test", engine_version: 1 };
|
||||
let instance = vulkano::instance::Instance::new(Some(&app), &[]).expect("failed to create instance");
|
||||
|
||||
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
|
||||
.next().expect("no device available");
|
||||
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
|
||||
|
||||
let window = winit::WindowBuilder::new().build().unwrap();
|
||||
let surface = unsafe { vulkano::swapchain::Surface::from_hwnd(&instance, ptr::null() as *const () /* FIXME */, window.get_hwnd()).unwrap() };
|
||||
|
||||
let queue = physical.queue_families().find(|q| q.supports_graphics() &&
|
||||
surface.is_supported(q).unwrap_or(false))
|
||||
.expect("couldn't find a graphical queue family");
|
||||
|
||||
let (device, queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
|
||||
[(queue, 0.5)].iter().cloned(), &[])
|
||||
.expect("failed to create device");
|
||||
let queue = queues.into_iter().next().unwrap();
|
||||
|
||||
let (swapchain, images) = {
|
||||
let caps = surface.get_capabilities(&physical).expect("failed to get surface capabilities");
|
||||
|
||||
let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
|
||||
let present = caps.present_modes[0];
|
||||
let usage = caps.supported_usage_flags;
|
||||
|
||||
vulkano::swapchain::Swapchain::new(&device, &surface, 3,
|
||||
vulkano::formats::B8G8R8A8Srgb, dimensions, 1,
|
||||
&usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
|
||||
vulkano::swapchain::CompositeAlpha::Opaque,
|
||||
present, true).expect("failed to create swapchain")
|
||||
};
|
||||
|
||||
|
||||
let cb_pool = vulkano::command_buffer::CommandBufferPool::new(&device, &queue.lock().unwrap().family())
|
||||
.expect("failed to create command buffer pool");
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
let vertex_buffer = vulkano::buffer::Buffer::<[Vertex], _>
|
||||
::array(&device, 4, &vulkano::buffer::Usage::all(),
|
||||
vulkano::memory::HostVisible, &queue)
|
||||
.expect("failed to create buffer");
|
||||
|
||||
struct Vertex { position: [f32; 2] }
|
||||
impl_vertex!(Vertex, position);
|
||||
|
||||
// The buffer that we created contains uninitialized data.
|
||||
// In order to fill it with data, we have to *map* it.
|
||||
{
|
||||
// The `try_write` function would return `None` if the buffer was in use by the GPU. This
|
||||
// obviously can't happen here, since we haven't ask the GPU to do anything yet.
|
||||
let mut mapping = vertex_buffer.try_write().unwrap();
|
||||
mapping[0].position = [-0.5, -0.5];
|
||||
mapping[1].position = [-0.5, 0.5];
|
||||
mapping[2].position = [ 0.5, -0.5];
|
||||
mapping[3].position = [ 0.5, 0.5];
|
||||
}
|
||||
|
||||
|
||||
mod vs { include!{concat!(env!("OUT_DIR"), "/examples-image_vs.rs")} }
|
||||
let vs = vs::ImageShader::load(&device).expect("failed to create shader module");
|
||||
mod fs { include!{concat!(env!("OUT_DIR"), "/examples-image_fs.rs")} }
|
||||
let fs = fs::ImageShader::load(&device).expect("failed to create shader module");
|
||||
|
||||
let renderpass = single_pass_renderpass!{
|
||||
device: &device,
|
||||
attachments: {
|
||||
color [Clear]
|
||||
}
|
||||
}.unwrap();
|
||||
|
||||
|
||||
let texture = vulkano::image::Image::<vulkano::image::Type2d, vulkano::formats::R8G8B8A8Unorm, _>::new(&device, &vulkano::image::Usage::all(),
|
||||
vulkano::memory::DeviceLocal, &queue,
|
||||
images[0].dimensions(), (), 1).unwrap();
|
||||
let texture = texture.transition(vulkano::image::Layout::ShaderReadOnlyOptimal, &cb_pool, &mut queue.lock().unwrap()).unwrap();
|
||||
let texture_view = vulkano::image::ImageView::new(&texture).expect("failed to create image view");
|
||||
|
||||
let sampler = vulkano::sampler::Sampler::new(&device, vulkano::sampler::Filter::Linear,
|
||||
vulkano::sampler::Filter::Linear, vulkano::sampler::MipmapMode::Linear,
|
||||
vulkano::sampler::SamplerAddressMode::Repeat,
|
||||
vulkano::sampler::SamplerAddressMode::Repeat,
|
||||
vulkano::sampler::SamplerAddressMode::Repeat,
|
||||
0.0, 1.0, 0.0, 0.0).unwrap();
|
||||
|
||||
let descriptor_pool = vulkano::descriptor_set::DescriptorPool::new(&device).unwrap();
|
||||
let descriptor_set_layout = {
|
||||
let desc = vulkano::descriptor_set::RuntimeDescriptorSetDesc {
|
||||
descriptors: vec![
|
||||
vulkano::descriptor_set::DescriptorDesc {
|
||||
binding: 0,
|
||||
ty: vulkano::descriptor_set::DescriptorType::CombinedImageSampler,
|
||||
array_count: 1,
|
||||
stages: vulkano::descriptor_set::ShaderStages::all_graphics(),
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
vulkano::descriptor_set::DescriptorSetLayout::new(&device, desc).unwrap()
|
||||
};
|
||||
|
||||
let pipeline_layout = vulkano::descriptor_set::PipelineLayout::new(&device, vulkano::descriptor_set::RuntimeDesc, vec![descriptor_set_layout.clone()]).unwrap();
|
||||
let set = vulkano::descriptor_set::DescriptorSet::new(&descriptor_pool, &descriptor_set_layout,
|
||||
vec![(0, vulkano::descriptor_set::DescriptorBind::CombinedImageSampler(sampler.clone(), texture_view.clone(), vulkano::image::Layout::ShaderReadOnlyOptimal))]).unwrap();
|
||||
|
||||
|
||||
let images = images.into_iter().map(|image| {
|
||||
let image = image.transition(vulkano::image::Layout::PresentSrc, &cb_pool,
|
||||
&mut queue.lock().unwrap()).unwrap();
|
||||
vulkano::image::ImageView::new(&image).expect("failed to create image view")
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
let pipeline = {
|
||||
let ia = vulkano::pipeline::input_assembly::InputAssembly {
|
||||
topology: vulkano::pipeline::input_assembly::PrimitiveTopology::TriangleStrip,
|
||||
primitive_restart_enable: false,
|
||||
};
|
||||
|
||||
let raster = Default::default();
|
||||
let ms = vulkano::pipeline::multisample::Multisample::disabled();
|
||||
let blend = vulkano::pipeline::blend::Blend {
|
||||
logic_op: None,
|
||||
blend_constants: Some([0.0; 4]),
|
||||
};
|
||||
|
||||
let viewports = vulkano::pipeline::viewport::ViewportsState::Fixed {
|
||||
data: vec![(
|
||||
vulkano::pipeline::viewport::Viewport {
|
||||
origin: [0.0, 0.0],
|
||||
dimensions: [1244.0, 699.0],
|
||||
depth_range: 0.0 .. 1.0
|
||||
},
|
||||
vulkano::pipeline::viewport::Scissor {
|
||||
origin: [0, 0],
|
||||
dimensions: [1244, 699],
|
||||
}
|
||||
)],
|
||||
};
|
||||
|
||||
vulkano::pipeline::GraphicsPipeline::new(&device, &vs.main_entry_point(), &ia, &viewports,
|
||||
&raster, &ms, &blend, &fs.main_entry_point(),
|
||||
&pipeline_layout, &renderpass.subpass(0).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let framebuffers = images.iter().map(|image| {
|
||||
vulkano::framebuffer::Framebuffer::new(&renderpass, (1244, 699, 1), image.clone() as std::sync::Arc<_>).unwrap()
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
|
||||
let command_buffers = framebuffers.iter().map(|framebuffer| {
|
||||
vulkano::command_buffer::PrimaryCommandBufferBuilder::new(&cb_pool).unwrap()
|
||||
.clear_color_image(&texture, [0.0, 1.0, 0.0, 1.0])
|
||||
.draw_inline(&renderpass, &framebuffer, [0.0, 0.0, 1.0, 1.0])
|
||||
.draw(&pipeline, vertex_buffer.clone(), &vulkano::command_buffer::DynamicState::none(), set.clone())
|
||||
.draw_end()
|
||||
.build().unwrap()
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
loop {
|
||||
let image_num = swapchain.acquire_next_image(1000000).unwrap();
|
||||
let mut queue = queue.lock().unwrap();
|
||||
command_buffers[image_num].submit(&mut queue).unwrap();
|
||||
swapchain.present(&mut queue, image_num).unwrap();
|
||||
drop(queue);
|
||||
|
||||
for ev in window.poll_events() {
|
||||
match ev {
|
||||
winit::Event::Closed => break,
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
13
vulkano/examples/image_fs.glsl
Normal file
13
vulkano/examples/image_fs.glsl
Normal file
@ -0,0 +1,13 @@
|
||||
#version 450
|
||||
|
||||
#extension GL_ARB_separate_shader_objects : enable
|
||||
#extension GL_ARB_shading_language_420pack : enable
|
||||
|
||||
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);
|
||||
}
|
BIN
vulkano/examples/image_img.png
Normal file
BIN
vulkano/examples/image_img.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.3 KiB |
12
vulkano/examples/image_vs.glsl
Normal file
12
vulkano/examples/image_vs.glsl
Normal file
@ -0,0 +1,12 @@
|
||||
#version 450
|
||||
|
||||
#extension GL_ARB_separate_shader_objects : enable
|
||||
#extension GL_ARB_shading_language_420pack : enable
|
||||
|
||||
layout(location = 0) in vec2 position;
|
||||
out vec2 tex_coords;
|
||||
|
||||
void main() {
|
||||
gl_Position = vec4(position, 0.0, 1.0);
|
||||
tex_coords = (position + vec2(0.5)) * 2.0;
|
||||
}
|
@ -10,11 +10,14 @@ use command_buffer::DynamicState;
|
||||
use descriptor_set::PipelineLayoutDesc;
|
||||
use descriptor_set::DescriptorSetsCollection;
|
||||
use device::Queue;
|
||||
use formats::FloatOrCompressedFormatMarker;
|
||||
use framebuffer::ClearValue;
|
||||
use framebuffer::Framebuffer;
|
||||
use framebuffer::RenderPass;
|
||||
use framebuffer::RenderPassLayout;
|
||||
use image::AbstractImageView;
|
||||
use image::Image;
|
||||
use image::ImageTypeMarker;
|
||||
use memory::MemorySourceChunk;
|
||||
use pipeline::GenericPipeline;
|
||||
use pipeline::GraphicsPipeline;
|
||||
@ -264,6 +267,31 @@ impl InnerCommandBufferBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
pub unsafe fn clear_color_image<'a, Ty, F, M>(self, image: &Arc<Image<Ty, F, M>>,
|
||||
color: [f32; 4] /* FIXME: */)
|
||||
-> InnerCommandBufferBuilder
|
||||
where Ty: ImageTypeMarker, F: FloatOrCompressedFormatMarker
|
||||
{
|
||||
{
|
||||
let vk = self.device.pointers();
|
||||
|
||||
let color = vk::ClearColorValue::float32(color);
|
||||
|
||||
let range = vk::ImageSubresourceRange {
|
||||
aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
|
||||
baseMipLevel: 0, // FIXME:
|
||||
levelCount: 1, // FIXME:
|
||||
baseArrayLayer: 0, // FIXME:
|
||||
layerCount: 1, // FIXME:
|
||||
};
|
||||
|
||||
vk.CmdClearColorImage(self.cmd.unwrap(), image.internal_object(), vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL /* FIXME: */,
|
||||
&color, 1, &range);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/*pub unsafe fn copy_buffer_to_image<'a, S, Sm>(mut self, source: S, )
|
||||
where S: Into<BufferSlice<'a, [], Sm>
|
||||
{
|
||||
@ -313,7 +341,7 @@ impl InnerCommandBufferBuilder {
|
||||
let ids = buffers.map(|b| b.internal_object()).collect::<Vec<_>>();
|
||||
vk.CmdBindVertexBuffers(self.cmd.unwrap(), 0, ids.len() as u32, ids.as_ptr(),
|
||||
offsets.as_ptr());
|
||||
vk.CmdDraw(self.cmd.unwrap(), 3, 1, 0, 0); // FIXME: params
|
||||
vk.CmdDraw(self.cmd.unwrap(), 4, 1, 0, 0); // FIXME: params
|
||||
}
|
||||
|
||||
self
|
||||
|
@ -8,9 +8,12 @@ use command_buffer::inner::InnerCommandBuffer;
|
||||
use descriptor_set::PipelineLayoutDesc;
|
||||
use descriptor_set::DescriptorSetsCollection;
|
||||
use device::Queue;
|
||||
use formats::FloatOrCompressedFormatMarker;
|
||||
use framebuffer::Framebuffer;
|
||||
use framebuffer::RenderPass;
|
||||
use framebuffer::RenderPassLayout;
|
||||
use image::Image;
|
||||
use image::ImageTypeMarker;
|
||||
use memory::MemorySourceChunk;
|
||||
use pipeline::GraphicsPipeline;
|
||||
use pipeline::input_assembly::Index;
|
||||
@ -107,6 +110,18 @@ impl PrimaryCommandBufferBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_color_image<'a, Ty, F, M>(self, image: &Arc<Image<Ty, F, M>>,
|
||||
color: [f32; 4] /* FIXME: */)
|
||||
-> PrimaryCommandBufferBuilder
|
||||
where Ty: ImageTypeMarker, F: FloatOrCompressedFormatMarker
|
||||
{
|
||||
unsafe {
|
||||
PrimaryCommandBufferBuilder {
|
||||
inner: self.inner.clear_color_image(image, color),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes secondary compute command buffers within this primary command buffer.
|
||||
#[inline]
|
||||
pub fn execute_commands<'a, I>(self, iter: I) -> PrimaryCommandBufferBuilder
|
||||
|
@ -115,13 +115,19 @@ macro_rules! formats {
|
||||
)+
|
||||
);
|
||||
|
||||
(__inner_impl__ $name:ident float) => { unsafe impl FloatFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident float) => {
|
||||
unsafe impl FloatFormatMarker for $name {}
|
||||
unsafe impl FloatOrCompressedFormatMarker for $name {}
|
||||
};
|
||||
(__inner_impl__ $name:ident uint) => { unsafe impl UintFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident sint) => { unsafe impl SintFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident depth) => { unsafe impl DepthFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident stencil) => { unsafe impl StencilFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident depthstencil) => { unsafe impl DepthStencilFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident compressed) => { unsafe impl CompressedFormatMarker for $name {} };
|
||||
(__inner_impl__ $name:ident compressed) => {
|
||||
unsafe impl CompressedFormatMarker for $name {}
|
||||
unsafe impl FloatOrCompressedFormatMarker for $name {}
|
||||
};
|
||||
|
||||
(__inner_ty__ $name:ident float) => { FormatTy::Float };
|
||||
(__inner_ty__ $name:ident uint) => { FormatTy::Uint };
|
||||
@ -331,6 +337,7 @@ pub unsafe trait DepthFormatMarker: FormatMarker {}
|
||||
pub unsafe trait StencilFormatMarker: FormatMarker {}
|
||||
pub unsafe trait DepthStencilFormatMarker: FormatMarker {}
|
||||
pub unsafe trait CompressedFormatMarker: FormatMarker {}
|
||||
pub unsafe trait FloatOrCompressedFormatMarker {}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum FormatTy {
|
||||
|
@ -297,7 +297,7 @@ macro_rules! single_pass_renderpass {
|
||||
|
||||
struct Layout;
|
||||
unsafe impl $crate::framebuffer::RenderPassLayout for Layout {
|
||||
type ClearValues = ([f32; 4], f32); // FIXME:
|
||||
type ClearValues = [f32; 4]; // FIXME:
|
||||
type ClearValuesIter = std::vec::IntoIter<$crate::framebuffer::ClearValue>;
|
||||
type AttachmentsDescIter = std::vec::IntoIter<$crate::framebuffer::AttachmentDescription>;
|
||||
type PassesIter = std::option::IntoIter<$crate::framebuffer::PassDescription>;
|
||||
@ -306,15 +306,14 @@ macro_rules! single_pass_renderpass {
|
||||
|
||||
// FIXME: should be stronger-typed
|
||||
type AttachmentsList = (
|
||||
Arc<$crate::image::AbstractImageView>,
|
||||
Arc<$crate::image::AbstractImageView>
|
||||
); // FIXME:
|
||||
|
||||
#[inline]
|
||||
fn convert_clear_values(&self, val: Self::ClearValues) -> Self::ClearValuesIter {
|
||||
vec![
|
||||
$crate::framebuffer::ClearValue::Float(val.0),
|
||||
$crate::framebuffer::ClearValue::Depth(val.1)
|
||||
$crate::framebuffer::ClearValue::Float(val)
|
||||
//$crate::framebuffer::ClearValue::Depth(val.1)
|
||||
].into_iter()
|
||||
}
|
||||
|
||||
@ -332,14 +331,14 @@ macro_rules! single_pass_renderpass {
|
||||
},
|
||||
)*
|
||||
|
||||
$crate::framebuffer::AttachmentDescription {
|
||||
/*$crate::framebuffer::AttachmentDescription {
|
||||
format: $crate::formats::Format::D16Unorm, // FIXME:
|
||||
samples: 1, // FIXME:
|
||||
load: $crate::framebuffer::LoadOp::Clear, // FIXME:
|
||||
store: $crate::framebuffer::StoreOp::Store, // FIXME:
|
||||
initial_layout: $crate::image::Layout::DepthStencilAttachmentOptimal, // FIXME:
|
||||
final_layout: $crate::image::Layout::DepthStencilAttachmentOptimal, // FIXME:
|
||||
},
|
||||
},*/
|
||||
].into_iter()
|
||||
}
|
||||
|
||||
@ -348,7 +347,7 @@ macro_rules! single_pass_renderpass {
|
||||
Some(
|
||||
$crate::framebuffer::PassDescription {
|
||||
color_attachments: vec![(0, $crate::image::Layout::ColorAttachmentOptimal)],
|
||||
depth_stencil: Some((1, $crate::image::Layout::DepthStencilAttachmentOptimal)),
|
||||
depth_stencil: None,//Some((1, $crate::image::Layout::DepthStencilAttachmentOptimal)),
|
||||
input_attachments: vec![],
|
||||
resolve_attachments: vec![],
|
||||
preserve_attachments: vec![],
|
||||
@ -363,7 +362,7 @@ macro_rules! single_pass_renderpass {
|
||||
|
||||
#[inline]
|
||||
fn convert_attachments_list(&self, l: Self::AttachmentsList) -> Self::AttachmentsIter {
|
||||
vec![l.0.clone(), l.1.clone()].into_iter()
|
||||
vec![l.clone()/*, l.1.clone()*/].into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user