master
mitchellhansen 4 years ago
parent 59c44a2f2d
commit f5f0346d5c

@ -3,7 +3,6 @@
#![allow(unused_mut)] #![allow(unused_mut)]
extern crate cgmath; extern crate cgmath;
extern crate image; extern crate image;
extern crate nalgebra as na; extern crate nalgebra as na;
@ -35,6 +34,7 @@ use winit::dpi::LogicalSize;
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
use winit::event::{Event, WindowEvent, DeviceEvent, VirtualKeyCode, ElementState}; use winit::event::{Event, WindowEvent, DeviceEvent, VirtualKeyCode, ElementState};
use winit::platform::unix::WindowBuilderExtUnix; use winit::platform::unix::WindowBuilderExtUnix;
use crate::vkprocessor::VkProcessor;
pub mod util; pub mod util;
@ -43,157 +43,163 @@ pub mod drawables;
pub mod canvas; pub mod canvas;
pub mod compute; pub mod compute;
pub fn main() { pub fn main() {
hprof::start_frame(); hprof::start_frame();
let q1 = hprof::enter("setup"); let q1 = hprof::enter("setup");
let instance = { let instance = {
let extensions = vulkano_win::required_extensions(); let extensions = vulkano_win::required_extensions();
Instance::new(None, &extensions, None).unwrap() Instance::new(None, &extensions, None).unwrap()
}; };
{ let _callback = DebugCallback::errors_and_warnings(&instance, |msg| {
let mut processor = vkprocessor::VkProcessor::new(instance.clone()); println!("Debug callback: {:?}", msg.description);
}).ok();
{ let mut events_loop = EventLoop::new();
let g = hprof::enter("vulkan preload");
processor.create_swapchain();
processor.preload_kernels(); let mut surface = WindowBuilder::new()
processor.preload_shaders(); .with_inner_size(LogicalSize::new(800, 800));
processor.preload_textures(); // Some weird namespacing issue here
processor.preload_fonts(); let mut surface = VkSurfaceBuild::build_vk_surface(surface.clone(), &events_loop, instance.clone()).unwrap();
}
let mut processor = VkProcessor::new(&instance, surface.clone());
let q2 = hprof::enter("Game Objects"); {
let g = hprof::enter("vulkan preload");
processor.create_swapchain(surface.clone());
let mut timer = Timer::new(); processor.preload_kernels();
let mut frame_future: Box<dyn GpuFuture> = processor.preload_shaders();
Box::new(sync::now(processor.device.clone())) as Box<dyn GpuFuture>; processor.preload_textures();
processor.preload_fonts();
}
let step_size: f32 = 0.005; let q2 = hprof::enter("Game Objects");
let mut elapsed_time: f32;
let mut delta_time: f32;
let mut accumulator_time: f32 = 0.0;
let mut current_time: f32 = timer.elap_time();
let image_data = load_raw(String::from("funky-bird.jpg")); let mut timer = Timer::new();
let image_dimensions_f: (f32, f32) = ((image_data.1).0 as f32, (image_data.1).1 as f32); let mut frame_future: Box<dyn GpuFuture> =
let image_dimensions_u: (u32, u32) = image_data.1; Box::new(sync::now(processor.device.clone())) as Box<dyn GpuFuture>;
let compu_sprite1: CompuSprite =
CompuSprite::new((0.0, -0.5), (0.4, 0.4), 0, image_dimensions_f,
// Swap image to render the result to. Must match dimensions
processor.new_swap_image(image_dimensions_u));
let compute_buffer: Arc<CompuBufferHandle> = let step_size: f32 = 0.005;
processor.new_compute_buffer(image_data.0, image_data.1, 4); let mut elapsed_time: f32;
let mut delta_time: f32;
let mut accumulator_time: f32 = 0.0;
let mut current_time: f32 = timer.elap_time();
let compute_kernel: Arc<CompuKernelHandle> = let image_data = load_raw(String::from("funky-bird.jpg"));
processor.get_kernel_handle(String::from("simple-edge.compute")) let image_dimensions_f: (f32, f32) = ((image_data.1).0 as f32, (image_data.1).1 as f32);
.expect("Can't find that kernel"); let image_dimensions_u: (u32, u32) = image_data.1;
let compu_sprite1: CompuSprite =
CompuSprite::new((0.0, -0.5), (0.4, 0.4), 0, image_dimensions_f,
// Swap image to render the result to. Must match dimensions
processor.new_swap_image(image_dimensions_u));
// Get the handles for the assets let compute_buffer: Arc<CompuBufferHandle> =
let funky_handle: Arc<CanvasTextureHandle> = processor.new_compute_buffer(image_data.0, image_data.1, 4);
processor.get_texture_handle(String::from("funky-bird.jpg")).unwrap();
let sfml_handle: Arc<CanvasTextureHandle> =
processor.get_texture_handle(String::from("sfml.png")).unwrap();
//let font_handle : Arc<CanvasFontHandle> =
// processor.get_font_handle(String::from("sansation.ttf")).unwrap();
let funky_sprite = Sprite::new((0.0, 0.5), (0.5, 0.5), 0, funky_handle.clone()); let compute_kernel: Arc<CompuKernelHandle> =
let sfml_sprite = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone()); processor.get_kernel_handle(String::from("simple-edge.compute"))
let rect = Rect::new((-0.5, -0.5), (0.5, 0.5), 1); .expect("Can't find that kernel");
// Get the handles for the assets
let funky_handle: Arc<CanvasTextureHandle> =
processor.get_texture_handle(String::from("funky-bird.jpg")).unwrap();
let sfml_handle: Arc<CanvasTextureHandle> =
processor.get_texture_handle(String::from("sfml.png")).unwrap();
//let font_handle : Arc<CanvasFontHandle> =
// processor.get_font_handle(String::from("sansation.ttf")).unwrap();
//let sfml_sprite = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone()); let funky_sprite = Sprite::new((0.0, 0.5), (0.5, 0.5), 0, funky_handle.clone());
let text_sprite = Text::new((-0.1, -0.1), (10.0, 10.0), 1); let sfml_sprite = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone());
//let test_polygon = Poly::new_with_color((-0.5, -0.5), (0.5, 0.5), 1, (1.0,0.0,0.0,0.0)); let rect = Rect::new((-0.5, -0.5), (0.5, 0.5), 1);
drop(q2);
drop(q1);
let l = hprof::enter("Loop"); //let sfml_sprite = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone());
let text_sprite = Text::new((-0.1, -0.1), (10.0, 10.0), 1);
//let test_polygon = Poly::new_with_color((-0.5, -0.5), (0.5, 0.5), 1, (1.0,0.0,0.0,0.0));
let mut exit = false; drop(q2);
drop(q1);
let mut count = 0; let l = hprof::enter("Loop");
while let true = processor.is_open() { let mut exit = false;
// Take care of our timing let mut count = 0;
{
elapsed_time = timer.elap_time();
delta_time = elapsed_time - current_time;
current_time = elapsed_time;
if delta_time > 0.02 {
delta_time = 0.02;
}
accumulator_time += delta_time;
}
while (accumulator_time - step_size) >= step_size { while let true = processor.is_open() {
accumulator_time -= step_size;
// Take care of our timing
{
elapsed_time = timer.elap_time();
delta_time = elapsed_time - current_time;
current_time = elapsed_time;
if delta_time > 0.02 {
delta_time = 0.02;
} }
accumulator_time += delta_time;
}
// Events loop is borrowed from the surface while (accumulator_time - step_size) >= step_size {
processor.event_loop().clone().run(move |event, _, control_flow| { accumulator_time -= step_size;
match event { }
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } =>
{ // Events loop is borrowed from the surface
exit = true; events_loop.run(move |event, _, control_flow| {
} match event {
Event::WindowEvent { event: WindowEvent::Resized(_), .. } => { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } =>
processor.swapchain_recreate_needed = true; {
exit = true;
} }
Event::DeviceEvent { event: DeviceEvent::Key(keyboard_input), .. } => { Event::WindowEvent { event: WindowEvent::Resized(_), .. } => {
match keyboard_input.virtual_keycode.unwrap() { processor.swapchain_recreate_needed = true;
VirtualKeyCode::A => { }
if keyboard_input.state == ElementState::Pressed { Event::DeviceEvent { event: DeviceEvent::Key(keyboard_input), .. } => {
// processor.save_edges_image(); match keyboard_input.virtual_keycode.unwrap() {
} VirtualKeyCode::A => {
if keyboard_input.state == ElementState::Pressed {
// processor.save_edges_image();
} }
_ => ()
} }
_ => ()
} }
}
// Event::DeviceEvent { event: DeviceEvent::Button(mouse_input), .. } => { // Event::DeviceEvent { event: DeviceEvent::Button(mouse_input), .. } => {
// mouse_xy.x // mouse_xy.x
// }, // },
_ => () _ => ()
}
});
if exit {
break;
} }
});
let mut canvas_frame = CanvasFrame::default(); if exit {
canvas_frame.draw(&funky_sprite); break;
canvas_frame.draw(&text_sprite); }
let mut canvas_frame = CanvasFrame::default();
canvas_frame.draw(&funky_sprite);
canvas_frame.draw(&text_sprite);
// canvas_frame.draw(&rect); // canvas_frame.draw(&rect);
let mut compu_frame = CompuFrame::new(); let mut compu_frame = CompuFrame::new();
//compu_frame.add(compute_buffer.clone(), compute_kernel.clone()); //compu_frame.add(compute_buffer.clone(), compute_kernel.clone());
compu_frame.add_with_image_swap(compute_buffer.clone(), compute_kernel.clone(), &compu_sprite1); compu_frame.add_with_image_swap(compute_buffer.clone(), compute_kernel.clone(), &compu_sprite1);
{ {
let g = hprof::enter("Run"); let g = hprof::enter("Run");
processor.run(canvas_frame, processor.run(&surface.clone(),
compu_frame); canvas_frame,
} compu_frame);
} }
}
drop(l); drop(l);
hprof::end_frame(); hprof::end_frame();
hprof::profiler().print_timing(); hprof::profiler().print_timing();
drop(processor);
}
} }

@ -32,7 +32,6 @@ use winit::event_loop::EventLoop;
/// and the compute and canvas states /// and the compute and canvas states
pub struct VkProcessor<'a> { pub struct VkProcessor<'a> {
// Vulkan state fields // Vulkan state fields
pub instance: Arc<Instance>,
pub physical: PhysicalDevice<'a>, pub physical: PhysicalDevice<'a>,
pub device: Arc<Device>, pub device: Arc<Device>,
pub queues: QueuesIter, pub queues: QueuesIter,
@ -43,9 +42,6 @@ pub struct VkProcessor<'a> {
pub swapchain_recreate_needed: bool, pub swapchain_recreate_needed: bool,
pub surface: Arc<Surface<Window>>,
pub event_loop: Arc<EventLoop<()>>,
/// State holding textures, images, and their related vertex buffers /// State holding textures, images, and their related vertex buffers
canvas_state: CanvasState, canvas_state: CanvasState,
/// State holding /// State holding
@ -59,42 +55,29 @@ pub struct VkProcessor<'a> {
impl<'a> VkProcessor<'a> { impl<'a> VkProcessor<'a> {
/// Creates a new VkProcessor from an instance and surface /// Creates a new VkProcessor from an instance and surface
/// This includes the physical device, queues, compute and canvas state /// This includes the physical device, queues, compute and canvas state
//pub fn new(instance: &'a Arc<Instance>, surface: &'a Arc<Surface<Window>>) -> VkProcessor<'a> { pub fn new(instance: &'a Arc<Instance>, surface: Arc<Surface<Window>>) -> VkProcessor<'a> {
pub fn new(instance: Arc<Instance>) -> VkProcessor<'a> {
let _callback = DebugCallback::errors_and_warnings(&instance, |msg| {
println!("Debug callback: {:?}", msg.description);
}).ok();
let mut events_loop = Arc::new(EventLoop::new());
let mut surface = WindowBuilder::new()
.with_inner_size(LogicalSize::new(800, 800));
// Some weird namespacing issue here let physical = PhysicalDevice::enumerate(instance).next().unwrap();
let mut surface = VkSurfaceBuild::build_vk_surface(surface, &events_loop, instance.clone()).unwrap();
let physical = PhysicalDevice::enumerate(&instance).next().unwrap(); let queue_family = physical.queue_families().find(|&q| {
// We take the first queue that supports drawing to our window.
q.supports_graphics() &&
surface.is_supported(q).unwrap_or(false) &&
q.supports_compute()
}).unwrap();
let queue_family = physical.queue_families().find(|&q| { let device_ext = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::none() };
// We take the first queue that supports drawing to our window.
q.supports_graphics() &&
surface.is_supported(q).unwrap_or(false) &&
q.supports_compute()
}).unwrap();
let device_ext = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::none() }; let (device, mut queues) = Device::new(physical,
physical.supported_features(),
&device_ext,
[(queue_family, 0.5)].iter().cloned()).unwrap();
let queue = queues.next().unwrap();
let (device, mut queues) = Device::new(physical, let capabilities = surface.capabilities(physical).unwrap();
physical.supported_features(),
&device_ext,
[(queue_family, 0.5)].iter().cloned()).unwrap();
let queue = queues.next().unwrap();
let capabilities = surface.capabilities(physical).unwrap();
VkProcessor { VkProcessor {
instance: instance.clone(),
physical: physical.clone(), physical: physical.clone(),
device: device.clone(), device: device.clone(),
queue: queue.clone(), queue: queue.clone(),
@ -105,8 +88,6 @@ impl<'a> VkProcessor<'a> {
compute_state: CompuState::new(), compute_state: CompuState::new(),
capabilities: capabilities.clone(), capabilities: capabilities.clone(),
canvas_state: CanvasState::new(queue, device, physical, capabilities), canvas_state: CanvasState::new(queue, device, physical, capabilities),
surface: surface,
event_loop: events_loop,
} }
} }
@ -116,24 +97,19 @@ impl<'a> VkProcessor<'a> {
true true
} }
pub fn event_loop(&mut self) -> Arc<EventLoop<()>> {
self.event_loop()
}
/// Using the surface, we calculate the surface capabilities and create the swapchain and swapchain images /// Using the surface, we calculate the surface capabilities and create the swapchain and swapchain images
pub fn create_swapchain(&mut self) { pub fn create_swapchain(&mut self, surface: Arc<Surface<Window>>) {
let (mut swapchain, images) = { let (mut swapchain, images) = {
let capabilities = self.surface.capabilities(self.physical).unwrap(); let capabilities = surface.capabilities(self.physical).unwrap();
let usage = capabilities.supported_usage_flags; let usage = capabilities.supported_usage_flags;
let alpha = capabilities.supported_composite_alpha.iter().next().unwrap(); let alpha = capabilities.supported_composite_alpha.iter().next().unwrap();
// Choosing the internal format that the images will have. // Choosing the internal format that the images will have.
let format = capabilities.supported_formats[0].0; let format = capabilities.supported_formats[0].0;
// Set the swapchains window dimensions // Set the swapchains window dimensions
let initial_dimensions = if let dimensions = self.surface.window().inner_size() { let initial_dimensions = if let dimensions = surface.window().inner_size() {
// convert to physical pixels // convert to physical pixels
let dimensions: (u32, u32) = dimensions.to_logical::<u32>(self.surface.window().scale_factor()).into(); let dimensions: (u32, u32) = dimensions.to_logical::<u32>(surface.window().scale_factor()).into();
[dimensions.0, dimensions.1] [dimensions.0, dimensions.1]
} else { } else {
// The window no longer exists so exit the application. // The window no longer exists so exit the application.
@ -141,7 +117,7 @@ impl<'a> VkProcessor<'a> {
}; };
Swapchain::new(self.device.clone(), Swapchain::new(self.device.clone(),
self.surface.clone(), surface.clone(),
capabilities.min_image_count, // number of attachment images capabilities.min_image_count, // number of attachment images
format, format,
initial_dimensions, initial_dimensions,
@ -160,9 +136,9 @@ impl<'a> VkProcessor<'a> {
} }
/// On screen resizes, the swapchain and images must be recreated /// On screen resizes, the swapchain and images must be recreated
pub fn recreate_swapchain(&mut self) { pub fn recreate_swapchain(&mut self, surface: &'a Arc<Surface<Window>>) {
let dimensions = if let dimensions = self.surface.window().inner_size() { let dimensions = if let dimensions = surface.window().inner_size() {
let dimensions: (u32, u32) = dimensions.to_logical::<u32>(self.surface.window().scale_factor()).into(); let dimensions: (u32, u32) = dimensions.to_logical::<u32>(surface.window().scale_factor()).into();
[dimensions.0, dimensions.1] [dimensions.0, dimensions.1]
} else { } else {
return; return;
@ -254,6 +230,7 @@ impl<'a> VkProcessor<'a> {
/// Run the VKprocessor for a single frame, consuming the Canvas/Compu Frames /// Run the VKprocessor for a single frame, consuming the Canvas/Compu Frames
pub fn run(&mut self, pub fn run(&mut self,
surface: &'a Arc<Surface<Window>>,
canvas_frame: CanvasFrame, canvas_frame: CanvasFrame,
compute_frame: CompuFrame, compute_frame: CompuFrame,
) { ) {
@ -269,7 +246,7 @@ impl<'a> VkProcessor<'a> {
// Whenever the window resizes we need to recreate everything dependent on the window size. // Whenever the window resizes we need to recreate everything dependent on the window size.
// In this example that includes the swapchain, the framebuffers and the dynamic state viewport. // In this example that includes the swapchain, the framebuffers and the dynamic state viewport.
if self.swapchain_recreate_needed { if self.swapchain_recreate_needed {
self.recreate_swapchain(); self.recreate_swapchain(surface);
framebuffers = framebuffers =
self.canvas_state.window_size_dependent_setup(&self.swapchain_images.clone().unwrap().clone()); self.canvas_state.window_size_dependent_setup(&self.swapchain_images.clone().unwrap().clone());
self.swapchain_recreate_needed = false; self.swapchain_recreate_needed = false;

Loading…
Cancel
Save