From ff4302837ebb10965928bae71ca160b099c31211 Mon Sep 17 00:00:00 2001 From: zomseffen Date: Thu, 18 Apr 2024 19:00:01 +0200 Subject: [PATCH] pre vertex transfer buffer --- shaders/shader.vert | 17 ++----- shaders/vert.spv | Bin 1504 -> 1080 bytes src/app_data.rs | 3 ++ src/main.rs | 109 +++++++++++++++++++++++++++++++++++++++++++- src/vertex.rs | 46 +++++++++++++++++++ 5 files changed, 160 insertions(+), 15 deletions(-) create mode 100644 src/vertex.rs diff --git a/shaders/shader.vert b/shaders/shader.vert index ff4b88b..cb40e1e 100644 --- a/shaders/shader.vert +++ b/shaders/shader.vert @@ -1,20 +1,11 @@ #version 450 -vec2 positions[3] = vec2[]( - vec2(0.0, -0.5), - vec2(0.5, 0.5), - vec2(-0.5, 0.5) -); - -vec3 colors[3] = vec3[]( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0) -); +layout(location = 0) in vec2 inPosition; +layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { - gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); - fragColor = colors[gl_VertexIndex]; + gl_Position = vec4(inPosition, 0.0, 1.0); + fragColor = inColor; } \ No newline at end of file diff --git a/shaders/vert.spv b/shaders/vert.spv index a41dd2cd675e3469d59dc6e98d84c97a7d2d2693..1e4ce0c041e7ee15f8cf030b9c3e352942361e75 100644 GIT binary patch literal 1080 zcmYk4Uuzmc6vZd%Mx)Wx7-O5JsUeSr(1)fJN*h8_whw}qKwlTpZ5Y_BvTjP-r+l`2 zs=gF@ezQB`$o1ZP?!Pm4wpux>8?$9vrfp75ak{1=#0cAVIvm}O&R6;T{N2S{GCHQ} z63N*!JI=1@|9)yyoVH|N@=EerQq`{_{iK4LX_{~ph2wEJ`V!5S%V?GVPU0xBX&lXM z7SD3~GbXRGk!RCc@-W{_2$ZooGZ5F7X51ywB+kCaSswqAE409|i7i$(w~JJ0-Q{x! zhubv2wSP33nj!{g#jX>(ys@i%n$F^Nj13TbNRo9d&^@_3C(w@_*mOP8VeI5bHod!E zB#X@D)!dG3S|DGQ#XUG)d#rd9UdtGd!I3=pcnlki{e+5OlNSns(}{$G51&n+_rhmJ zPgT^Nss}x>4`ppj4*H}gv-Rwj>{|hG6#Q8!hzQ_Y39J0eqCuefYT43U4T(f?tz5k{l4=aFR6bao7r%s z|4V6Vz=$80HaPw9*{zTJo%%RFyJr4-y*WJDA%~j3LIUYeLgCz#!1tR_<{p-q)EXO< u7(FLq3fJcna*1(2?sTOd+~-KbPTAXMO~oglneZG+;7E+S;Qtfj50d|?qgO8g literal 1504 zcmYk5ZBNud6oqGZ>4G32BH#;R0mT<^MFnDF)EG3?WD_tXer-10N+zk@OW-Q!$6U%CCwBbK=EWe5;z^DZB6pD_lbols z;A~j*!x>3aHS;kY(h;+8ZeOy&`7ymK{vghmXU$b^!qFcb-s$KIjvgFG49B?z%J}l= z0x|SK?oo}|e?!JvmI~dbYWN26s-mvEFI!W+9#DzNtqAiXd>L!E#+MXRzb-s0PYs+e z%-(zt{$-81PdMuF^D>sh3l;pmr?cT(i!wCuPIE=E)*Gi;5`e=TcU3Vp71u3$SQh4c z=*ctVHF^4QGps0vb2F^gd3a_3^ZuGMTo*Rxm-^|JwKs&|=o@qV%^JI$<8L*zhH;ugQp(6Q*-1WD5ekY5ZsgJ+w=n7uQ6v$J(%~2hWvAR>d7DJE${}JnT6)B z7*GDS5O0dRCFX88w^vfr+kF{*y_K4t9?H(LSvj4QYY=-~< diff --git a/src/app_data.rs b/src/app_data.rs index 15e821b..4dfc417 100644 --- a/src/app_data.rs +++ b/src/app_data.rs @@ -27,4 +27,7 @@ pub struct AppData { pub in_flight_fences: Vec, pub images_in_flight: Vec, + + pub vertex_buffer: vk::Buffer, + pub vertex_buffer_memory: vk::DeviceMemory, } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index cdca99d..29b94f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,10 +27,16 @@ use vulkanalia::vk::ExtDebugUtilsExtension; use vulkanalia::vk::KhrSurfaceExtension; use vulkanalia::vk::KhrSwapchainExtension; +use cgmath::{vec2, vec3}; +use std::mem::size_of; + +use std::ptr::copy_nonoverlapping as memcpy; + pub mod app_data; pub mod errors; pub mod swapchain; pub mod queue_family_indices; +pub mod vertex; const PORTABILITY_MACOS_VERSION: Version = Version::new(1, 3, 216); const VALIDATION_ENABLED: bool = @@ -42,6 +48,12 @@ const DEVICE_EXTENSIONS: &[vk::ExtensionName] = &[vk::KHR_SWAPCHAIN_EXTENSION.na const MAX_FRAMES_IN_FLIGHT: usize = 2; +static VERTICES: [vertex::Vertex; 3] = [ + vertex::Vertex::new(vec2(0.0, -0.5), vec3(1.0, 0.0, 0.0)), + vertex::Vertex::new(vec2(0.5, 0.5), vec3(0.0, 1.0, 0.0)), + vertex::Vertex::new(vec2(-0.5, 0.5), vec3(0.0, 0.0, 1.0)), +]; + fn main() -> Result<()> { pretty_env_logger::init(); @@ -117,6 +129,8 @@ impl App { create_framebuffers(&device, &mut data)?; create_command_pool(&instance, &device, &mut data)?; + + create_vertex_buffer(&instance, &device, &mut data)?; create_command_buffers(&device, &mut data)?; @@ -191,6 +205,9 @@ impl App { unsafe fn destroy(&mut self) { self.destroy_swapchain(); + self.device.destroy_buffer(self.data.vertex_buffer, None); + self.device.free_memory(self.data.vertex_buffer_memory, None); + self.data.in_flight_fences .iter() .for_each(|f| self.device.destroy_fence(*f, None)); @@ -477,7 +494,11 @@ unsafe fn create_pipeline(device: &Device, data: &mut app_data::AppData) -> Resu .module(frag_shader_module) .name(b"main\0"); - let vertex_input_state = vk::PipelineVertexInputStateCreateInfo::builder(); + let binding_descriptions = &[vertex::Vertex::binding_description()]; + let attribute_descriptions = vertex::Vertex::attribute_descriptions(); + let vertex_input_state = vk::PipelineVertexInputStateCreateInfo::builder() + .vertex_binding_descriptions(binding_descriptions) + .vertex_attribute_descriptions(&attribute_descriptions); let input_assembly_state = vk::PipelineInputAssemblyStateCreateInfo::builder() .topology(vk::PrimitiveTopology::TRIANGLE_LIST) @@ -690,7 +711,8 @@ unsafe fn create_command_buffers(device: &Device, data: &mut app_data::AppData) device.cmd_bind_pipeline( *command_buffer, vk::PipelineBindPoint::GRAPHICS, data.pipeline); - device.cmd_draw(*command_buffer, 3, 1, 0, 0); + device.cmd_bind_vertex_buffers(*command_buffer, 0, &[data.vertex_buffer], &[0]); + device.cmd_draw(*command_buffer, VERTICES.len() as u32, 1, 0, 0); device.cmd_end_render_pass(*command_buffer); @@ -720,4 +742,87 @@ unsafe fn create_sync_objects(device: &Device, data: &mut app_data::AppData) -> .collect(); Ok(()) +} + +unsafe fn create_buffer( + instance: &Instance, + device: &Device, + data: &app_data::AppData, + size: vk::DeviceSize, + usage: vk::BufferUsageFlags, + properties: vk::MemoryPropertyFlags, +) -> Result<(vk::Buffer, vk::DeviceMemory)> { + let buffer_info = vk::BufferCreateInfo::builder() + .size(size) + .usage(usage) + .sharing_mode(vk::SharingMode::EXCLUSIVE); + + let buffer = device.create_buffer(&buffer_info, None)?; + + let requirements = device.get_buffer_memory_requirements(buffer); + + let memory_info = vk::MemoryAllocateInfo::builder() + .allocation_size(requirements.size) + .memory_type_index(get_memory_type_index( + instance, + data, + properties, + requirements, + )?); + + let buffer_memory = device.allocate_memory(&memory_info, None)?; + + device.bind_buffer_memory(buffer, buffer_memory, 0)?; + + Ok((buffer, buffer_memory)) +} + +unsafe fn create_vertex_buffer( + instance: &Instance, + device: &Device, + data: &mut app_data::AppData, +) -> Result<()> { + let size = (size_of::() * VERTICES.len()) as u64; + + let (vertex_buffer, vertex_buffer_memory) = create_buffer( + instance, + device, + data, + size, + vk::BufferUsageFlags::VERTEX_BUFFER, + vk::MemoryPropertyFlags::HOST_COHERENT | vk::MemoryPropertyFlags::HOST_VISIBLE, + )?; + + data.vertex_buffer = vertex_buffer; + data.vertex_buffer_memory = vertex_buffer_memory; + + let memory = device.map_memory( + vertex_buffer_memory, + 0, + size, + vk::MemoryMapFlags::empty(), + )?; + + memcpy(VERTICES.as_ptr(), memory.cast(), VERTICES.len()); + + device.unmap_memory(vertex_buffer_memory); + + Ok(()) +} + +unsafe fn get_memory_type_index( + instance: &Instance, + data: &app_data::AppData, + properties: vk::MemoryPropertyFlags, + requirements: vk::MemoryRequirements, +) -> Result { + let memory = instance.get_physical_device_memory_properties(data.physical_device); + + (0..memory.memory_type_count) + .find(|i| { + let suitable = (requirements.memory_type_bits & (1 << i)) != 0; + let memory_type = memory.memory_types[*i as usize]; + suitable && memory_type.property_flags.contains(properties) + }) + .ok_or_else(|| anyhow!("Failed to find suitable memory type.")) } \ No newline at end of file diff --git a/src/vertex.rs b/src/vertex.rs new file mode 100644 index 0000000..bc03ff1 --- /dev/null +++ b/src/vertex.rs @@ -0,0 +1,46 @@ +use vulkanalia::prelude::v1_0::*; + +use std::mem::size_of; + +use cgmath; + +type Vec2 = cgmath::Vector2; +type Vec3 = cgmath::Vector3; + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct Vertex { + pub pos: Vec2, + pub color: Vec3, +} + +impl Vertex { + pub const fn new(pos: Vec2, color: Vec3) -> Self { + Self { pos, color } + } + + pub fn binding_description() -> vk::VertexInputBindingDescription { + vk::VertexInputBindingDescription::builder() + .binding(0) + .stride(size_of::() as u32) + .input_rate(vk::VertexInputRate::VERTEX) + .build() + } + + pub fn attribute_descriptions() -> [vk::VertexInputAttributeDescription; 2] { + let pos = vk::VertexInputAttributeDescription::builder() + .binding(0) + .location(0) + .format(vk::Format::R32G32_SFLOAT) + .offset(0) + .build(); + + let color = vk::VertexInputAttributeDescription::builder() + .binding(0) + .location(1) + .format(vk::Format::R32G32B32_SFLOAT) + .offset(size_of::() as u32) + .build(); + [pos, color] + } +}