use rustfmt for formatting after edits

This commit is contained in:
porky11 2019-01-12 19:15:48 +01:00
parent 6675a4d3e4
commit a5a5b88014
17 changed files with 464 additions and 445 deletions

View File

@ -28,15 +28,15 @@ fn main() {
let fs_bytes = include_bytes!("./../data/hello_triangle.frag.spv");
let fs_module = device.create_shader_module(fs_bytes);
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[],
});
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[] });
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let blend_state0 = device.create_blend_state(&wgpu::BlendStateDescriptor::REPLACE);
let depth_stencil_state = device.create_depth_stencil_state(&wgpu::DepthStencilStateDescriptor::IGNORE);
let depth_stencil_state =
device.create_depth_stencil_state(&wgpu::DepthStencilStateDescriptor::IGNORE);
let _render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout,
@ -54,17 +54,13 @@ fn main() {
],
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
attachments_state: wgpu::AttachmentsState {
color_attachments: &[
wgpu::Attachment {
format: wgpu::TextureFormat::R8g8b8a8Unorm,
samples: 1,
},
],
color_attachments: &[wgpu::Attachment {
format: wgpu::TextureFormat::R8g8b8a8Unorm,
samples: 1,
}],
depth_stencil_attachment: None,
},
blend_states: &[
&blend_state0,
],
blend_states: &[&blend_state0],
depth_stencil_state: &depth_stencil_state,
});
@ -72,20 +68,17 @@ fn main() {
{
let rpass = cmd_buf.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[
wgpu::RenderPassColorAttachmentDescriptor {
attachment: &color_view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color::GREEN,
},
],
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &color_view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color::GREEN,
}],
depth_stencil_attachment: None,
});
rpass.end_pass();
}
let queue = device.get_queue();
queue.submit(&[cmd_buf]);
}

View File

@ -2,7 +2,6 @@ use hal;
use {BindGroupLayoutId, BufferId, SamplerId, TextureViewId};
bitflags! {
#[repr(transparent)]
pub struct ShaderStageFlags: u32 {

View File

@ -1,6 +1,6 @@
use super::CommandBuffer;
use track::Tracker;
use {DeviceId, LifeGuard, Stored};
use track::{Tracker};
use hal::command::RawCommandBuffer;
use hal::pool::RawCommandPool;
@ -37,7 +37,9 @@ impl<B: hal::Backend> Inner<B> {
fn recycle(&mut self, cmd_buf: CommandBuffer<B>) {
let pool = self.pools.get_mut(&cmd_buf.recorded_thread_id).unwrap();
for mut raw in cmd_buf.raw {
unsafe { raw.reset(false); }
unsafe {
raw.reset(false);
}
pool.available.push(raw);
}
self.fences.push(cmd_buf.fence);
@ -62,7 +64,9 @@ impl<B: hal::Backend> CommandAllocator<B> {
}
pub(crate) fn allocate(
&self, device_id: Stored<DeviceId>, device: &B::Device
&self,
device_id: Stored<DeviceId>,
device: &B::Device,
) -> CommandBuffer<B> {
let thread_id = thread::current().id();
let mut inner = self.inner.lock().unwrap();
@ -72,16 +76,17 @@ impl<B: hal::Backend> CommandAllocator<B> {
unsafe { device.reset_fence(&fence).unwrap() };
fence
}
None => {
device.create_fence(false).unwrap()
}
None => device.create_fence(false).unwrap(),
};
let pool = inner.pools.entry(thread_id).or_insert_with(|| CommandPool {
raw: unsafe { device.create_command_pool(
self.queue_family,
hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL,
)}.unwrap(),
raw: unsafe {
device.create_command_pool(
self.queue_family,
hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL,
)
}
.unwrap(),
available: Vec::new(),
});
let init = pool.allocate();

View File

@ -1,15 +1,11 @@
use registry::{HUB, Items};
use {
Stored,
BindGroupId, CommandBufferId, ComputePassId, ComputePipelineId,
};
use registry::{Items, HUB};
use {BindGroupId, CommandBufferId, ComputePassId, ComputePipelineId, Stored};
use hal;
use hal::command::RawCommandBuffer;
use std::iter;
pub struct ComputePass<B: hal::Backend> {
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
@ -17,20 +13,13 @@ pub struct ComputePass<B: hal::Backend> {
impl<B: hal::Backend> ComputePass<B> {
pub(crate) fn new(raw: B::CommandBuffer, cmb_id: Stored<CommandBufferId>) -> Self {
ComputePass {
raw,
cmb_id,
}
ComputePass { raw, cmb_id }
}
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_end_pass(
pass_id: ComputePassId,
) -> CommandBufferId {
let pass = HUB.compute_passes
.write()
.take(pass_id);
pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandBufferId {
let pass = HUB.compute_passes.write().take(pass_id);
HUB.command_buffers
.write()
@ -42,7 +31,9 @@ pub extern "C" fn wgpu_compute_pass_end_pass(
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_set_bind_group(
pass_id: ComputePassId, index: u32, bind_group_id: BindGroupId,
pass_id: ComputePassId,
index: u32,
bind_group_id: BindGroupId,
) {
let bind_group_guard = HUB.bind_groups.read();
let set = &bind_group_guard.get(bind_group_id).raw;
@ -60,11 +51,12 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group(
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_set_pipeline(
pass_id: ComputePassId, pipeline_id: ComputePipelineId,
pass_id: ComputePassId,
pipeline_id: ComputePipelineId,
) {
let pipeline_guard = HUB.compute_pipelines.read();
let pipeline = &pipeline_guard.get(pipeline_id).raw;
unsafe {
HUB.compute_passes
.write()
@ -75,9 +67,7 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline(
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_dispatch(
pass_id: ComputePassId, x: u32, y: u32, z: u32,
) {
pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) {
unsafe {
HUB.compute_passes
.write()

View File

@ -6,23 +6,22 @@ pub(crate) use self::allocator::CommandAllocator;
pub use self::compute::*;
pub use self::render::*;
use hal::{self, Device};
use hal::command::RawCommandBuffer;
use hal::{self, Device};
use {
B, Color, LifeGuard, Origin3d, Stored, BufferUsageFlags, TextureUsageFlags, WeaklyStored,
BufferId, CommandBufferId, ComputePassId, DeviceId, RenderPassId, TextureId, TextureViewId,
};
use {conv, resource};
use device::{FramebufferKey, RenderPassKey};
use registry::{HUB, Items};
use registry::{Items, HUB};
use track::{BufferTracker, TextureTracker};
use {conv, resource};
use {
BufferId, BufferUsageFlags, Color, CommandBufferId, ComputePassId, DeviceId, LifeGuard,
Origin3d, RenderPassId, Stored, TextureId, TextureUsageFlags, TextureViewId, WeaklyStored, B,
};
use std::collections::hash_map::Entry;
use std::ops::Range;
use std::thread::ThreadId;
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum LoadOp {
@ -105,10 +104,12 @@ impl CommandBuffer<B> {
let b = buffer_guard.get(id);
trace!("transit {:?} {:?}", id, transit);
hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(transit.start) ..
conv::map_buffer_state(transit.end),
states: conv::map_buffer_state(transit.start)..conv::map_buffer_state(transit.end),
target: &b.raw,
range: Range { start: None, end: None},
range: Range {
start: None,
end: None,
},
families: None,
}
});
@ -117,8 +118,8 @@ impl CommandBuffer<B> {
trace!("transit {:?} {:?}", id, transit);
let aspects = t.full_range.aspects;
hal::memory::Barrier::Image {
states: conv::map_texture_state(transit.start, aspects) ..
conv::map_texture_state(transit.end, aspects),
states: conv::map_texture_state(transit.start, aspects)
..conv::map_texture_state(transit.end, aspects),
target: &t.raw,
range: t.full_range.clone(), //TODO?
families: None,
@ -126,7 +127,7 @@ impl CommandBuffer<B> {
});
unsafe {
raw.pipeline_barrier(
hal::pso::PipelineStage::TOP_OF_PIPE .. hal::pso::PipelineStage::BOTTOM_OF_PIPE,
hal::pso::PipelineStage::TOP_OF_PIPE..hal::pso::PipelineStage::BOTTOM_OF_PIPE,
hal::memory::Dependencies::empty(),
buffer_barriers.chain(texture_barriers),
);
@ -178,31 +179,29 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
samples: view.samples,
ops: conv::map_load_store_ops(at.depth_load_op, at.depth_store_op),
stencil_ops: conv::map_load_store_ops(at.stencil_load_op, at.stencil_store_op),
layouts: layout .. layout,
layouts: layout..layout,
})
}
None => None,
};
let color_keys = desc.color_attachments
.iter()
.map(|at| {
let view = view_guard.get(at.attachment);
if let Some(ex) = extent {
assert_eq!(ex, view.extent);
} else {
extent = Some(view.extent);
}
let query = tracker.query(&view.texture_id, TextureUsageFlags::empty());
let (_, layout) = conv::map_texture_state(query.usage, hal::format::Aspects::COLOR);
hal::pass::Attachment {
format: Some(conv::map_texture_format(view.format)),
samples: view.samples,
ops: conv::map_load_store_ops(at.load_op, at.store_op),
stencil_ops: hal::pass::AttachmentOps::DONT_CARE,
layouts: layout .. layout,
}
});
let color_keys = desc.color_attachments.iter().map(|at| {
let view = view_guard.get(at.attachment);
if let Some(ex) = extent {
assert_eq!(ex, view.extent);
} else {
extent = Some(view.extent);
}
let query = tracker.query(&view.texture_id, TextureUsageFlags::empty());
let (_, layout) = conv::map_texture_state(query.usage, hal::format::Aspects::COLOR);
hal::pass::Attachment {
format: Some(conv::map_texture_format(view.format)),
samples: view.samples,
ops: conv::map_load_store_ops(at.load_op, at.store_op),
stencil_ops: hal::pass::AttachmentOps::DONT_CARE,
layouts: layout..layout,
}
});
RenderPassKey {
attachments: color_keys.chain(depth_stencil_key).collect(),
@ -219,31 +218,40 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
(2, hal::image::Layout::ColorAttachmentOptimal),
(3, hal::image::Layout::ColorAttachmentOptimal),
];
let depth_id = (desc.color_attachments.len(), hal::image::Layout::DepthStencilAttachmentOptimal);
let depth_id = (
desc.color_attachments.len(),
hal::image::Layout::DepthStencilAttachmentOptimal,
);
let subpass = hal::pass::SubpassDesc {
colors: &color_ids[.. desc.color_attachments.len()],
colors: &color_ids[..desc.color_attachments.len()],
depth_stencil: desc.depth_stencil_attachment.as_ref().map(|_| &depth_id),
inputs: &[],
resolves: &[],
preserves: &[],
};
let pass = unsafe { device.raw.create_render_pass(
&e.key().attachments,
&[subpass],
&[],
)}.unwrap();
let pass = unsafe {
device
.raw
.create_render_pass(&e.key().attachments, &[subpass], &[])
}
.unwrap();
e.insert(pass)
}
};
let mut framebuffer_cache = device.framebuffers.lock();
let fb_key = FramebufferKey {
attachments: desc.color_attachments
attachments: desc
.color_attachments
.iter()
.map(|at| WeaklyStored(at.attachment))
.chain(desc.depth_stencil_attachment.as_ref().map(|at| WeaklyStored(at.attachment)))
.chain(
desc.depth_stencil_attachment
.as_ref()
.map(|at| WeaklyStored(at.attachment)),
)
.collect(),
};
let framebuffer = match framebuffer_cache.entry(fb_key) {
@ -256,9 +264,12 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
.iter()
.map(|&WeaklyStored(id)| &view_guard.get(id).raw);
unsafe { device.raw
.create_framebuffer(&render_pass, attachments, extent.unwrap())
}.unwrap()
unsafe {
device
.raw
.create_framebuffer(&render_pass, attachments, extent.unwrap())
}
.unwrap()
};
e.insert(fb)
}
@ -273,7 +284,8 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
h: ex.height as _,
}
};
let clear_values = desc.color_attachments
let clear_values = desc
.color_attachments
.iter()
.map(|at| {
//TODO: integer types?
@ -284,7 +296,7 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
let value = hal::command::ClearDepthStencil(at.clear_depth, at.clear_stencil);
hal::command::ClearValueRaw::from(hal::command::ClearValue::DepthStencil(value))
}));
unsafe {
current_comb.begin_render_pass(
render_pass,
@ -295,15 +307,13 @@ pub extern "C" fn wgpu_command_buffer_begin_render_pass(
);
}
HUB.render_passes
.write()
.register(RenderPass::new(
current_comb,
Stored {
value: command_buffer_id,
ref_count: cmb.life_guard.ref_count.clone(),
},
))
HUB.render_passes.write().register(RenderPass::new(
current_comb,
Stored {
value: command_buffer_id,
ref_count: cmb.life_guard.ref_count.clone(),
},
))
}
#[no_mangle]

View File

@ -1,14 +1,10 @@
use registry::{HUB, Items};
use registry::{Items, HUB};
use track::{BufferTracker, TextureTracker};
use {
CommandBuffer, Stored,
CommandBufferId, RenderPassId,
};
use {CommandBuffer, CommandBufferId, RenderPassId, Stored};
use hal;
use hal::command::RawCommandBuffer;
pub struct RenderPass<B: hal::Backend> {
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
@ -17,10 +13,7 @@ pub struct RenderPass<B: hal::Backend> {
}
impl<B: hal::Backend> RenderPass<B> {
pub(crate) fn new(
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
) -> Self {
pub(crate) fn new(raw: B::CommandBuffer, cmb_id: Stored<CommandBufferId>) -> Self {
RenderPass {
raw,
cmb_id,
@ -31,13 +24,11 @@ impl<B: hal::Backend> RenderPass<B> {
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_end_pass(
pass_id: RenderPassId,
) -> CommandBufferId {
let mut pass = HUB.render_passes
.write()
.take(pass_id);
unsafe {pass.raw.end_render_pass(); }
pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) -> CommandBufferId {
let mut pass = HUB.render_passes.write().take(pass_id);
unsafe {
pass.raw.end_render_pass();
}
let mut cmb_guard = HUB.command_buffers.write();
let cmb = cmb_guard.get_mut(pass.cmb_id.value);

View File

@ -1,7 +1,6 @@
use hal;
use {Color, Extent3d, binding_model, command, pipeline, resource};
use {binding_model, command, pipeline, resource, Color, Extent3d};
pub fn map_buffer_usage(
usage: resource::BufferUsageFlags,
@ -42,7 +41,8 @@ pub fn map_buffer_usage(
}
pub fn map_texture_usage(
usage: resource::TextureUsageFlags, aspects: hal::format::Aspects
usage: resource::TextureUsageFlags,
aspects: hal::format::Aspects,
) -> hal::image::Usage {
use hal::image::Usage as U;
use resource::TextureUsageFlags as W;
@ -72,9 +72,7 @@ pub fn map_texture_usage(
value
}
pub fn map_binding_type(
binding_ty: binding_model::BindingType,
) -> hal::pso::DescriptorType {
pub fn map_binding_type(binding_ty: binding_model::BindingType) -> hal::pso::DescriptorType {
use binding_model::BindingType::*;
use hal::pso::DescriptorType as H;
match binding_ty {
@ -104,9 +102,7 @@ pub fn map_shader_stage_flags(
value
}
pub fn map_primitive_topology(
primitive_topology: pipeline::PrimitiveTopology,
) -> hal::Primitive {
pub fn map_primitive_topology(primitive_topology: pipeline::PrimitiveTopology) -> hal::Primitive {
use hal::Primitive as H;
use pipeline::PrimitiveTopology::*;
match primitive_topology {
@ -134,8 +130,8 @@ pub fn map_blend_state_descriptor(
}
fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMask {
use pipeline::ColorWriteFlags as F;
use hal::pso::ColorMask as H;
use pipeline::ColorWriteFlags as F;
let mut value = H::empty();
if flags.contains(F::RED) {
@ -276,7 +272,11 @@ fn checked_u32_as_u16(value: u32) -> u16 {
pub fn map_texture_dimension_size(
dimension: resource::TextureDimension,
Extent3d { width, height, depth }: Extent3d,
Extent3d {
width,
height,
depth,
}: Extent3d,
) -> hal::image::Kind {
use hal::image::Kind as H;
use resource::TextureDimension::*;
@ -305,11 +305,9 @@ pub fn map_texture_view_dimension(
}
}
pub fn map_texture_aspect_flags(
aspect: resource::TextureAspectFlags
) -> hal::format::Aspects {
use resource::TextureAspectFlags as Taf;
pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::format::Aspects {
use hal::format::Aspects;
use resource::TextureAspectFlags as Taf;
let mut flags = Aspects::empty();
if aspect.contains(Taf::COLOR) {
@ -324,9 +322,7 @@ pub fn map_texture_aspect_flags(
flags
}
pub fn map_buffer_state(
usage: resource::BufferUsageFlags,
) -> hal::buffer::State {
pub fn map_buffer_state(usage: resource::BufferUsageFlags) -> hal::buffer::State {
use hal::buffer::Access as A;
use resource::BufferUsageFlags as W;
@ -386,13 +382,20 @@ pub fn map_texture_state(
}
if usage.contains(W::OUTPUT_ATTACHMENT) {
//TODO: read-only attachments
access |= if is_color { A::COLOR_ATTACHMENT_WRITE } else { A::DEPTH_STENCIL_ATTACHMENT_WRITE };
access |= if is_color {
A::COLOR_ATTACHMENT_WRITE
} else {
A::DEPTH_STENCIL_ATTACHMENT_WRITE
};
}
(access, layout)
}
pub fn map_load_store_ops(load: command::LoadOp, store: command::StoreOp) -> hal::pass::AttachmentOps {
pub fn map_load_store_ops(
load: command::LoadOp,
store: command::StoreOp,
) -> hal::pass::AttachmentOps {
hal::pass::AttachmentOps {
load: match load {
command::LoadOp::Clear => hal::pass::AttachmentLoadOp::Clear,

View File

@ -1,12 +1,10 @@
use {back, binding_model, command, conv, pipeline, resource};
use registry::{HUB, Items};
use registry::{Items, HUB};
use track::{BufferTracker, TextureTracker};
use {back, binding_model, command, conv, pipeline, resource};
use {
CommandBuffer, LifeGuard, RefCount, Stored, SubmissionIndex, WeaklyStored,
TextureUsageFlags,
BindGroupLayoutId, BlendStateId, BufferId, CommandBufferId, DepthStencilStateId,
DeviceId, PipelineLayoutId, QueueId, RenderPipelineId, ShaderModuleId,
TextureId, TextureViewId,
BindGroupLayoutId, BlendStateId, BufferId, CommandBuffer, CommandBufferId, DepthStencilStateId,
DeviceId, LifeGuard, PipelineLayoutId, QueueId, RefCount, RenderPipelineId, ShaderModuleId,
Stored, SubmissionIndex, TextureId, TextureUsageFlags, TextureViewId, WeaklyStored,
};
use hal::command::RawCommandBuffer;
@ -14,13 +12,12 @@ use hal::queue::RawCommandQueue;
use hal::{self, Device as _Device};
//use rendy_memory::{allocator, Config, Heaps};
use std::{ffi, slice};
use std::collections::hash_map::{Entry, HashMap};
use std::{ffi, slice};
use parking_lot::Mutex;
use std::sync::atomic::Ordering;
#[derive(Hash, PartialEq)]
pub(crate) struct RenderPassKey {
pub attachments: Vec<hal::pass::Attachment>,
@ -66,16 +63,16 @@ unsafe impl<B: hal::Backend> Sync for DestroyedResources<B> {}
impl<B: hal::Backend> DestroyedResources<B> {
fn add(&mut self, resource_id: ResourceId, life_guard: &LifeGuard) {
self.referenced.push((resource_id, life_guard.ref_count.clone()));
self.referenced
.push((resource_id, life_guard.ref_count.clone()));
}
fn triage_referenced<Gb, Gt>(
&mut self, buffer_guard: &mut Gb, texture_guard: &mut Gt,
) where
fn triage_referenced<Gb, Gt>(&mut self, buffer_guard: &mut Gb, texture_guard: &mut Gt)
where
Gb: Items<resource::Buffer<B>>,
Gt: Items<resource::Texture<B>>,
{
for i in (0 .. self.referenced.len()).rev() {
for i in (0..self.referenced.len()).rev() {
// one in resource itself, and one here in this list
let num_refs = self.referenced[i].1.load();
if num_refs <= 2 {
@ -93,7 +90,8 @@ impl<B: hal::Backend> DestroyedResources<B> {
(si, Resource::Texture(tex))
}
};
match self.active
match self
.active
.iter_mut()
.find(|af| af.submission_index == submit_index)
{
@ -105,7 +103,7 @@ impl<B: hal::Backend> DestroyedResources<B> {
}
fn cleanup(&mut self, raw: &B::Device) {
for i in (0 .. self.active.len()).rev() {
for i in (0..self.active.len()).rev() {
if unsafe { raw.get_fence_status(&self.active[i].fence) }.unwrap() {
let af = self.active.swap_remove(i);
self.free.extend(af.resources);
@ -193,7 +191,6 @@ pub(crate) struct ShaderModule<B: hal::Backend> {
pub raw: B::ShaderModule,
}
#[no_mangle]
pub extern "C" fn wgpu_device_create_texture(
device_id: DeviceId,
@ -205,9 +202,8 @@ pub extern "C" fn wgpu_device_create_texture(
let usage = conv::map_texture_usage(desc.usage, aspects);
let device_guard = HUB.devices.read();
let device = &device_guard.get(device_id);
let mut image_unbound = unsafe { device
.raw
.create_image(
let mut image_unbound = unsafe {
device.raw.create_image(
kind,
1, // TODO: mips
format,
@ -215,57 +211,59 @@ pub extern "C" fn wgpu_device_create_texture(
usage,
hal::image::ViewCapabilities::empty(), // TODO: format, 2d array, cube
)
}.unwrap();
}
.unwrap();
let image_req = unsafe { device.raw.get_image_requirements(&image_unbound) };
let device_type = device
.mem_props
.memory_types
.iter()
.enumerate()
.position(|(id, memory_type)| { // TODO
.position(|(id, memory_type)| {
// TODO
image_req.type_mask & (1 << id) != 0
&& memory_type.properties.contains(hal::memory::Properties::DEVICE_LOCAL)
&& memory_type
.properties
.contains(hal::memory::Properties::DEVICE_LOCAL)
})
.unwrap()
.into();
// TODO: allocate with rendy
let image_memory = unsafe{
device.raw.allocate_memory(device_type, image_req.size)
}.unwrap();
let image_memory = unsafe { device.raw.allocate_memory(device_type, image_req.size) }.unwrap();
unsafe {
device
.raw
.bind_image_memory(&image_memory, 0, &mut image_unbound)
}.unwrap();
}
.unwrap();
let bound_image = image_unbound; //TODO: Maybe call this image the same way in the first place
let full_range = hal::image::SubresourceRange {
aspects,
levels: 0 .. 1, //TODO: mips
layers: 0 .. 1, //TODO
levels: 0..1, //TODO: mips
layers: 0..1, //TODO
};
let life_guard = LifeGuard::new();
let ref_count = life_guard.ref_count.clone();
let id = HUB.textures
.write()
.register(resource::Texture {
raw: bound_image,
device_id: Stored {
value: device_id,
ref_count: device.life_guard.ref_count.clone(),
},
kind,
format: desc.format,
full_range,
life_guard,
});
let query = device.texture_tracker
.lock()
.query(
&Stored { value: id, ref_count },
TextureUsageFlags::WRITE_ALL,
);
let id = HUB.textures.write().register(resource::Texture {
raw: bound_image,
device_id: Stored {
value: device_id,
ref_count: device.life_guard.ref_count.clone(),
},
kind,
format: desc.format,
full_range,
life_guard,
});
let query = device.texture_tracker.lock().query(
&Stored {
value: id,
ref_count,
},
TextureUsageFlags::WRITE_ALL,
);
assert!(query.initialized);
id
@ -279,42 +277,42 @@ pub extern "C" fn wgpu_texture_create_texture_view(
let texture_guard = HUB.textures.read();
let texture = texture_guard.get(texture_id);
let raw = unsafe { HUB.devices
.read()
.get(texture.device_id.value)
.raw
.create_image_view(
&texture.raw,
conv::map_texture_view_dimension(desc.dimension),
conv::map_texture_format(desc.format),
hal::format::Swizzle::NO,
hal::image::SubresourceRange {
aspects: conv::map_texture_aspect_flags(desc.aspect),
levels: desc.base_mip_level as u8 .. (desc.base_mip_level + desc.level_count) as u8,
layers: desc.base_array_layer as u16 .. (desc.base_array_layer + desc.array_count) as u16,
},
)
}.unwrap();
let raw = unsafe {
HUB.devices
.read()
.get(texture.device_id.value)
.raw
.create_image_view(
&texture.raw,
conv::map_texture_view_dimension(desc.dimension),
conv::map_texture_format(desc.format),
hal::format::Swizzle::NO,
hal::image::SubresourceRange {
aspects: conv::map_texture_aspect_flags(desc.aspect),
levels: desc.base_mip_level as u8
..(desc.base_mip_level + desc.level_count) as u8,
layers: desc.base_array_layer as u16
..(desc.base_array_layer + desc.array_count) as u16,
},
)
}
.unwrap();
HUB.texture_views
.write()
.register(resource::TextureView {
raw,
texture_id: Stored {
value: texture_id,
ref_count: texture.life_guard.ref_count.clone(),
},
format: texture.format,
extent: texture.kind.extent(),
samples: texture.kind.num_samples(),
life_guard: LifeGuard::new(),
})
HUB.texture_views.write().register(resource::TextureView {
raw,
texture_id: Stored {
value: texture_id,
ref_count: texture.life_guard.ref_count.clone(),
},
format: texture.format,
extent: texture.kind.extent(),
samples: texture.kind.num_samples(),
life_guard: LifeGuard::new(),
})
}
#[no_mangle]
pub extern "C" fn wgpu_texture_create_default_texture_view(
texture_id: TextureId,
) -> TextureViewId {
pub extern "C" fn wgpu_texture_create_default_texture_view(texture_id: TextureId) -> TextureViewId {
let texture_guard = HUB.textures.read();
let texture = texture_guard.get(texture_id);
@ -324,38 +322,36 @@ pub extern "C" fn wgpu_texture_create_default_texture_view(
hal::image::Kind::D3(..) => hal::image::ViewKind::D3,
};
let raw = unsafe { HUB.devices
.read()
.get(texture.device_id.value)
.raw
.create_image_view(
&texture.raw,
view_kind,
conv::map_texture_format(texture.format),
hal::format::Swizzle::NO,
texture.full_range.clone(),
)
}.unwrap();
let raw = unsafe {
HUB.devices
.read()
.get(texture.device_id.value)
.raw
.create_image_view(
&texture.raw,
view_kind,
conv::map_texture_format(texture.format),
hal::format::Swizzle::NO,
texture.full_range.clone(),
)
}
.unwrap();
HUB.texture_views
.write()
.register(resource::TextureView {
raw,
texture_id: Stored {
value: texture_id,
ref_count: texture.life_guard.ref_count.clone(),
},
format: texture.format,
extent: texture.kind.extent(),
samples: texture.kind.num_samples(),
life_guard: LifeGuard::new(),
})
HUB.texture_views.write().register(resource::TextureView {
raw,
texture_id: Stored {
value: texture_id,
ref_count: texture.life_guard.ref_count.clone(),
},
format: texture.format,
extent: texture.kind.extent(),
samples: texture.kind.num_samples(),
life_guard: LifeGuard::new(),
})
}
#[no_mangle]
pub extern "C" fn wgpu_texture_destroy(
texture_id: TextureId,
) {
pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) {
let texture_guard = HUB.textures.read();
let texture = texture_guard.get(texture_id);
let device_guard = HUB.devices.write();
@ -367,9 +363,7 @@ pub extern "C" fn wgpu_texture_destroy(
}
#[no_mangle]
pub extern "C" fn wgpu_texture_view_destroy(
_texture_view_id: TextureViewId,
) {
pub extern "C" fn wgpu_texture_view_destroy(_texture_view_id: TextureViewId) {
unimplemented!()
}
@ -380,23 +374,25 @@ pub extern "C" fn wgpu_device_create_bind_group_layout(
) -> BindGroupLayoutId {
let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length) };
let descriptor_set_layout = unsafe { HUB.devices
.read()
.get(device_id)
.raw
.create_descriptor_set_layout(
bindings.iter().map(|binding| {
hal::pso::DescriptorSetLayoutBinding {
binding: binding.binding,
ty: conv::map_binding_type(binding.ty),
count: bindings.len(),
stage_flags: conv::map_shader_stage_flags(binding.visibility),
immutable_samplers: false, // TODO
}
}),
&[],
)
}.unwrap();
let descriptor_set_layout = unsafe {
HUB.devices
.read()
.get(device_id)
.raw
.create_descriptor_set_layout(
bindings.iter().map(|binding| {
hal::pso::DescriptorSetLayoutBinding {
binding: binding.binding,
ty: conv::map_binding_type(binding.ty),
count: bindings.len(),
stage_flags: conv::map_shader_stage_flags(binding.visibility),
immutable_samplers: false, // TODO
}
}),
&[],
)
}
.unwrap();
HUB.bind_group_layouts
.write()
@ -410,21 +406,22 @@ pub extern "C" fn wgpu_device_create_pipeline_layout(
device_id: DeviceId,
desc: &binding_model::PipelineLayoutDescriptor,
) -> PipelineLayoutId {
let bind_group_layouts = unsafe {
slice::from_raw_parts(desc.bind_group_layouts, desc.bind_group_layouts_length)
};
let bind_group_layouts =
unsafe { slice::from_raw_parts(desc.bind_group_layouts, desc.bind_group_layouts_length) };
let bind_group_layout_guard = HUB.bind_group_layouts.read();
let descriptor_set_layouts = bind_group_layouts
.iter()
.map(|&id| &bind_group_layout_guard.get(id).raw);
// TODO: push constants
let pipeline_layout = unsafe { HUB.devices
.read()
.get(device_id)
.raw
.create_pipeline_layout(descriptor_set_layouts, &[])
}.unwrap();
let pipeline_layout = unsafe {
HUB.devices
.read()
.get(device_id)
.raw
.create_pipeline_layout(descriptor_set_layouts, &[])
}
.unwrap();
HUB.pipeline_layouts
.write()
@ -438,11 +435,9 @@ pub extern "C" fn wgpu_device_create_blend_state(
_device_id: DeviceId,
desc: &pipeline::BlendStateDescriptor,
) -> BlendStateId {
HUB.blend_states
.write()
.register(pipeline::BlendState {
raw: conv::map_blend_state_descriptor(desc),
})
HUB.blend_states.write().register(pipeline::BlendState {
raw: conv::map_blend_state_descriptor(desc),
})
}
#[no_mangle]
@ -462,15 +457,15 @@ pub extern "C" fn wgpu_device_create_shader_module(
device_id: DeviceId,
desc: &pipeline::ShaderModuleDescriptor,
) -> ShaderModuleId {
let spv = unsafe {
slice::from_raw_parts(desc.code.bytes, desc.code.length)
};
let shader = unsafe { HUB.devices
.read()
.get(device_id)
.raw
.create_shader_module(spv)
}.unwrap();
let spv = unsafe { slice::from_raw_parts(desc.code.bytes, desc.code.length) };
let shader = unsafe {
HUB.devices
.read()
.get(device_id)
.raw
.create_shader_module(spv)
}
.unwrap();
HUB.shader_modules
.write()
@ -516,13 +511,15 @@ pub extern "C" fn wgpu_queue_submit(
let mut texture_tracker = device.texture_tracker.lock();
let mut command_buffer_guard = HUB.command_buffers.write();
let command_buffer_ids = unsafe {
slice::from_raw_parts(command_buffer_ptr, command_buffer_count)
};
let command_buffer_ids =
unsafe { slice::from_raw_parts(command_buffer_ptr, command_buffer_count) };
let mut buffer_guard = HUB.buffers.write();
let mut texture_guard = HUB.textures.write();
let old_submit_index = device.life_guard.submission_index.fetch_add(1, Ordering::Relaxed);
let old_submit_index = device
.life_guard
.submission_index
.fetch_add(1, Ordering::Relaxed);
//TODO: if multiple command buffers are submitted, we can re-use the last
// native command buffer of the previous chain instead of always creating
@ -533,10 +530,18 @@ pub extern "C" fn wgpu_queue_submit(
let comb = command_buffer_guard.get_mut(cmb_id);
// update submission IDs
for id in comb.buffer_tracker.used() {
buffer_guard.get(id).life_guard.submission_index.store(old_submit_index, Ordering::Release);
buffer_guard
.get(id)
.life_guard
.submission_index
.store(old_submit_index, Ordering::Release);
}
for id in comb.texture_tracker.used() {
texture_guard.get(id).life_guard.submission_index.store(old_submit_index, Ordering::Release);
texture_guard
.get(id)
.life_guard
.submission_index
.store(old_submit_index, Ordering::Release);
}
// execute resource transitions
@ -555,28 +560,27 @@ pub extern "C" fn wgpu_queue_submit(
&*buffer_guard,
&*texture_guard,
);
unsafe { transit.finish(); }
unsafe {
transit.finish();
}
comb.raw.insert(0, transit);
unsafe {
comb.raw
.last_mut()
.unwrap()
.finish();
comb.raw.last_mut().unwrap().finish();
}
}
// now prepare the GPU submission
let fence = device.raw.create_fence(false).unwrap();
{
let submission = hal::queue::Submission::<_, _, &[<back::Backend as hal::Backend>::Semaphore]> { //TODO: may `OneShot` be enough?
command_buffers: command_buffer_ids
.iter()
.flat_map(|&cmb_id| {
&command_buffer_guard.get(cmb_id).raw
}),
wait_semaphores: Vec::new(),
signal_semaphores: &[],
};
let submission =
hal::queue::Submission::<_, _, &[<back::Backend as hal::Backend>::Semaphore]> {
//TODO: may `OneShot` be enough?
command_buffers: command_buffer_ids
.iter()
.flat_map(|&cmb_id| &command_buffer_guard.get(cmb_id).raw),
wait_semaphores: Vec::new(),
signal_semaphores: &[],
};
unsafe {
device.queue_group.queues[0]
.as_raw_mut()
@ -632,22 +636,21 @@ pub extern "C" fn wgpu_device_create_render_pipeline(
desc.attachments_state.color_attachments_length,
)
};
let depth_stencil_attachment = unsafe {
desc.attachments_state.depth_stencil_attachment.as_ref()
};
let depth_stencil_attachment =
unsafe { desc.attachments_state.depth_stencil_attachment.as_ref() };
let color_keys = color_attachments.iter().map(|at| hal::pass::Attachment {
format: Some(conv::map_texture_format(at.format)),
samples: at.samples as u8,
ops: op_keep,
stencil_ops: hal::pass::AttachmentOps::DONT_CARE,
layouts: hal::image::Layout::General .. hal::image::Layout::General,
layouts: hal::image::Layout::General..hal::image::Layout::General,
});
let depth_stencil_key = depth_stencil_attachment.map(|at| hal::pass::Attachment {
format: Some(conv::map_texture_format(at.format)),
samples: at.samples as u8,
ops: op_keep,
stencil_ops: op_keep,
layouts: hal::image::Layout::General .. hal::image::Layout::General,
layouts: hal::image::Layout::General..hal::image::Layout::General,
});
RenderPassKey {
attachments: color_keys.chain(depth_stencil_key).collect(),
@ -664,10 +667,13 @@ pub extern "C" fn wgpu_device_create_render_pipeline(
(2, hal::image::Layout::ColorAttachmentOptimal),
(3, hal::image::Layout::ColorAttachmentOptimal),
];
let depth_id = (desc.attachments_state.color_attachments_length, hal::image::Layout::DepthStencilAttachmentOptimal);
let depth_id = (
desc.attachments_state.color_attachments_length,
hal::image::Layout::DepthStencilAttachmentOptimal,
);
let subpass = hal::pass::SubpassDesc {
colors: &color_ids[.. desc.attachments_state.color_attachments_length],
colors: &color_ids[..desc.attachments_state.color_attachments_length],
depth_stencil: if desc.attachments_state.depth_stencil_attachment.is_null() {
None
} else {
@ -678,11 +684,12 @@ pub extern "C" fn wgpu_device_create_render_pipeline(
preserves: &[],
};
let pass = unsafe { device.raw.create_render_pass(
&e.key().attachments,
&[subpass],
&[],
)}.unwrap();
let pass = unsafe {
device
.raw
.create_render_pass(&e.key().attachments, &[subpass], &[])
}
.unwrap();
e.insert(pass)
}
};
@ -745,10 +752,11 @@ pub extern "C" fn wgpu_device_create_render_pipeline(
};
let blend_state_guard = HUB.blend_states.read();
let blend_states = unsafe { slice::from_raw_parts(desc.blend_states, desc.blend_states_length) }
.iter()
.map(|id| blend_state_guard.get(id.clone()).raw)
.collect();
let blend_states =
unsafe { slice::from_raw_parts(desc.blend_states, desc.blend_states_length) }
.iter()
.map(|id| blend_state_guard.get(id.clone()).raw)
.collect();
let blender = hal::pso::BlendDesc {
logic_op: None, // TODO
@ -809,9 +817,7 @@ pub extern "C" fn wgpu_device_create_render_pipeline(
};
// TODO: cache
let pipeline = unsafe { device.raw
.create_graphics_pipeline(&pipeline_desc, None)
}.unwrap();
let pipeline = unsafe { device.raw.create_graphics_pipeline(&pipeline_desc, None) }.unwrap();
HUB.render_pipelines
.write()

View File

@ -1,6 +1,6 @@
use hal::{self, Instance as _Instance, PhysicalDevice as _PhysicalDevice};
use registry::{HUB, Items};
use registry::{Items, HUB};
use {AdapterId, Device, DeviceId, InstanceId};
#[repr(C)]
@ -67,9 +67,7 @@ pub extern "C" fn wgpu_instance_get_adapter(
PowerPreference::LowPower => low.or(high),
PowerPreference::HighPerformance | PowerPreference::Default => high.or(low),
};
HUB.adapters
.write()
.register(some.or(other).unwrap())
HUB.adapters.write().register(some.or(other).unwrap())
}
#[no_mangle]

View File

@ -45,7 +45,6 @@ pub use registry::Id;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
type SubmissionIndex = usize;
#[derive(Debug)]
@ -109,7 +108,6 @@ struct WeaklyStored<T>(T);
unsafe impl<T> Send for WeaklyStored<T> {}
unsafe impl<T> Sync for WeaklyStored<T> {}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Color {
@ -120,12 +118,42 @@ pub struct Color {
}
impl Color {
pub const TRANSPARENT : Self = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
pub const BLACK : Self = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
pub const WHITE : Self = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
pub const RED : Self = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
pub const GREEN : Self = Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 };
pub const BLUE : Self = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
pub const TRANSPARENT: Self = Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
};
pub const BLACK: Self = Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 1.0,
};
pub const WHITE: Self = Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
};
pub const RED: Self = Color {
r: 1.0,
g: 0.0,
b: 0.0,
a: 1.0,
};
pub const GREEN: Self = Color {
r: 0.0,
g: 1.0,
b: 0.0,
a: 1.0,
};
pub const BLUE: Self = Color {
r: 0.0,
g: 0.0,
b: 1.0,
a: 1.0,
};
}
#[repr(C)]

View File

@ -1,10 +1,7 @@
use hal;
use resource;
use {
BlendStateId, ByteArray, DepthStencilStateId, PipelineLayoutId,
ShaderModuleId,
};
use {BlendStateId, ByteArray, DepthStencilStateId, PipelineLayoutId, ShaderModuleId};
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]

View File

@ -1,7 +1,6 @@
use std::marker::PhantomData;
use std::os::raw::c_void;
pub type Id = *mut c_void;
pub struct Items<T> {

View File

@ -3,14 +3,12 @@ use std::sync::Arc;
use parking_lot::RwLock;
use {
AdapterHandle, BindGroupLayoutHandle, BindGroupHandle,
BlendStateHandle, CommandBufferHandle, DepthStencilStateHandle, DeviceHandle, InstanceHandle,
RenderPassHandle, ComputePassHandle,
PipelineLayoutHandle, RenderPipelineHandle, ComputePipelineHandle, ShaderModuleHandle,
BufferHandle, TextureHandle, TextureViewHandle,
AdapterHandle, BindGroupHandle, BindGroupLayoutHandle, BlendStateHandle, BufferHandle,
CommandBufferHandle, ComputePassHandle, ComputePipelineHandle, DepthStencilStateHandle,
DeviceHandle, InstanceHandle, PipelineLayoutHandle, RenderPassHandle, RenderPipelineHandle,
ShaderModuleHandle, TextureHandle, TextureViewHandle,
};
#[cfg(not(feature = "remote"))]
mod local;
#[cfg(feature = "remote")]
@ -21,7 +19,6 @@ pub use self::local::{Id, Items as ConcreteItems};
#[cfg(feature = "remote")]
pub use self::remote::{Id, Items as ConcreteItems};
pub trait Items<T>: Default {
fn register(&mut self, handle: T) -> Id;
fn get(&self, id: Id) -> &T;

View File

@ -1,6 +1,5 @@
use hal::backend::FastHashMap;
pub type Id = u32;
pub struct Items<T> {

View File

@ -1,11 +1,7 @@
use {
Extent3d, LifeGuard, Stored,
DeviceId, TextureId,
};
use {DeviceId, Extent3d, LifeGuard, Stored, TextureId};
use hal;
bitflags! {
#[repr(transparent)]
pub struct BufferUsageFlags: u32 {
@ -36,7 +32,6 @@ pub(crate) struct Buffer<B: hal::Backend> {
// TODO: mapping, unmap()
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum TextureDimension {
@ -86,7 +81,6 @@ pub(crate) struct Texture<B: hal::Backend> {
pub life_guard: LifeGuard,
}
bitflags! {
#[repr(transparent)]
pub struct TextureAspectFlags: u32 {
@ -127,7 +121,6 @@ pub(crate) struct TextureView<B: hal::Backend> {
pub life_guard: LifeGuard,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum AddressMode {

View File

@ -1,12 +1,11 @@
use {RefCount, Stored, WeaklyStored, BufferId, TextureId};
use resource::{BufferUsageFlags, TextureUsageFlags};
use {BufferId, RefCount, Stored, TextureId, WeaklyStored};
use std::collections::hash_map::{Entry, HashMap};
use std::hash::Hash;
use std::mem;
use std::ops::{BitOr, Range};
#[derive(Clone, Debug, PartialEq)]
#[allow(unused)]
pub enum Tracktion<T> {
@ -29,7 +28,6 @@ bitflags! {
}
}
pub trait GenericUsage {
fn is_exclusive(&self) -> bool;
}
@ -61,10 +59,7 @@ pub struct Tracker<I, U> {
pub type BufferTracker = Tracker<BufferId, BufferUsageFlags>;
pub type TextureTracker = Tracker<TextureId, TextureUsageFlags>;
impl<
I: Clone + Hash + Eq,
U: Copy + GenericUsage + BitOr<Output = U> + PartialEq,
> Tracker<I, U> {
impl<I: Clone + Hash + Eq, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I, U> {
pub(crate) fn new() -> Self {
Tracker {
map: HashMap::new(),
@ -72,9 +67,7 @@ impl<
}
/// Get the last usage on a resource.
pub(crate) fn query(
&mut self, stored: &Stored<I>, default: U
) -> Query<U> {
pub(crate) fn query(&mut self, stored: &Stored<I>, default: U) -> Query<U> {
match self.map.entry(WeaklyStored(stored.value.clone())) {
Entry::Vacant(e) => {
e.insert(Track {
@ -87,18 +80,20 @@ impl<
initialized: true,
}
}
Entry::Occupied(e) => {
Query {
usage: e.get().last,
initialized: false,
}
}
Entry::Occupied(e) => Query {
usage: e.get().last,
initialized: false,
},
}
}
/// Transit a specified resource into a different usage.
pub(crate) fn transit(
&mut self, id: I, ref_count: &RefCount, usage: U, permit: TrackPermit
&mut self,
id: I,
ref_count: &RefCount,
usage: U,
permit: TrackPermit,
) -> Result<Tracktion<U>, U> {
match self.map.entry(WeaklyStored(id)) {
Entry::Vacant(e) => {
@ -127,12 +122,9 @@ impl<
}
/// Consume another tacker, adding it's transitions to `self`.
pub fn consume<'a>(
&'a mut self, other: &'a Self
) -> impl 'a + Iterator<Item = (I, Range<U>)> {
other.map
.iter()
.flat_map(move |(id, new)| match self.map.entry(WeaklyStored(id.0.clone())) {
pub fn consume<'a>(&'a mut self, other: &'a Self) -> impl 'a + Iterator<Item = (I, Range<U>)> {
other.map.iter().flat_map(move |(id, new)| {
match self.map.entry(WeaklyStored(id.0.clone())) {
Entry::Vacant(e) => {
e.insert(new.clone());
None
@ -142,10 +134,11 @@ impl<
if old == new.init {
None
} else {
Some((id.0.clone(), old .. new.last))
Some((id.0.clone(), old..new.last))
}
}
})
}
})
}
/// Return an iterator over used resources keys.

View File

@ -1,5 +1,5 @@
extern crate wgpu_native as wgn;
extern crate arrayvec;
extern crate wgpu_native as wgn;
use arrayvec::ArrayVec;
@ -7,16 +7,14 @@ use std::ffi::CString;
use std::ptr;
pub use wgn::{
AdapterDescriptor, Color, CommandBufferDescriptor, DeviceDescriptor, Extensions, Extent3d,
Origin3d, PowerPreference, ShaderModuleDescriptor, ShaderStage, ShaderStageFlags,
BindGroupLayoutBinding, BindingType, TextureDimension, TextureDescriptor, TextureFormat,
TextureUsageFlags, TextureViewDescriptor,
PrimitiveTopology, BlendStateDescriptor, ColorWriteFlags, DepthStencilStateDescriptor,
RenderPassDescriptor, RenderPassColorAttachmentDescriptor, RenderPassDepthStencilAttachmentDescriptor,
Attachment, LoadOp, StoreOp,
AdapterDescriptor, Attachment, BindGroupLayoutBinding, BindingType, BlendStateDescriptor,
Color, ColorWriteFlags, CommandBufferDescriptor, DepthStencilStateDescriptor, DeviceDescriptor,
Extensions, Extent3d, LoadOp, Origin3d, PowerPreference, PrimitiveTopology,
RenderPassColorAttachmentDescriptor, RenderPassDepthStencilAttachmentDescriptor,
RenderPassDescriptor, ShaderModuleDescriptor, ShaderStage, ShaderStageFlags, StoreOp,
TextureDescriptor, TextureDimension, TextureFormat, TextureUsageFlags, TextureViewDescriptor,
};
pub struct Instance {
id: wgn::InstanceId,
}
@ -115,7 +113,6 @@ pub struct RenderPipelineDescriptor<'a> {
pub depth_stencil_state: &'a DepthStencilState,
}
impl Instance {
pub fn new() -> Self {
Instance {
@ -165,24 +162,31 @@ impl Device {
pub fn create_bind_group_layout(&self, desc: &BindGroupLayoutDescriptor) -> BindGroupLayout {
BindGroupLayout {
id: wgn::wgpu_device_create_bind_group_layout(self.id, &wgn::BindGroupLayoutDescriptor {
bindings: desc.bindings.as_ptr(),
bindings_length: desc.bindings.len(),
}),
id: wgn::wgpu_device_create_bind_group_layout(
self.id,
&wgn::BindGroupLayoutDescriptor {
bindings: desc.bindings.as_ptr(),
bindings_length: desc.bindings.len(),
},
),
}
}
pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor) -> PipelineLayout {
//TODO: avoid allocation here
let temp_layouts = desc.bind_group_layouts
let temp_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.id)
.collect::<Vec<_>>();
PipelineLayout {
id: wgn::wgpu_device_create_pipeline_layout(self.id, &wgn::PipelineLayoutDescriptor {
bind_group_layouts: temp_layouts.as_ptr(),
bind_group_layouts_length: temp_layouts.len(),
}),
id: wgn::wgpu_device_create_pipeline_layout(
self.id,
&wgn::PipelineLayoutDescriptor {
bind_group_layouts: temp_layouts.as_ptr(),
bind_group_layouts_length: temp_layouts.len(),
},
),
}
}
@ -192,18 +196,23 @@ impl Device {
}
}
pub fn create_depth_stencil_state(&self, desc: &DepthStencilStateDescriptor) -> DepthStencilState {
pub fn create_depth_stencil_state(
&self,
desc: &DepthStencilStateDescriptor,
) -> DepthStencilState {
DepthStencilState {
id: wgn::wgpu_device_create_depth_stencil_state(self.id, desc),
}
}
pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor) -> RenderPipeline {
let entry_points = desc.stages
let entry_points = desc
.stages
.iter()
.map(|ps| CString::new(ps.entry_point).unwrap())
.collect::<ArrayVec<[_; 2]>>();
let stages = desc.stages
let stages = desc
.stages
.iter()
.zip(&entry_points)
.map(|(ps, ep_name)| wgn::PipelineStageDescriptor {
@ -213,26 +222,31 @@ impl Device {
})
.collect::<ArrayVec<[_; 2]>>();
let temp_blend_states = desc.blend_states
.iter()
.map(|bs| bs.id)
.collect::<Vec<_>>();
let temp_blend_states = desc.blend_states.iter().map(|bs| bs.id).collect::<Vec<_>>();
RenderPipeline {
id: wgn::wgpu_device_create_render_pipeline(self.id, &wgn::RenderPipelineDescriptor {
layout: desc.layout.id,
stages: stages.as_ptr(),
stages_length: stages.len(),
primitive_topology: desc.primitive_topology,
attachments_state: wgn::AttachmentsState {
color_attachments: desc.attachments_state.color_attachments.as_ptr(),
color_attachments_length: desc.attachments_state.color_attachments.len(),
depth_stencil_attachment: desc.attachments_state.depth_stencil_attachment.as_ref().map(|at| at as *const _).unwrap_or(ptr::null()),
id: wgn::wgpu_device_create_render_pipeline(
self.id,
&wgn::RenderPipelineDescriptor {
layout: desc.layout.id,
stages: stages.as_ptr(),
stages_length: stages.len(),
primitive_topology: desc.primitive_topology,
attachments_state: wgn::AttachmentsState {
color_attachments: desc.attachments_state.color_attachments.as_ptr(),
color_attachments_length: desc.attachments_state.color_attachments.len(),
depth_stencil_attachment: desc
.attachments_state
.depth_stencil_attachment
.as_ref()
.map(|at| at as *const _)
.unwrap_or(ptr::null()),
},
blend_states: temp_blend_states.as_ptr(),
blend_states_length: temp_blend_states.len(),
depth_stencil_state: desc.depth_stencil_state.id,
},
blend_states: temp_blend_states.as_ptr(),
blend_states_length: temp_blend_states.len(),
depth_stencil_state: desc.depth_stencil_state.id,
}),
),
}
}
@ -259,7 +273,8 @@ impl Texture {
impl CommandBuffer {
pub fn begin_render_pass(&mut self, desc: &RenderPassDescriptor<&TextureView>) -> RenderPass {
let colors = desc.color_attachments
let colors = desc
.color_attachments
.iter()
.map(|ca| RenderPassColorAttachmentDescriptor {
attachment: ca.attachment.id,
@ -269,9 +284,8 @@ impl CommandBuffer {
})
.collect::<ArrayVec<[_; 4]>>();
let depth_stencil = desc.depth_stencil_attachment
.as_ref()
.map(|dsa| RenderPassDepthStencilAttachmentDescriptor {
let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
RenderPassDepthStencilAttachmentDescriptor {
attachment: dsa.attachment.id,
depth_load_op: dsa.depth_load_op,
depth_store_op: dsa.depth_store_op,
@ -279,13 +293,17 @@ impl CommandBuffer {
stencil_load_op: dsa.stencil_load_op,
stencil_store_op: dsa.stencil_store_op,
clear_stencil: dsa.clear_stencil,
});
}
});
RenderPass {
id: wgn::wgpu_command_buffer_begin_render_pass(self.id, RenderPassDescriptor {
color_attachments: &colors,
depth_stencil_attachment: depth_stencil,
}),
id: wgn::wgpu_command_buffer_begin_render_pass(
self.id,
RenderPassDescriptor {
color_attachments: &colors,
depth_stencil_attachment: depth_stencil,
},
),
parent: self,
}
}