struggling with the borrow checker

master
mitchellhansen 5 years ago
parent f903b741e0
commit 8c56bda87a

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

@ -51,7 +51,10 @@ mod vkprocessor;
fn main() { fn main() {
let processor = vkprocessor::VkProcessor::new(); let mut processor = vkprocessor::VkProcessor::new();
processor.compile_kernel();
processor.load_buffers();
let mut window = RenderWindow::new( let mut window = RenderWindow::new(
@ -66,8 +69,9 @@ fn main() {
let font = Font::from_file("resources/fonts/sansation.ttf").unwrap(); let font = Font::from_file("resources/fonts/sansation.ttf").unwrap();
let xy = processor.img.unwrap().dimensions();
let mut bg_texture = Texture::new(xy.0, xy.1).unwrap(); let mut bg_texture = Texture::new(xy.0, xy.1).unwrap();
bg_texture.update_from_pixels(image_buffer.as_slice(), xy.0, xy.1, 0, 0); bg_texture.update_from_pixels(processor.image_buffer.as_slice(), xy.0, xy.1, 0, 0);
let mut background_sprite = Sprite::with_texture(&bg_texture); let mut background_sprite = Sprite::with_texture(&bg_texture);
background_sprite.set_position((0., 0.)); background_sprite.set_position((0., 0.));

@ -1,6 +1,6 @@
use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer, DeviceLocalBuffer, ImmutableBuffer, BufferAccess}; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer, DeviceLocalBuffer, ImmutableBuffer, BufferAccess};
use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::command_buffer::AutoCommandBufferBuilder;
use vulkano::descriptor::descriptor_set::PersistentDescriptorSet; use vulkano::descriptor::descriptor_set::{PersistentDescriptorSet, StdDescriptorPoolAlloc};
use vulkano::device::{Device, DeviceExtensions, QueuesIter, Queue}; use vulkano::device::{Device, DeviceExtensions, QueuesIter, Queue};
use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice, QueueFamily}; use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice, QueueFamily};
use vulkano::pipeline::ComputePipeline; use vulkano::pipeline::ComputePipeline;
@ -12,21 +12,30 @@ use std::ffi::CStr;
use std::path::PathBuf; use std::path::PathBuf;
use shade_runner as sr; use shade_runner as sr;
use image::DynamicImage; use image::DynamicImage;
use image::GenericImageView;
use vulkano::descriptor::pipeline_layout::PipelineLayout;
use image::GenericImage;
use shade_runner::ComputeLayout;
use vulkano::descriptor::descriptor_set::PersistentDescriptorSetBuf;
pub struct VkProcessor<'a> { pub struct VkProcessor<'a> {
instance: Arc<Instance>, pub instance: Arc<Instance>,
physical: PhysicalDevice<'a>, pub physical: PhysicalDevice<'a>,
queue_family: QueueFamily<'a>, pub queue_family: QueueFamily<'a>,
device: Arc<Device>, pub pipeline: Option<Arc<ComputePipeline<PipelineLayout<shade_runner::layouts::ComputeLayout>>>>,
queues: QueuesIter, pub device: Arc<Device>,
queue: Arc<Queue>, pub queues: QueuesIter,
img: Option<DynamicImage>, pub queue: Arc<Queue>,
image_buffer: Vec<u8>, pub set: Option<Arc<PersistentDescriptorSet<std::sync::Arc<ComputePipeline<PipelineLayout<shade_runner::layouts::ComputeLayout>>>, ((((), PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u8]>>>), PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u8]>>>), PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u32]>>>)>>>,
buffers: Vec:: pub img: Option<DynamicImage>,
pub image_buffer: Vec<u8>,
pub img_buffers: Vec<Arc<CpuAccessibleBuffer<[u8]>>>,
pub settings_buffer: Option<Arc<CpuAccessibleBuffer<[u32]>>>,
} }
impl VkProcessor { impl<'a> VkProcessor<'a> {
pub fn new() -> VkProcessor { pub fn new() -> VkProcessor<'a> {
let instance = Instance::new(None, &InstanceExtensions::none(), None).unwrap(); let instance = Instance::new(None, &InstanceExtensions::none(), None).unwrap();
let physical = PhysicalDevice::enumerate(&instance).next().unwrap(); let physical = PhysicalDevice::enumerate(&instance).next().unwrap();
let queue_family = physical.queue_families().find(|&q| q.supports_compute()).unwrap(); let queue_family = physical.queue_families().find(|&q| q.supports_compute()).unwrap();
@ -34,17 +43,23 @@ impl VkProcessor {
physical.supported_features(), physical.supported_features(),
&DeviceExtensions::none(), &DeviceExtensions::none(),
[(queue_family, 0.5)].iter().cloned()).unwrap(); [(queue_family, 0.5)].iter().cloned()).unwrap();
// Self referential struct problem
VkProcessor { VkProcessor {
instance: instance, instance: instance.clone(),
physical: physical, physical: physical.clone(),
queue_family: queue_family, queue_family: physical.queue_families().find(|&q| q.supports_compute()).unwrap(),
pipeline: Option::None,
device: device, device: device,
queues: queues, queues: queues,
queue: queues.next().unwrap(), queue: queues.next().unwrap(),
img: Option::None, img: Option::None,
set: Option::None,
image_buffer: Vec::new(), image_buffer: Vec::new(),
buffers: Vec::new(), img_buffers: Vec::new(),
settings_buffer: Option::None,
} }
} }
pub fn compile_kernel(&mut self) { pub fn compile_kernel(&mut self) {
@ -68,20 +83,21 @@ impl VkProcessor {
).unwrap() ).unwrap()
} }
}); });
} }
pub fn load_buffers(&mut self) { pub fn load_buffers(&mut self) {
self.img = Option::Some(image::open("resources/images/funky-bird.jpg").unwrap()); self.img = Option::Some(image::open("resources/images/funky-bird.jpg").unwrap());
let xy = self.img.dimensions(); let xy = self.img.unwrap().dimensions();
let data_length = xy.0 * xy.1 * 4; let data_length = xy.0 * xy.1 * 4;
let pixel_count = self.img.raw_pixels().len(); let pixel_count = self.img.unwrap().raw_pixels().len();
println!("Pixel count {}", pixel_count); println!("Pixel count {}", pixel_count);
if pixel_count != data_length as usize { if pixel_count != data_length as usize {
println!("Creating apha channel..."); println!("Creating apha channel...");
for i in self.img.raw_pixels().iter() { for i in self.img.unwrap().raw_pixels().iter() {
if (self.image_buffer.len() + 1) % 4 == 0 { if (self.image_buffer.len() + 1) % 4 == 0 {
self.image_buffer.push(255); self.image_buffer.push(255);
} }
@ -89,58 +105,63 @@ impl VkProcessor {
} }
self.image_buffer.push(255); self.image_buffer.push(255);
} else { } else {
self.image_buffer = self.img.raw_pixels(); self.image_buffer = self.img.unwrap().raw_pixels();
} }
println!("Buffer length {}", self.image_buffer.len()); println!("Buffer length {}", self.image_buffer.len());
println!("Size {:?}", xy); println!("Size {:?}", xy);
println!("Allocating Buffers..."); println!("Allocating Buffers...");
{
// Pull out the image data and place it in a buffer for the kernel to write to and for us to read from // Pull out the image data and place it in a buffer for the kernel to write to and for us to read from
let write_buffer = { let write_buffer = {
let mut buff = image_buffer.iter(); let mut buff = self.image_buffer.iter();
let data_iter = (0..data_length).map(|n| *(buff.next().unwrap())); let data_iter = (0..data_length).map(|n| *(buff.next().unwrap()));
CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter).unwrap() CpuAccessibleBuffer::from_iter(self.device.clone(), BufferUsage::all(), data_iter).unwrap()
}; };
self.img_buffers.push(write_buffer);
// Pull out the image data and place it in a buffer for the kernel to read from
let read_buffer = { // Pull out the image data and place it in a buffer for the kernel to read from
let mut buff = image_buffer.iter(); let read_buffer = {
let data_iter = (0..data_length).map(|n| *(buff.next().unwrap())); let mut buff = self.image_buffer.iter();
CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter).unwrap() let data_iter = (0..data_length).map(|n| *(buff.next().unwrap()));
}; CpuAccessibleBuffer::from_iter(self.device.clone(), BufferUsage::all(), data_iter).unwrap()
};
// A buffer to hold many i32 values to use as settings self.img_buffers.push(read_buffer);
let settings_buffer = {
let vec = vec![xy.0, xy.1]; // A buffer to hold many i32 values to use as settings
let mut buff = vec.iter(); let settings_buffer = {
let data_iter = (0..2).map(|n| *(buff.next().unwrap())); let vec = vec![xy.0, xy.1];
CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter).unwrap() let mut buff = vec.iter();
}; let data_iter = (0..2).map(|n| *(buff.next().unwrap()));
} CpuAccessibleBuffer::from_iter(self.device.clone(), BufferUsage::all(), data_iter).unwrap()
};
self.settings_buffer = Some(settings_buffer);
println!("Done"); println!("Done");
// Create the data descriptor set for our previously created shader pipeline // Create the data descriptor set for our previously created shader pipeline
let mut set = PersistentDescriptorSet::start(pipeline.clone(), 0) let mut set = PersistentDescriptorSet::start(self.pipeline.unwrap().clone(), 0)
.add_buffer(write_buffer.clone()).unwrap() .add_buffer(write_buffer.clone()).unwrap()
.add_buffer(read_buffer.clone()).unwrap() .add_buffer(read_buffer.clone()).unwrap()
.add_buffer(settings_buffer.clone()).unwrap(); .add_buffer(settings_buffer.clone()).unwrap();
let mut set = Arc::new(set.build().unwrap()); // self.set = Some(Arc::new(set.build().unwrap()));
} }
pub fn run_kernel(&mut self) { pub fn run_kernel(&mut self) {
println!("Running Kernel..."); println!("Running Kernel...");
let xy = self.img.unwrap().dimensions();
// The command buffer I think pretty much serves to define what runs where for how many times // The command buffer I think pretty much serves to define what runs where for how many times
let command_buffer = AutoCommandBufferBuilder::primary_one_time_submit(device.clone(), queue.family()).unwrap() let command_buffer = AutoCommandBufferBuilder::primary_one_time_submit(self.device.clone(), self.queue.family()).unwrap()
.dispatch([xy.0, xy.1, 1], pipeline.clone(), set.clone(), ()).unwrap() .dispatch([xy.0, xy.1, 1], self.pipeline.unwrap().clone(), self.set.unwrap().clone(), ()).unwrap()
.build().unwrap(); .build().unwrap();
// Create a future for running the command buffer and then just fence it // Create a future for running the command buffer and then just fence it
let future = sync::now(device.clone()) let future = sync::now(self.device.clone())
.then_execute(queue.clone(), command_buffer).unwrap() .then_execute(self.queue.clone(), command_buffer).unwrap()
.then_signal_fence_and_flush().unwrap(); .then_signal_fence_and_flush().unwrap();
// I think this is redundant and returns immediately // I think this is redundant and returns immediately
@ -148,10 +169,12 @@ impl VkProcessor {
println!("Done running kernel"); println!("Done running kernel");
} }
pub fn read_image() -> Vec<u8> { pub fn read_image(&self) -> Vec<u8> {
let xy = self.img.unwrap().dimensions();
// The buffer is sync'd so we can just read straight from the handle // The buffer is sync'd so we can just read straight from the handle
let mut data_buffer_content = write_buffer.read().unwrap(); let mut data_buffer_content = self.img_buffers.get(0).unwrap().read().unwrap();
println!("Reading output"); println!("Reading output");
@ -170,7 +193,7 @@ impl VkProcessor {
image_buffer.push(b); image_buffer.push(b);
image_buffer.push(a); image_buffer.push(a);
img.put_pixel(x, y, image::Rgba([r, g, b, a])) self.img.unwrap().put_pixel(x, y, image::Rgba([r, g, b, a]))
} }
} }
@ -179,7 +202,7 @@ impl VkProcessor {
pub fn save_image(&self) { pub fn save_image(&self) {
println!("Saving output"); println!("Saving output");
img.save(format!("output/{}.png", SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs())); self.img.unwrap().save(format!("output/{}.png", SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs()));
} }
} }

Loading…
Cancel
Save