Browse Source

cargo fmt, but this time we actually did it

master
Alison Watson 2 months ago
parent
commit
c0923b5d43
33 changed files with 473 additions and 511 deletions
  1. +1
    -1
      rustfmt.toml
  2. +3
    -3
      source/conf.rs
  3. +2
    -1
      source/hal/err.rs
  4. +1
    -1
      source/hal/event.rs
  5. +7
    -7
      source/hal/window.rs
  6. +79
    -84
      source/main.rs
  7. +2
    -5
      source/render.rs
  8. +33
    -35
      source/render/buffer.rs
  9. +69
    -85
      source/render/cmd.rs
  10. +5
    -5
      source/render/conf.rs
  11. +1
    -1
      source/render/descriptorlayout.rs
  12. +32
    -40
      source/render/descriptorpool.rs
  13. +17
    -17
      source/render/device.rs
  14. +1
    -1
      source/render/fence.rs
  15. +12
    -12
      source/render/framebuffer.rs
  16. +5
    -5
      source/render/image.rs
  17. +8
    -8
      source/render/imageview.rs
  18. +12
    -12
      source/render/instance.rs
  19. +56
    -55
      source/render/pipeline.rs
  20. +2
    -2
      source/render/pipelinelayout.rs
  21. +1
    -1
      source/render/properties.rs
  22. +11
    -8
      source/render/queue.rs
  23. +35
    -44
      source/render/renderpass.rs
  24. +1
    -1
      source/render/semaphore.rs
  25. +2
    -2
      source/render/shader.rs
  26. +1
    -1
      source/render/surface.rs
  27. +32
    -30
      source/render/swapchain.rs
  28. +9
    -10
      source/render/uniforms.rs
  29. +12
    -13
      source/render/vertex.rs
  30. +7
    -7
      source/util/log.rs
  31. +1
    -1
      source/util/log/color.rs
  32. +10
    -10
      source/util/log/level.rs
  33. +3
    -3
      source/util/log/standard.rs

+ 1
- 1
rustfmt.toml View File

@@ -1,5 +1,5 @@
hard_tabs = true
max_width = 80
max_width = 79
newline_style = "Unix"
tab_spaces = 3
use_field_init_shorthand = true


+ 3
- 3
source/conf.rs View File

@@ -17,8 +17,8 @@ pub enum ErrConfLoad {
impl std::fmt::Display for ErrConfLoad {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoFile => write!(f, "No existing conf file"),
Self::File(e) => write!(f, "Couldn't open conf file: {}", e),
Self::NoFile => write!(f, "No existing conf file"),
Self::File(e) => write!(f, "Couldn't open conf file: {}", e),
Self::Parse(e) => write!(f, "Couldn't parse conf file: {}", e),
}
}
@@ -28,7 +28,7 @@ impl From<std::io::Error> for ErrConfLoad {
fn from(err: std::io::Error) -> Self {
match err.kind() {
std::io::ErrorKind::NotFound => Self::NoFile,
_ => Self::File(err),
_ => Self::File(err),
}
}
}


+ 2
- 1
source/hal/err.rs View File

@@ -15,7 +15,8 @@ impl std::fmt::Display for ErrSdl {

impl ErrSdl {
pub unsafe fn new() -> Self {
let contents = std::ffi::CStr::from_ptr(SDL_GetError()).to_string_lossy();
let contents =
std::ffi::CStr::from_ptr(SDL_GetError()).to_string_lossy();
Self { contents }
}
}


+ 1
- 1
source/hal/event.rs View File

@@ -24,7 +24,7 @@ fn read_in(evt: SDL_Event) -> Option<Event> {
let typ = unsafe { std::mem::transmute(evt.type_) };
match typ {
SDL_EventType::SDL_QUIT => Some(Event::Quit),
_ => None,
_ => None,
}
}



+ 7
- 7
source/hal/window.rs View File

@@ -14,16 +14,16 @@ use std::{
};

pub struct Window<'a> {
hal: PhantomData<&'a Context>,
hal: PhantomData<&'a Context>,
handle: *mut SDL_Window,
}

impl<'a> Window<'a> {
pub fn new(
_hal: &'a Context,
_hal: &'a Context,
title: *const c_char,
w: i16,
h: i16,
w: i16,
h: i16,
) -> Result<Self, ErrSdl> {
let handle = unsafe {
SDL_CreateWindow(
@@ -32,9 +32,9 @@ impl<'a> Window<'a> {
SDL_WINDOWPOS_UNDEFINED_MASK as c_int,
w.into(),
h.into(),
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32 |
SDL_WindowFlags::SDL_WINDOW_VULKAN as u32 |
SDL_WindowFlags::SDL_WINDOW_RESIZABLE as u32,
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32
| SDL_WindowFlags::SDL_WINDOW_VULKAN as u32
| SDL_WindowFlags::SDL_WINDOW_RESIZABLE as u32,
)
};
if !handle.is_null() {


+ 79
- 84
source/main.rs View File

@@ -12,7 +12,7 @@ use crate::{
};

use ash::{version::DeviceV1_0, vk};
use cgmath::{prelude::*, Matrix4, Point3, Rad, Vector2, Vector3};
use cgmath::{prelude::*, Matrix4, Point3, Rad, Vector2, Vector3, Vector4};
use std::rc::Rc;

struct Pipelines {
@@ -20,10 +20,10 @@ struct Pipelines {
}

struct SwapchainData<'a> {
swapchain: Rc<Swapchain>,
image_f: Vec<Option<&'a Fence>>,
swapchain: Rc<Swapchain>,
image_f: Vec<Option<&'a Fence>>,
descriptor_pool: Rc<DescriptorPool>,
cmd_pool: Rc<CommandPool>,
cmd_pool: Rc<CommandPool>,
}

impl Pipelines {
@@ -35,17 +35,17 @@ impl Pipelines {

impl SwapchainData<'_> {
pub fn create(
device: Rc<Device>,
phys_device: &PhysicalDevice,
surface: Rc<Surface>,
shader_vert: Rc<ShaderModule>,
shader_frag: Rc<ShaderModule>,
layout: Rc<PipelineLayout>,
vertex_buffer: Rc<Buffer>,
index_buffer: Rc<Buffer>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
surface: Rc<Surface>,
shader_vert: Rc<ShaderModule>,
shader_frag: Rc<ShaderModule>,
layout: Rc<PipelineLayout>,
vertex_buffer: Rc<Buffer>,
index_buffer: Rc<Buffer>,
queue_graphics: &Queue,
queue_surface: &Queue,
conf: &render::Conf,
queue_surface: &Queue,
conf: &render::Conf,
) -> Result<Self, ErrAllocMem> {
let swapchain = Swapchain::create(
device.clone(),
@@ -67,15 +67,13 @@ impl SwapchainData<'_> {

let pipelines = Pipeline::create_all(
device.clone(),
&[
PipelineCreateInfo::info_basic(
shader_vert,
shader_frag,
layout.clone(),
render_pass.clone(),
swapchain.extent,
),
],
&[PipelineCreateInfo::info_basic(
shader_vert,
shader_frag,
layout.clone(),
render_pass.clone(),
swapchain.extent,
)],
)?;

let pipelines = Pipelines::create_from(pipelines);
@@ -87,11 +85,10 @@ impl SwapchainData<'_> {
swapchain.extent,
)?;

let uniform_buffers =
framebuffers
.iter()
.map(|_| Buffer::create_uniform(device.clone(), phys_device))
.collect::<Result<_, _>>()?;
let uniform_buffers = framebuffers
.iter()
.map(|_| Buffer::create_uniform(device.clone(), phys_device))
.collect::<Result<_, _>>()?;

let descriptor_pool = DescriptorPool::create(
device.clone(),
@@ -123,14 +120,14 @@ impl SwapchainData<'_> {
}

fn draw_frame<'a>(
sc_data: &mut SwapchainData<'a>,
device: &Device,
image_avail_s: &Semaphore,
render_fini_s: &Semaphore,
frame_f: &'a Fence,
sc_data: &mut SwapchainData<'a>,
device: &Device,
image_avail_s: &Semaphore,
render_fini_s: &Semaphore,
frame_f: &'a Fence,
queue_graphics: &Queue,
queue_surface: &Queue,
time_ms: u128,
queue_surface: &Queue,
time_ms: u128,
) -> Result<(), vk::Result> {
let cmd_buffers = sc_data.cmd_pool.buf_handles();

@@ -164,66 +161,61 @@ fn draw_frame<'a>(
let object =
Matrix4::from_angle_z(Rad::full_turn() * time_ms as f32 / 10_000.0);

let camera =
Matrix4::look_at(
Point3::new(2.0, 2.0, 2.0),
Point3::new(0.0, 0.0, 0.0),
Vector3::new(0.0, 0.0, 1.0),
);

let projection =
cgmath::perspective(
Rad::turn_div_4(),
sc_data.swapchain.extent.width as f32 /
sc_data.swapchain.extent.height as f32,
0.01,
100_000.0,
) *
Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, -1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
);
let camera = Matrix4::look_at(
Point3::new(2.0, 2.0, 2.0),
Point3::new(0.0, 0.0, 0.0),
Vector3::new(0.0, 0.0, 1.0),
);

let projection = cgmath::perspective(
Rad::turn_div_4(),
sc_data.swapchain.extent.width as f32
/ sc_data.swapchain.extent.height as f32,
0.01,
100_000.0,
) * Matrix4::from_cols(
Vector4::new(1.0, 0.0, 0.0, 0.0),
Vector4::new(0.0, -1.0, 0.0, 0.0),
Vector4::new(0.0, 0.0, 1.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
);

let uniforms = Uniforms { object, camera, projection };

sc_data.descriptor_pool.buffers[image_index].write_data(&[uniforms])?;

let wait_semaphores = [**image_avail_s];
let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];
let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];

let signal_semaphores = [**render_fini_s];

let submit_cmd_buffers = &cmd_buffers[image_index..=image_index];

let submit_info = [
vk::SubmitInfo {
wait_semaphore_count: wait_semaphores.len() as u32,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
command_buffer_count: submit_cmd_buffers.len() as u32,
p_command_buffers: submit_cmd_buffers.as_ptr(),
signal_semaphore_count: signal_semaphores.len() as u32,
p_signal_semaphores: signal_semaphores.as_ptr(),
..Default::default()
}
];
let submit_info = [vk::SubmitInfo {
wait_semaphore_count: wait_semaphores.len() as u32,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
command_buffer_count: submit_cmd_buffers.len() as u32,
p_command_buffers: submit_cmd_buffers.as_ptr(),
signal_semaphore_count: signal_semaphores.len() as u32,
p_signal_semaphores: signal_semaphores.as_ptr(),
..Default::default()
}];

unsafe {
device.reset_fences(&fences)?;
device.queue_submit(**queue_graphics, &submit_info, **frame_f)?;
}

let swapchains = [**sc_data.swapchain];
let swapchains = [**sc_data.swapchain];
let image_indices = [image_index as u32];

let present_info = vk::PresentInfoKHR {
wait_semaphore_count: signal_semaphores.len() as u32,
p_wait_semaphores: signal_semaphores.as_ptr(),
swapchain_count: swapchains.len() as u32,
p_swapchains: swapchains.as_ptr(),
p_image_indices: image_indices.as_ptr(),
p_wait_semaphores: signal_semaphores.as_ptr(),
swapchain_count: swapchains.len() as u32,
p_swapchains: swapchains.as_ptr(),
p_image_indices: image_indices.as_ptr(),
..Default::default()
};

@@ -244,7 +236,7 @@ fn seize_device(lg: &log::Log, device: &Device) {

fn fallback_main(
conf: &conf::Conf,
lg: &log::Log,
lg: &log::Log,
) -> Result<(), Box<dyn std::error::Error>> {
let start_time = std::time::Instant::now();

@@ -271,10 +263,10 @@ fn fallback_main(

let concur_frames = conf.render.concurrent_frames.into();

let hal = hal::Context::new()?;
let hal = hal::Context::new()?;
let window = hal::Window::new(&hal, meta::ffi::name(), 640, 480)?;

let entry = ash::Entry::new()?;
let entry = ash::Entry::new()?;
let instance = Instance::create(&conf.render, entry, &window)?;

let phys_device = PhysicalDevice::get(instance.clone(), &conf.render)?;
@@ -286,7 +278,7 @@ fn fallback_main(
let device = Device::create(instance, &phys_device, &qf_info)?;

let queue_graphics = Queue::get(device.clone(), qf_info.gfx_index);
let queue_surface = Queue::get(device.clone(), qf_info.srf_index);
let queue_surface = Queue::get(device.clone(), qf_info.srf_index);

let vertex_buffer = Buffer::create_vertex(
device.clone(),
@@ -308,7 +300,7 @@ fn fallback_main(
let frame_f = Fence::create_all(device.clone(), concur_frames)?;

let desc_layout = DescriptorSetLayout::create(device.clone())?;
let layout = PipelineLayout::create(desc_layout)?;
let layout = PipelineLayout::create(desc_layout)?;

let spir_vert = Spir::read(MAIN_VERT);
let spir_frag = Spir::read(MAIN_FRAG);
@@ -392,7 +384,7 @@ fn main() {
let conf = conf::Conf::read("blonkus.yaml").unwrap_or_else(|err| {
let level = match err {
conf::ErrConfLoad::NoFile => log::Level::Notice,
_ => log::Level::Error,
_ => log::Level::Error,
};
lg!(&lg, level, "{}", err);
lg!(&lg, log::Level::Notice, "Using default configuration.");
@@ -405,10 +397,13 @@ fn main() {
}

const VERTICES: &[Vertex] = &[
Vertex { pos: Vector2::new(-0.5, -0.5), color: Vector3::new(1.0, 0.0, 0.0) },
Vertex { pos: Vector2::new( 0.5, -0.5), color: Vector3::new(0.0, 1.0, 0.0) },
Vertex { pos: Vector2::new( 0.5, 0.5), color: Vector3::new(0.0, 0.0, 1.0) },
Vertex { pos: Vector2::new(-0.5, 0.5), color: Vector3::new(1.0, 1.0, 1.0) },
Vertex {
pos: Vector2::new(-0.5, -0.5),
color: Vector3::new(1.0, 0.0, 0.0),
},
Vertex { pos: Vector2::new(0.5, -0.5), color: Vector3::new(0.0, 1.0, 0.0) },
Vertex { pos: Vector2::new(0.5, 0.5), color: Vector3::new(0.0, 0.0, 1.0) },
Vertex { pos: Vector2::new(-0.5, 0.5), color: Vector3::new(1.0, 1.0, 1.0) },
];

const INDICES: &[u16] = &[0, 1, 2, 2, 3, 0];


+ 2
- 5
source/render.rs View File

@@ -31,10 +31,7 @@ pub use self::{
descriptorlayout::DescriptorSetLayout,
descriptorpool::{DescriptorPool, DescriptorSet},
device::{
Device,
ErrAllocMem,
ErrDeviceCreate,
ErrPhysicalDeviceGet,
Device, ErrAllocMem, ErrDeviceCreate, ErrPhysicalDeviceGet,
PhysicalDevice,
},
fence::Fence,
@@ -52,8 +49,8 @@ pub use self::{
spir::Spir,
surface::Surface,
swapchain::Swapchain,
vertex::Vertex,
uniforms::Uniforms,
vertex::Vertex,
};

// EOF

+ 33
- 35
source/render/buffer.rs View File

@@ -16,10 +16,10 @@ pub struct Buffer {
}

unsafe fn create_buffer(
device: &Device,
phys_device: &PhysicalDevice,
size: vk::DeviceSize,
usage: vk::BufferUsageFlags,
device: &Device,
phys_device: &PhysicalDevice,
size: vk::DeviceSize,
usage: vk::BufferUsageFlags,
memory_flags: vk::MemoryPropertyFlags,
) -> Result<(vk::Buffer, vk::DeviceMemory), ErrAllocMem> {
let create_info = vk::BufferCreateInfo {
@@ -50,10 +50,10 @@ fn dev_size_of<T>(data: &[T]) -> vk::DeviceSize {
impl Buffer {
/// Creates a vertex buffer.
pub fn create_vertex(
device: Rc<Device>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
vertices: &[Vertex],
queue: &Queue,
vertices: &[Vertex],
queue: &Queue,
) -> Result<Rc<Self>, ErrAllocMem> {
let size = dev_size_of(vertices);

@@ -62,8 +62,8 @@ impl Buffer {
&device,
phys_device,
size,
vk::BufferUsageFlags::TRANSFER_DST |
vk::BufferUsageFlags::VERTEX_BUFFER,
vk::BufferUsageFlags::TRANSFER_DST
| vk::BufferUsageFlags::VERTEX_BUFFER,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
)?;

@@ -77,10 +77,10 @@ impl Buffer {

/// Creates an index buffer.
pub fn create_index(
device: Rc<Device>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
indices: &[u16],
queue: &Queue,
indices: &[u16],
queue: &Queue,
) -> Result<Rc<Self>, ErrAllocMem> {
let size = dev_size_of(indices);

@@ -89,8 +89,8 @@ impl Buffer {
&device,
phys_device,
size,
vk::BufferUsageFlags::TRANSFER_DST |
vk::BufferUsageFlags::INDEX_BUFFER,
vk::BufferUsageFlags::TRANSFER_DST
| vk::BufferUsageFlags::INDEX_BUFFER,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
)?;

@@ -104,9 +104,9 @@ impl Buffer {

/// Creates an image buffer.
pub fn create_image(
device: Rc<Device>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
image: &[Color],
image: &[Color],
) -> Result<Rc<Self>, ErrAllocMem> {
let size = dev_size_of(image);

@@ -116,8 +116,8 @@ impl Buffer {
phys_device,
size,
vk::BufferUsageFlags::TRANSFER_SRC,
vk::MemoryPropertyFlags::HOST_VISIBLE |
vk::MemoryPropertyFlags::HOST_COHERENT,
vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT,
)?;

let src = Self { handle, memory, device };
@@ -130,7 +130,7 @@ impl Buffer {

/// Creates a uniform buffer.
pub fn create_uniform(
device: Rc<Device>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
) -> Result<Rc<Self>, ErrAllocMem> {
let (handle, memory) = unsafe {
@@ -139,8 +139,8 @@ impl Buffer {
phys_device,
std::mem::size_of::<Uniforms>() as vk::DeviceSize,
vk::BufferUsageFlags::UNIFORM_BUFFER,
vk::MemoryPropertyFlags::HOST_VISIBLE |
vk::MemoryPropertyFlags::HOST_COHERENT,
vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT,
)?
};

@@ -150,9 +150,9 @@ impl Buffer {
/// Copies the contents of `src` to `self` using a transient pool.
unsafe fn copy_buffer(
&self,
src: &Self,
size: vk::DeviceSize,
queue: &Queue,
src: &Self,
size: vk::DeviceSize,
queue: &Queue,
) -> Result<(), vk::Result> {
let pool = CommandPool::create_transfer(
self.device.clone(),
@@ -162,13 +162,11 @@ impl Buffer {

let submit_buffers = pool.buf_handles();

let submit_info = [
vk::SubmitInfo {
command_buffer_count: submit_buffers.len() as u32,
p_command_buffers: submit_buffers.as_ptr(),
..Default::default()
}
];
let submit_info = [vk::SubmitInfo {
command_buffer_count: submit_buffers.len() as u32,
p_command_buffers: submit_buffers.as_ptr(),
..Default::default()
}];

self.device.queue_submit(**queue, &submit_info, vk::Fence::null())?;

@@ -178,9 +176,9 @@ impl Buffer {
/// Transfers `data` from the client to the server.
pub fn xfer_data<T>(
&self,
queue: &Queue,
queue: &Queue,
phys_device: &PhysicalDevice,
data: &[T],
data: &[T],
) -> Result<(), ErrAllocMem> {
let size = dev_size_of(data);

@@ -190,8 +188,8 @@ impl Buffer {
phys_device,
size,
vk::BufferUsageFlags::TRANSFER_SRC,
vk::MemoryPropertyFlags::HOST_VISIBLE |
vk::MemoryPropertyFlags::HOST_COHERENT,
vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT,
)?;

let src = Self { handle, memory, device: self.device.clone() };


+ 69
- 85
source/render/cmd.rs View File

@@ -10,7 +10,7 @@ pub struct CommandPool {
handle: vk::CommandPool,

buf_handles: Vec<vk::CommandBuffer>,
buffers: Vec<CommandBuffer>,
buffers: Vec<CommandBuffer>,

pub device: Rc<Device>,
}
@@ -19,23 +19,23 @@ pub struct CommandPool {
pub struct CommandBuffer {
handle: vk::CommandBuffer,

device: Rc<Device>,
render_pass: Option<Rc<RenderPass>>,
framebuffer: Option<Rc<Framebuffer>>,
pipeline: Option<Rc<Pipeline>>,
vertex_buffer: Option<Rc<Buffer>>,
index_buffer: Option<Rc<Buffer>>,
device: Rc<Device>,
render_pass: Option<Rc<RenderPass>>,
framebuffer: Option<Rc<Framebuffer>>,
pipeline: Option<Rc<Pipeline>>,
vertex_buffer: Option<Rc<Buffer>>,
index_buffer: Option<Rc<Buffer>>,
descriptor_pool: Option<Rc<DescriptorPool>>,
}

impl CommandPool {
pub fn create_graphics(
device: Rc<Device>,
index: u32,
device: Rc<Device>,
index: u32,
framebuffers: &[Rc<Framebuffer>],
render_pass: Rc<RenderPass>,
extent: vk::Extent2D,
f: impl Fn(&mut CommandBuffer, usize) + Copy,
render_pass: Rc<RenderPass>,
extent: vk::Extent2D,
f: impl Fn(&mut CommandBuffer, usize) + Copy,
) -> Result<Rc<Self>, vk::Result> {
let (handle, buffers) = unsafe {
Self::create_inner(
@@ -46,22 +46,21 @@ impl CommandPool {
)?
};

let buffers =
buffers
.iter()
.zip(framebuffers.iter())
.enumerate()
.map(|(framebuffer_num, (&handle, framebuffer))| {
Ok(CommandBuffer::create_graphics(
handle,
device.clone(),
render_pass.clone(),
framebuffer.clone(),
extent,
|cmd| f(cmd, framebuffer_num),
)?)
})
.collect::<Result<Vec<_>, vk::Result>>()?;
let buffers = buffers
.iter()
.zip(framebuffers.iter())
.enumerate()
.map(|(framebuffer_num, (&handle, framebuffer))| {
Ok(CommandBuffer::create_graphics(
handle,
device.clone(),
render_pass.clone(),
framebuffer.clone(),
extent,
|cmd| f(cmd, framebuffer_num),
)?)
})
.collect::<Result<Vec<_>, vk::Result>>()?;

let buf_handles = buffers.iter().map(|cmd_buf| **cmd_buf).collect();

@@ -70,8 +69,8 @@ impl CommandPool {

pub fn create_transfer(
device: Rc<Device>,
index: u32,
f: impl Fn(&mut CommandBuffer) + Copy,
index: u32,
f: impl Fn(&mut CommandBuffer) + Copy,
) -> Result<Rc<Self>, vk::Result> {
let (handle, buffers) = unsafe {
Self::create_inner(
@@ -82,17 +81,12 @@ impl CommandPool {
)?
};

let buffers =
buffers
.iter()
.map(|&handle| {
Ok(CommandBuffer::create_transfer(
handle,
device.clone(),
f,
)?)
})
.collect::<Result<Vec<_>, vk::Result>>()?;
let buffers = buffers
.iter()
.map(|&handle| {
Ok(CommandBuffer::create_transfer(handle, device.clone(), f)?)
})
.collect::<Result<Vec<_>, vk::Result>>()?;

let buf_handles = buffers.iter().map(|cmd_buf| **cmd_buf).collect();

@@ -109,9 +103,9 @@ impl CommandPool {
}

unsafe fn create_inner(
device: &Device,
index: u32,
flags: vk::CommandPoolCreateFlags,
device: &Device,
index: u32,
flags: vk::CommandPoolCreateFlags,
buf_num: usize,
) -> Result<(vk::CommandPool, Vec<vk::CommandBuffer>), vk::Result> {
let create_info = vk::CommandPoolCreateInfo {
@@ -123,8 +117,8 @@ impl CommandPool {
let handle = device.create_command_pool(&create_info, None)?;

let alloc_info = vk::CommandBufferAllocateInfo {
command_pool: handle,
level: vk::CommandBufferLevel::PRIMARY,
command_pool: handle,
level: vk::CommandBufferLevel::PRIMARY,
command_buffer_count: buf_num as u32,
..Default::default()
};
@@ -153,8 +147,8 @@ impl CommandBuffer {
self.device.cmd_bind_vertex_buffers(
self.handle,
0,
&[ **buffer ],
&[ 0 ],
&[**buffer],
&[0],
);

self.vertex_buffer = Some(buffer);
@@ -175,7 +169,7 @@ impl CommandBuffer {
&mut self,
descriptor_pool: Rc<DescriptorPool>,
pipeline_layout: Rc<PipelineLayout>,
which: usize,
which: usize,
) {
unsafe {
self.device.cmd_bind_descriptor_sets(
@@ -199,16 +193,11 @@ impl CommandBuffer {

pub fn transfer(
&mut self,
src: vk::Buffer,
dst: vk::Buffer,
size: vk::DeviceSize
src: vk::Buffer,
dst: vk::Buffer,
size: vk::DeviceSize,
) {
let copy = [
vk::BufferCopy {
size,
..Default::default()
}
];
let copy = [vk::BufferCopy { size, ..Default::default() }];

unsafe {
self.device.cmd_copy_buffer(self.handle, src, dst, &copy);
@@ -238,41 +227,36 @@ impl CommandBuffer {
}

fn create_graphics(
handle: vk::CommandBuffer,
device: Rc<Device>,
handle: vk::CommandBuffer,
device: Rc<Device>,
render_pass: Rc<RenderPass>,
framebuffer: Rc<Framebuffer>,
extent: vk::Extent2D,
f: impl Fn(&mut Self),
extent: vk::Extent2D,
f: impl Fn(&mut Self),
) -> Result<Self, vk::Result> {
let cmd_begin_info = vk::CommandBufferBeginInfo::default();

let clear_values = [
vk::ClearValue {
color: vk::ClearColorValue { float32: [0.086, 0.098, 0.149, 1.0] }
}
];
let clear_values = [vk::ClearValue {
color: vk::ClearColorValue { float32: [0.086, 0.098, 0.149, 1.0] },
}];

let ren_begin_info = vk::RenderPassBeginInfo {
render_pass: **render_pass,
framebuffer: **framebuffer,
render_area: vk::Rect2D {
extent,
offset: vk::Offset2D::default(),
},
render_area: vk::Rect2D { extent, offset: vk::Offset2D::default() },
clear_value_count: clear_values.len() as u32,
p_clear_values: clear_values.as_ptr(),
p_clear_values: clear_values.as_ptr(),
..Default::default()
};

let mut this = Self {
handle,
device,
render_pass: Some(render_pass),
framebuffer: Some(framebuffer),
pipeline: None,
vertex_buffer: None,
index_buffer: None,
render_pass: Some(render_pass),
framebuffer: Some(framebuffer),
pipeline: None,
vertex_buffer: None,
index_buffer: None,
descriptor_pool: None,
};

@@ -296,9 +280,9 @@ impl CommandBuffer {
}

fn create_transfer(
handle: vk::CommandBuffer,
device: Rc<Device>,
f: impl Fn(&mut Self),
handle: vk::CommandBuffer,
device: Rc<Device>,
f: impl Fn(&mut Self),
) -> Result<Self, vk::Result> {
let cmd_begin_info = vk::CommandBufferBeginInfo {
flags: vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT,
@@ -308,11 +292,11 @@ impl CommandBuffer {
let mut this = Self {
handle,
device,
render_pass: None,
framebuffer: None,
pipeline: None,
vertex_buffer: None,
index_buffer: None,
render_pass: None,
framebuffer: None,
pipeline: None,
vertex_buffer: None,
index_buffer: None,
descriptor_pool: None,
};



+ 5
- 5
source/render/conf.rs View File

@@ -25,9 +25,9 @@ serialize! {
impl From<PresentMode> for vk::PresentModeKHR {
fn from(mode: PresentMode) -> Self {
match mode {
PresentMode::Immediate => Self::IMMEDIATE,
PresentMode::Mailbox => Self::MAILBOX,
PresentMode::Fifo => Self::FIFO,
PresentMode::Immediate => Self::IMMEDIATE,
PresentMode::Mailbox => Self::MAILBOX,
PresentMode::Fifo => Self::FIFO,
PresentMode::FifoRelaxed => Self::FIFO_RELAXED,
}
}
@@ -36,9 +36,9 @@ impl From<PresentMode> for vk::PresentModeKHR {
impl Default for Conf {
fn default() -> Self {
Self {
device: 0,
device: 0,
validation_layers: cfg!(debug_assertions),
swap_mode: PresentMode::Mailbox,
swap_mode: PresentMode::Mailbox,
concurrent_frames: NonZeroUsize::new(2).unwrap(),
}
}


+ 1
- 1
source/render/descriptorlayout.rs View File

@@ -12,7 +12,7 @@ impl DescriptorSetLayout {
pub fn create(device: Rc<Device>) -> Result<Rc<Self>, vk::Result> {
let create_info = vk::DescriptorSetLayoutCreateInfo {
binding_count: Uniforms::BIND_DESC.len() as u32,
p_bindings: Uniforms::BIND_DESC.as_ptr(),
p_bindings: Uniforms::BIND_DESC.as_ptr(),
..Default::default()
};
let handle =


+ 32
- 40
source/render/descriptorpool.rs View File

@@ -9,28 +9,26 @@ pub struct DescriptorSet {
pub struct DescriptorPool {
handle: vk::DescriptorPool,

pub device: Rc<Device>,
pub device: Rc<Device>,
pub buffers: Vec<Rc<Buffer>>,
pub sets: Vec<DescriptorSet>,
pub sets: Vec<DescriptorSet>,
}

impl DescriptorPool {
pub fn create(
device: Rc<Device>,
device: Rc<Device>,
buffers: Vec<Rc<Buffer>>,
layout: Rc<DescriptorSetLayout>,
layout: Rc<DescriptorSetLayout>,
) -> Result<Rc<Self>, vk::Result> {
let size_info = [
vk::DescriptorPoolSize {
ty: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: buffers.len() as u32,
}
];
let size_info = [vk::DescriptorPoolSize {
ty: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: buffers.len() as u32,
}];

let create_info = vk::DescriptorPoolCreateInfo {
pool_size_count: size_info.len() as u32,
p_pool_sizes: size_info.as_ptr(),
max_sets: buffers.len() as u32,
p_pool_sizes: size_info.as_ptr(),
max_sets: buffers.len() as u32,
..Default::default()
};

@@ -40,9 +38,9 @@ impl DescriptorPool {
let set_layouts = vec![**layout; buffers.len()];

let alloc_info = vk::DescriptorSetAllocateInfo {
descriptor_pool: handle,
descriptor_pool: handle,
descriptor_set_count: set_layouts.len() as u32,
p_set_layouts: set_layouts.as_ptr(),
p_set_layouts: set_layouts.as_ptr(),
..Default::default()
};

@@ -54,32 +52,26 @@ impl DescriptorPool {
.collect::<Vec<_>>()
};

let buffer_infos =
buffers
.iter()
.map(|buffer| {
vk::DescriptorBufferInfo {
buffer: ***buffer,
range: std::mem::size_of::<Uniforms>() as vk::DeviceSize,
..Default::default()
}
})
.collect::<Vec<_>>();

let write_descriptors =
sets
.iter()
.zip(&buffer_infos)
.map(|(dst_set, buffer_info)| {
vk::WriteDescriptorSet {
dst_set: **dst_set,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: 1,
p_buffer_info: &*buffer_info,
..Default::default()
}
})
.collect::<Vec<_>>();
let buffer_infos = buffers
.iter()
.map(|buffer| vk::DescriptorBufferInfo {
buffer: ***buffer,
range: std::mem::size_of::<Uniforms>() as vk::DeviceSize,
..Default::default()
})
.collect::<Vec<_>>();

let write_descriptors = sets
.iter()
.zip(&buffer_infos)
.map(|(dst_set, buffer_info)| vk::WriteDescriptorSet {
dst_set: **dst_set,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: 1,
p_buffer_info: &*buffer_info,
..Default::default()
})
.collect::<Vec<_>>();

unsafe {
device.update_descriptor_sets(&write_descriptors, &[]);


+ 17
- 17
source/render/device.rs View File

@@ -11,7 +11,7 @@ use std::{os::raw::c_char, rc::Rc};
pub struct Device {
handle: ash::Device,

pub instance: Rc<Instance>,
pub instance: Rc<Instance>,
pub swapchain_ext: khr::Swapchain,
}

@@ -40,9 +40,9 @@ pub enum ErrAllocMem {
}

fn enable_device_extensions(
instance: &ash::Instance,
instance: &ash::Instance,
phys_device: &PhysicalDevice,
extensions: &[*const c_char],
extensions: &[*const c_char],
) -> Result<vk::DeviceCreateInfo, ErrDeviceCreate> {
if !extensions.is_empty() {
let props = unsafe {
@@ -53,7 +53,7 @@ fn enable_device_extensions(
}

Ok(vk::DeviceCreateInfo {
enabled_extension_count: extensions.len() as u32,
enabled_extension_count: extensions.len() as u32,
pp_enabled_extension_names: extensions.as_ptr(),
..Default::default()
})
@@ -65,7 +65,7 @@ fn get_memory_type(
filter_types: u32,
) -> Result<u32, ErrAllocMem> {
let count = memory_props.memory_type_count as usize;
let iter = memory_props.memory_types.iter().take(count).enumerate();
let iter = memory_props.memory_types.iter().take(count).enumerate();

for (i, memory_type) in iter {
let has_flags = memory_type.property_flags.contains(filter_flags);
@@ -81,22 +81,22 @@ fn get_memory_type(

impl Device {
pub fn create(
instance: Rc<Instance>,
instance: Rc<Instance>,
phys_device: &PhysicalDevice,
qf_info: &QueueFamilyInfo,
qf_info: &QueueFamilyInfo,
) -> Result<Rc<Self>, ErrDeviceCreate> {
const QUEUE_PRIORITY: [f32; 1] = [1.0];

let queue_create_info = [
vk::DeviceQueueCreateInfo {
queue_family_index: qf_info.gfx_index,
queue_count: 1,
queue_count: 1,
p_queue_priorities: QUEUE_PRIORITY.as_ptr(),
..Default::default()
},
vk::DeviceQueueCreateInfo {
queue_family_index: qf_info.srf_index,
queue_count: 1,
queue_count: 1,
p_queue_priorities: QUEUE_PRIORITY.as_ptr(),
..Default::default()
},
@@ -108,8 +108,8 @@ impl Device {

let create_info = vk::DeviceCreateInfo {
queue_create_info_count: queue_create_info.len() as u32,
p_queue_create_infos: queue_create_info.as_ptr(),
p_enabled_features: &device_features,
p_queue_create_infos: queue_create_info.as_ptr(),
p_enabled_features: &device_features,
..enable_device_extensions(&instance, phys_device, &extensions)?
};

@@ -123,8 +123,8 @@ impl Device {

pub fn alloc_mem(
&self,
phys_device: &PhysicalDevice,
memory_reqs: vk::MemoryRequirements,
phys_device: &PhysicalDevice,
memory_reqs: vk::MemoryRequirements,
memory_flags: vk::MemoryPropertyFlags,
) -> Result<vk::DeviceMemory, ErrAllocMem> {
unsafe {
@@ -134,7 +134,7 @@ impl Device {
let memory_type_index = get_memory_type(
memory_props,
memory_flags,
memory_reqs.memory_type_bits
memory_reqs.memory_type_bits,
)?;

let allocate_info = vk::MemoryAllocateInfo {
@@ -151,7 +151,7 @@ impl Device {
impl PhysicalDevice {
pub fn get(
instance: Rc<Instance>,
conf: &Conf,
conf: &Conf,
) -> Result<Rc<Self>, ErrPhysicalDeviceGet> {
let devs = unsafe { instance.enumerate_physical_devices()? };

@@ -189,7 +189,7 @@ impl std::ops::Deref for PhysicalDevice {
impl std::fmt::Display for ErrDeviceCreate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Vk(res) => res.fmt(f),
Self::Vk(res) => res.fmt(f),
Self::NoExtension(err) => write!(f, "Missing extension: {}", err),
}
}
@@ -198,7 +198,7 @@ impl std::fmt::Display for ErrDeviceCreate {
impl std::fmt::Display for ErrPhysicalDeviceGet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Vk(res) => res.fmt(f),
Self::Vk(res) => res.fmt(f),
Self::NoDevice => f.write_str("No suitable devices available"),
}
}


+ 1
- 1
source/render/fence.rs View File

@@ -20,7 +20,7 @@ impl Fence {

pub fn create_all(
device: Rc<Device>,
num: usize,
num: usize,
) -> Result<Vec<Rc<Self>>, vk::Result> {
(0..num).map(|_| Self::create(device.clone())).collect()
}


+ 12
- 12
source/render/framebuffer.rs View File

@@ -5,27 +5,27 @@ use std::rc::Rc;
pub struct Framebuffer {
handle: vk::Framebuffer,

pub device: Rc<Device>,
pub device: Rc<Device>,
pub render_pass: Rc<RenderPass>,
pub image_view: Rc<ImageView>,
pub image_view: Rc<ImageView>,
}

impl Framebuffer {
pub fn create(
device: Rc<Device>,
render_pass: Rc<RenderPass>,
image_view: Rc<ImageView>,
device: Rc<Device>,
render_pass: Rc<RenderPass>,
image_view: Rc<ImageView>,
image_extent: vk::Extent2D,
) -> Result<Rc<Self>, vk::Result> {
let attachments = [**image_view];

let create_info = vk::FramebufferCreateInfo {
render_pass: **render_pass,
render_pass: **render_pass,
attachment_count: attachments.len() as u32,
p_attachments: attachments.as_ptr(),
width: image_extent.width,
height: image_extent.height,
layers: 1,
p_attachments: attachments.as_ptr(),
width: image_extent.width,
height: image_extent.height,
layers: 1,
..Default::default()
};

@@ -34,10 +34,10 @@ impl Framebuffer {
}

pub fn create_all(
device: Rc<Device>,
device: Rc<Device>,
render_pass: Rc<RenderPass>,
image_views: &[Rc<ImageView>],
extent: vk::Extent2D,
extent: vk::Extent2D,
) -> Result<Vec<Rc<Self>>, vk::Result> {
image_views
.iter()


+ 5
- 5
source/render/image.rs View File

@@ -24,10 +24,10 @@ impl OwnedImage {

impl Image {
pub fn new(
device: Rc<Device>,
device: Rc<Device>,
phys_device: &PhysicalDevice,
width: usize,
height: usize,
width: usize,
height: usize,
) -> Result<Rc<Self>, ErrAllocMem> {
let layout = vk::ImageLayout::UNDEFINED;

@@ -43,8 +43,8 @@ impl Image {
array_layers: 1,
samples: vk::SampleCountFlags::TYPE_1,
tiling: vk::ImageTiling::OPTIMAL,
usage:
vk::ImageUsageFlags::TRANSFER_DST | vk::ImageUsageFlags::SAMPLED,
usage: vk::ImageUsageFlags::TRANSFER_DST
| vk::ImageUsageFlags::SAMPLED,
sharing_mode: vk::SharingMode::EXCLUSIVE,
initial_layout: layout,
..Default::default()


+ 8
- 8
source/render/imageview.rs View File

@@ -6,19 +6,19 @@ pub struct ImageView {
handle: vk::ImageView,

pub device: Rc<Device>,
pub image: Rc<OwnedImage>,
pub image: Rc<OwnedImage>,
}

impl ImageView {
pub fn create(
device: Rc<Device>,
image: Rc<OwnedImage>,
image: Rc<OwnedImage>,
format: vk::Format,
) -> Result<Rc<Self>, vk::Result> {
let create_info = vk::ImageViewCreateInfo {
format,
image: **image,
view_type: vk::ImageViewType::TYPE_2D,
image: **image,
view_type: vk::ImageViewType::TYPE_2D,
components: vk::ComponentMapping {
r: vk::ComponentSwizzle::IDENTITY,
g: vk::ComponentSwizzle::IDENTITY,
@@ -26,11 +26,11 @@ impl ImageView {
a: vk::ComponentSwizzle::IDENTITY,
},
subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
layer_count: 1,
},
..Default::default()
};


+ 12
- 12
source/render/instance.rs View File

@@ -12,7 +12,7 @@ use std::{os::raw::c_char, rc::Rc};

pub struct Instance {
#[allow(dead_code)]
entry: ash::Entry,
entry: ash::Entry,
handle: ash::Instance,

pub surface_ext: khr::Surface,
@@ -28,7 +28,7 @@ pub enum ErrInstanceCreate {

fn enable_instance_layers(
layers: &[*const c_char],
entry: &ash::Entry,
entry: &ash::Entry,
) -> Result<vk::InstanceCreateInfo, ErrInstanceCreate> {
if !layers.is_empty() {
let props = entry.enumerate_instance_layer_properties()?;
@@ -36,7 +36,7 @@ fn enable_instance_layers(
}

Ok(vk::InstanceCreateInfo {
enabled_layer_count: layers.len() as u32,
enabled_layer_count: layers.len() as u32,
pp_enabled_layer_names: layers.as_ptr(),
..Default::default()
})
@@ -44,15 +44,15 @@ fn enable_instance_layers(

impl Instance {
pub fn create(
conf: &Conf,
entry: ash::Entry,
conf: &Conf,
entry: ash::Entry,
window: &crate::hal::Window,
) -> Result<Rc<Self>, ErrInstanceCreate> {
let exts = window.vulkan_instance_extensions()?;

let app_info = vk::ApplicationInfo {
p_engine_name: meta::ffi::name(),
api_version: vk::make_version(1, 0, 0),
api_version: vk::make_version(1, 0, 0),
..Default::default()
};

@@ -63,13 +63,13 @@ impl Instance {
}

let create_info = vk::InstanceCreateInfo {
p_application_info: &app_info,
enabled_extension_count: exts.len() as u32,
p_application_info: &app_info,
enabled_extension_count: exts.len() as u32,
pp_enabled_extension_names: exts.as_ptr(),
..enable_instance_layers(&layers, &entry)?
};

let handle = unsafe { entry.create_instance(&create_info, None)? };
let handle = unsafe { entry.create_instance(&create_info, None)? };
let surface_ext = khr::Surface::new(&entry, &handle);
Ok(Rc::new(Self { entry, handle, surface_ext }))
}
@@ -93,10 +93,10 @@ impl std::ops::Deref for Instance {
impl std::fmt::Display for ErrInstanceCreate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Vk(res) => res.fmt(f),
Self::Instance(err) => err.fmt(f),
Self::Vk(res) => res.fmt(f),
Self::Instance(err) => err.fmt(f),
Self::NoExtension(err) => write!(f, "Missing extension: {}", err),
Self::Sdl(err) => err.fmt(f),
Self::Sdl(err) => err.fmt(f),
}
}
}


+ 56
- 55
source/render/pipeline.rs View File

@@ -1,27 +1,29 @@
use crate::render::{Device, PipelineLayout, RenderPass, ShaderModule, Vertex};
use crate::render::{
Device, PipelineLayout, RenderPass, ShaderModule, Vertex,
};
use ash::{version::DeviceV1_0, vk};
use std::rc::Rc;

pub struct PipelineCreateInfo {
shader_data: Vec<Rc<ShaderModule>>,
layout: Rc<PipelineLayout>,
render_pass: Rc<RenderPass>,
shader_stages: Vec<vk::PipelineShaderStageCreateInfo>,
vertex_input_state: vk::PipelineVertexInputStateCreateInfo,
input_assembly_state: vk::PipelineInputAssemblyStateCreateInfo,
viewports: Vec<vk::Viewport>,
scissors: Vec<vk::Rect2D>,
rasterization_state: vk::PipelineRasterizationStateCreateInfo,
multisample_state: vk::PipelineMultisampleStateCreateInfo,
shader_data: Vec<Rc<ShaderModule>>,
layout: Rc<PipelineLayout>,
render_pass: Rc<RenderPass>,
shader_stages: Vec<vk::PipelineShaderStageCreateInfo>,
vertex_input_state: vk::PipelineVertexInputStateCreateInfo,
input_assembly_state: vk::PipelineInputAssemblyStateCreateInfo,
viewports: Vec<vk::Viewport>,
scissors: Vec<vk::Rect2D>,
rasterization_state: vk::PipelineRasterizationStateCreateInfo,
multisample_state: vk::PipelineMultisampleStateCreateInfo,
color_blend_attachments: Vec<vk::PipelineColorBlendAttachmentState>,
}

pub struct Pipeline {
handle: vk::Pipeline,

pub device: Rc<Device>,
pub device: Rc<Device>,
pub shader_data: Vec<Rc<ShaderModule>>,
pub layout: Rc<PipelineLayout>,
pub layout: Rc<PipelineLayout>,
pub render_pass: Rc<RenderPass>,
}

@@ -29,9 +31,9 @@ impl PipelineCreateInfo {
pub fn info_basic(
shader_vert: Rc<ShaderModule>,
shader_frag: Rc<ShaderModule>,
layout: Rc<PipelineLayout>,
layout: Rc<PipelineLayout>,
render_pass: Rc<RenderPass>,
extent: vk::Extent2D,
extent: vk::Extent2D,
) -> Self {
Self {
layout,
@@ -39,61 +41,60 @@ impl PipelineCreateInfo {
shader_data: vec![shader_vert.clone(), shader_frag.clone()],
shader_stages: vec![
vk::PipelineShaderStageCreateInfo {
stage: vk::ShaderStageFlags::VERTEX,
stage: vk::ShaderStageFlags::VERTEX,
module: **shader_vert,
p_name: c_str!("main"),
..Default::default()
},
vk::PipelineShaderStageCreateInfo {
stage: vk::ShaderStageFlags::FRAGMENT,
stage: vk::ShaderStageFlags::FRAGMENT,
module: **shader_frag,
p_name: c_str!("main"),
..Default::default()
},
],
vertex_input_state: vk::PipelineVertexInputStateCreateInfo {
vertex_binding_description_count: Vertex::BIND_DESC.len() as u32,
p_vertex_binding_descriptions: Vertex::BIND_DESC.as_ptr(),
vertex_binding_description_count: Vertex::BIND_DESC.len() as u32,
p_vertex_binding_descriptions: Vertex::BIND_DESC.as_ptr(),
vertex_attribute_description_count: Vertex::ATTR_DESC.len() as u32,
p_vertex_attribute_descriptions: Vertex::ATTR_DESC.as_ptr(),
p_vertex_attribute_descriptions: Vertex::ATTR_DESC.as_ptr(),
..Default::default()
},
input_assembly_state: vk::PipelineInputAssemblyStateCreateInfo {
topology: vk::PrimitiveTopology::TRIANGLE_LIST,
topology: vk::PrimitiveTopology::TRIANGLE_LIST,
primitive_restart_enable: vk::FALSE,
..Default::default()
},
viewports: vec![
vk::Viewport {
x: 0.0,
y: 0.0,
width: extent.width as f32,
height: extent.height as f32,
min_depth: 0.0,
max_depth: 1.0,
}
],
scissors: vec![
vk::Rect2D { extent, offset: vk::Offset2D::default() }
],
viewports: vec![vk::Viewport {
x: 0.0,
y: 0.0,
width: extent.width as f32,
height: extent.height as f32,
min_depth: 0.0,
max_depth: 1.0,
}],
scissors: vec![vk::Rect2D {
extent,
offset: vk::Offset2D::default(),
}],
rasterization_state: vk::PipelineRasterizationStateCreateInfo {
polygon_mode: vk::PolygonMode::FILL,
line_width: 1.0,
cull_mode: vk::CullModeFlags::BACK,
front_face: vk::FrontFace::COUNTER_CLOCKWISE,
line_width: 1.0,
cull_mode: vk::CullModeFlags::BACK,
front_face: vk::FrontFace::COUNTER_CLOCKWISE,
..Default::default()
},
multisample_state: vk::PipelineMultisampleStateCreateInfo {
sample_shading_enable: vk::FALSE,
rasterization_samples: vk::SampleCountFlags::TYPE_1,
min_sample_shading: 1.0,
min_sample_shading: 1.0,
..Default::default()
},
color_blend_attachments: vec![
vk::PipelineColorBlendAttachmentState {
color_write_mask: vk::ColorComponentFlags::all(),
..Default::default()
}
},
],
}
}
@@ -102,15 +103,15 @@ impl PipelineCreateInfo {
impl Pipeline {
pub fn create_all(
device: Rc<Device>,
infos: &[PipelineCreateInfo],
infos: &[PipelineCreateInfo],
) -> Result<Vec<Rc<Self>>, vk::Result> {
let viewport_states = infos
.iter()
.map(|info| vk::PipelineViewportStateCreateInfo {
viewport_count: info.viewports.len() as u32,
p_viewports: info.viewports.as_ptr(),
scissor_count: info.scissors.len() as u32,
p_scissors: info.scissors.as_ptr(),
p_viewports: info.viewports.as_ptr(),
scissor_count: info.scissors.len() as u32,
p_scissors: info.scissors.as_ptr(),
..Default::default()
})
.collect::<Vec<_>>();
@@ -119,7 +120,7 @@ impl Pipeline {
.iter()
.map(|info| vk::PipelineColorBlendStateCreateInfo {
attachment_count: info.color_blend_attachments.len() as u32,
p_attachments: info.color_blend_attachments.as_ptr(),
p_attachments: info.color_blend_attachments.as_ptr(),
..Default::default()
})
.collect::<Vec<_>>();
@@ -130,16 +131,16 @@ impl Pipeline {
.zip(color_blend_states.iter())
.map(|((info, viewport_state), color_blend_state)| {
vk::GraphicsPipelineCreateInfo {
layout: **info.layout,
render_pass: **info.render_pass,
stage_count: info.shader_stages.len() as u32,
p_stages: info.shader_stages.as_ptr(),
p_vertex_input_state: &info.vertex_input_state,
layout: **info.layout,
render_pass: **info.render_pass,
stage_count: info.shader_stages.len() as u32,
p_stages: info.shader_stages.as_ptr(),
p_vertex_input_state: &info.vertex_input_state,
p_input_assembly_state: &info.input_assembly_state,
p_viewport_state: viewport_state,
p_rasterization_state: &info.rasterization_state,
p_multisample_state: &info.multisample_state,
p_color_blend_state: color_blend_state,
p_viewport_state: viewport_state,
p_rasterization_state: &info.rasterization_state,
p_multisample_state: &info.multisample_state,
p_color_blend_state: color_blend_state,
..Default::default()
}
})
@@ -163,9 +164,9 @@ impl Pipeline {
.map(|(&handle, info)| {
Rc::new(Self {
handle,
device: device.clone(),
device: device.clone(),
shader_data: info.shader_data.clone(),
layout: info.layout.clone(),
layout: info.layout.clone(),
render_pass: info.render_pass.clone(),
})
})


+ 2
- 2
source/render/pipelinelayout.rs View File

@@ -12,11 +12,11 @@ impl PipelineLayout {
pub fn create(
descriptor: Rc<DescriptorSetLayout>,
) -> Result<Rc<Self>, vk::Result> {
let set_layouts = [ **descriptor ];
let set_layouts = [**descriptor];

let create_info = vk::PipelineLayoutCreateInfo {
set_layout_count: set_layouts.len() as u32,
p_set_layouts: set_layouts.as_ptr(),
p_set_layouts: set_layouts.as_ptr(),
..Default::default()
};



+ 1
- 1
source/render/properties.rs View File

@@ -16,7 +16,7 @@ impl std::error::Error for ErrNoProperty {}
pub fn ensure_properties<T, F>(
props: &[T],
names: &[*const c_char],
func: F,
func: F,
) -> Result<(), ErrNoProperty>
where
F: Fn(&T) -> *const c_char,


+ 11
- 8
source/render/queue.rs View File

@@ -16,7 +16,7 @@ pub struct Queue {
handle: vk::Queue,

pub device: Rc<Device>,
pub index: QueueIndex,
pub index: QueueIndex,
}

#[derive(Debug)]
@@ -27,8 +27,8 @@ pub enum ErrQueueFamilyCollect {

impl QueueFamilyInfo {
pub fn collect(
instance: &Instance,
surface: &Surface,
instance: &Instance,
surface: &Surface,
phys_device: &PhysicalDevice,
) -> Result<Self, ErrQueueFamilyCollect> {
let mut gfx_index = None;
@@ -42,11 +42,14 @@ impl QueueFamilyInfo {
let i = i as u32;

let surface_support = unsafe {
instance.surface_ext.get_physical_device_surface_support(
**phys_device,
i,
**surface,
).unwrap_or(false)
instance
.surface_ext
.get_physical_device_surface_support(
**phys_device,
i,
**surface,
)
.unwrap_or(false)
};

if queue.queue_flags.contains(vk::QueueFlags::GRAPHICS) {


+ 35
- 44
source/render/renderpass.rs View File

@@ -13,57 +13,48 @@ impl RenderPass {
device: Rc<Device>,
format: vk::Format,
) -> Result<Rc<Self>, vk::Result> {
let attachments = [
vk::AttachmentDescription {
format,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::STORE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::UNDEFINED,
final_layout: vk::ImageLayout::PRESENT_SRC_KHR,
}
];
let attachments = [vk::AttachmentDescription {
format,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::STORE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::UNDEFINED,
final_layout: vk::ImageLayout::PRESENT_SRC_KHR,
}];

let attachment_references = [
vk::AttachmentReference {
attachment: 0,
layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
}
];
let attachment_references = [vk::AttachmentReference {
attachment: 0,
layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
}];

let subpasses = [
vk::SubpassDescription {
pipeline_bind_point: vk::PipelineBindPoint::GRAPHICS,
color_attachment_count: attachment_references.len() as u32,
p_color_attachments: attachment_references.as_ptr(),
..Default::default()
}
];
let subpasses = [vk::SubpassDescription {
pipeline_bind_point: vk::PipelineBindPoint::GRAPHICS,
color_attachment_count: attachment_references.len() as u32,
p_color_attachments: attachment_references.as_ptr(),
..Default::default()
}];

let dependencies = [
vk::SubpassDependency {
src_subpass: vk::SUBPASS_EXTERNAL,
dst_subpass: 0,
src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
src_access_mask: vk::AccessFlags::empty(),
dst_access_mask:
vk::AccessFlags::COLOR_ATTACHMENT_READ |
vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
dependency_flags: vk::DependencyFlags::empty(),
}
];
let dependencies = [vk::SubpassDependency {
src_subpass: vk::SUBPASS_EXTERNAL,
dst_subpass: 0,
src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
src_access_mask: vk::AccessFlags::empty(),
dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ
| vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
dependency_flags: vk::DependencyFlags::empty(),
}];

let create_info = vk::RenderPassCreateInfo {
attachment_count: attachments.len() as u32,
p_attachments: attachments.as_ptr(),
subpass_count: subpasses.len() as u32,
p_subpasses: subpasses.as_ptr(),
p_attachments: attachments.as_ptr(),
subpass_count: subpasses.len() as u32,
p_subpasses: subpasses.as_ptr(),
dependency_count: dependencies.len() as u32,
p_dependencies: dependencies.as_ptr(),
p_dependencies: dependencies.as_ptr(),
..Default::default()
};



+ 1
- 1
source/render/semaphore.rs View File

@@ -17,7 +17,7 @@ impl Semaphore {

pub fn create_all(
device: Rc<Device>,
num: usize,
num: usize,
) -> Result<Vec<Rc<Self>>, vk::Result> {
(0..num).map(|_| Self::create(device.clone())).collect()
}


+ 2
- 2
source/render/shader.rs View File

@@ -11,11 +11,11 @@ pub struct ShaderModule {
impl ShaderModule {
pub fn create(
device: Rc<Device>,
spir: &Spir,
spir: &Spir,
) -> Result<Rc<Self>, vk::Result> {
let create_info = vk::ShaderModuleCreateInfo {
code_size: spir.size,
p_code: spir.code.as_ptr(),
p_code: spir.code.as_ptr(),
..Default::default()
};



+ 1
- 1
source/render/surface.rs View File

@@ -11,7 +11,7 @@ pub struct Surface {
impl Surface {
pub fn create(
instance: Rc<Instance>,
window: &crate::hal::Window,
window: &crate::hal::Window,
) -> Result<Rc<Self>, crate::hal::ErrSdl> {
let handle = window.vulkan_create_surface(&instance)?;
Ok(Rc::new(Self { handle, instance }))


+ 32
- 30
source/render/swapchain.rs View File

@@ -7,7 +7,7 @@ use std::rc::Rc;
pub struct Swapchain {
handle: vk::SwapchainKHR,

pub device: Rc<Device>,
pub device: Rc<Device>,
pub surface: Rc<Surface>,

pub format: vk::Format,
@@ -16,12 +16,12 @@ pub struct Swapchain {

impl Swapchain {
pub fn create(
device: Rc<Device>,
phys_device: &PhysicalDevice,
surface: Rc<Surface>,
conf: &Conf,
device: Rc<Device>,
phys_device: &PhysicalDevice,
surface: Rc<Surface>,
conf: &Conf,
queue_graphics: &Queue,
queue_surface: &Queue,
queue_surface: &Queue,
) -> Result<Rc<Self>, vk::Result> {
let capabilities = unsafe {
device.instance.surface_ext.get_physical_device_surface_capabilities(
@@ -38,10 +38,13 @@ impl Swapchain {
};

let modes = unsafe {
device.instance.surface_ext.get_physical_device_surface_present_modes(
**phys_device,
**surface,
)?
device
.instance
.surface_ext
.get_physical_device_surface_present_modes(
**phys_device,
**surface,
)?
};

let extent = if capabilities.current_extent.width != u32::max_value() {
@@ -62,8 +65,8 @@ impl Swapchain {
let format = *formats
.iter()
.find(|format| {
format.format == vk::Format::B8G8R8A8_UNORM &&
format.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR
format.format == vk::Format::B8G8R8A8_UNORM
&& format.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR
})
.unwrap_or_else(|| &formats[0]);

@@ -74,36 +77,35 @@ impl Swapchain {

let min_image_count = capabilities.min_image_count + 1;

let min_image_count =
if capabilities.max_image_count > 0 &&
min_image_count > capabilities.max_image_count
{
capabilities.max_image_count
} else {
min_image_count
};
let min_image_count = if capabilities.max_image_count > 0
&& min_image_count > capabilities.max_image_count
{
capabilities.max_image_count
} else {
min_image_count
};

let queue_family_indices = [queue_graphics.index, queue_surface.index];

let create_info = vk::SwapchainCreateInfoKHR {
min_image_count,
present_mode: mode,
image_extent: extent,
surface: **surface,
image_format: format.format,
image_color_space: format.color_space,
present_mode: mode,
image_extent: extent,
surface: **surface,
image_format: format.format,
image_color_space: format.color_space,
image_array_layers: 1,
image_usage: vk::ImageUsageFlags::COLOR_ATTACHMENT,
image_usage: vk::ImageUsageFlags::COLOR_ATTACHMENT,
image_sharing_mode: if queue_graphics.index != queue_surface.index {
vk::SharingMode::CONCURRENT
} else {
vk::SharingMode::EXCLUSIVE
},
queue_family_index_count: queue_family_indices.len() as u32,
p_queue_family_indices: queue_family_indices.as_ptr(),
pre_transform: capabilities.current_transform,
composite_alpha: vk::CompositeAlphaFlagsKHR::OPAQUE,
clipped: vk::TRUE,
p_queue_family_indices: queue_family_indices.as_ptr(),
pre_transform: capabilities.current_transform,
composite_alpha: vk::CompositeAlphaFlagsKHR::OPAQUE,
clipped: vk::TRUE,
..Default::default()
};



+ 9
- 10
source/render/uniforms.rs View File

@@ -3,21 +3,20 @@ use cgmath::Matrix4;

#[repr(C, align(16))]
pub struct Uniforms {
pub object: Matrix4<f32>,
pub camera: Matrix4<f32>,
pub object: Matrix4<f32>,
pub camera: Matrix4<f32>,
pub projection: Matrix4<f32>,
}

impl Uniforms {
pub const BIND_DESC: [vk::DescriptorSetLayoutBinding; 1] = [
vk::DescriptorSetLayoutBinding {
binding: 0,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: 1,
stage_flags: vk::ShaderStageFlags::VERTEX,
pub const BIND_DESC: [vk::DescriptorSetLayoutBinding; 1] =
[vk::DescriptorSetLayoutBinding {
binding: 0,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: 1,
stage_flags: vk::ShaderStageFlags::VERTEX,
p_immutable_samplers: std::ptr::null(),
}
];
}];
}

// EOF

+ 12
- 13
source/render/vertex.rs View File

@@ -3,31 +3,30 @@ use cgmath::{Vector2, Vector3};

#[repr(C, packed)]
pub struct Vertex {
pub pos: Vector2<f32>,
pub pos: Vector2<f32>,
pub color: Vector3<f32>,
}

impl Vertex {
pub const BIND_DESC: [vk::VertexInputBindingDescription; 1] = [
vk::VertexInputBindingDescription {
binding: 0,
stride: std::mem::size_of::<Self>() as u32,
pub const BIND_DESC: [vk::VertexInputBindingDescription; 1] =
[vk::VertexInputBindingDescription {
binding: 0,
stride: std::mem::size_of::<Self>() as u32,
input_rate: vk::VertexInputRate::VERTEX,
}
];
}];

pub const ATTR_DESC: [vk::VertexInputAttributeDescription; 2] = [
vk::VertexInputAttributeDescription {
location: 0,
binding: 0,
format: vk::Format::R32G32_SFLOAT,
offset: 0,
binding: 0,
format: vk::Format::R32G32_SFLOAT,
offset: 0,
},
vk::VertexInputAttributeDescription {
location: 1,
binding: 0,
format: vk::Format::R32G32B32_SFLOAT,
offset: std::mem::size_of::<Vector2<f32>>() as u32,
binding: 0,
format: vk::Format::R32G32B32_SFLOAT,
offset: std::mem::size_of::<Vector2<f32>>() as u32,
},
];
}


+ 7
- 7
source/util/log.rs View File

@@ -59,10 +59,10 @@ macro_rules! trace {
}

pub struct Record {
pub level: Level,
pub level: Level,
pub module: &'static str,
pub file: &'static str,
pub line: u32,
pub file: &'static str,
pub line: u32,
pub column: u32,
}

@@ -70,7 +70,7 @@ pub struct Log {
level: Level,
begin: std::time::Instant,
modes: HashMap<&'static str, Box<dyn LogMode>>,
mode: &'static str,
mode: &'static str,
}

pub trait LogMode {
@@ -85,7 +85,7 @@ impl Log {
modes,
level: Level::default(),
begin: std::time::Instant::now(),
mode: "Std",
mode: "Std",
}
}

@@ -116,9 +116,9 @@ impl Log {

pub fn write_into(
&self,
args: std::fmt::Arguments,
args: std::fmt::Arguments,