From 0a30cf4b4623f3a701c0a9ee3826ec13bfeb3f6f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 24 Mar 2020 19:18:42 -0400 Subject: [PATCH] Recycled identity management (#533) --- wgpu-core/src/command/compute.rs | 4 +- wgpu-core/src/command/mod.rs | 4 +- wgpu-core/src/command/render.rs | 4 +- wgpu-core/src/command/transfer.rs | 4 +- wgpu-core/src/device/life.rs | 32 ++--- wgpu-core/src/device/mod.rs | 120 +++++++----------- wgpu-core/src/hub.rs | 166 ++++++++++++++---------- wgpu-core/src/instance.rs | 12 +- wgpu-core/src/swap_chain.rs | 6 +- wgpu-native/src/lib.rs | 4 +- wgpu-remote/cbindgen.toml | 1 - wgpu-remote/src/identity.rs | 201 ++++++++++++++++++++++++++++++ wgpu-remote/src/lib.rs | 22 ++-- wgpu-remote/src/server.rs | 9 +- 14 files changed, 397 insertions(+), 192 deletions(-) create mode 100644 wgpu-remote/src/identity.rs diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 610294e15..29a355267 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -9,7 +9,7 @@ use crate::{ PhantomSlice, }, device::{all_buffer_stages, BIND_BUFFER_ALIGNMENT}, - hub::{GfxBackend, Global, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token}, id, }; @@ -56,7 +56,7 @@ pub struct ComputePassDescriptor { // Common routines between render/compute -impl Global { +impl Global { pub fn command_encoder_run_compute_pass( &self, encoder_id: id::CommandEncoderId, diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index a348c050c..16c740462 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -19,7 +19,7 @@ use crate::{ all_buffer_stages, all_image_stages, }, - hub::{GfxBackend, Global, Storage, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, id, resource::{Buffer, Texture}, track::TrackerSet, @@ -205,7 +205,7 @@ pub struct RawRenderTargets { pub depth_stencil: RenderPassDepthStencilAttachmentDescriptor, } -impl Global { +impl Global { pub fn command_encoder_finish( &self, encoder_id: id::CommandEncoderId, diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 3c9015168..ed7805ad1 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -18,7 +18,7 @@ use crate::{ MAX_VERTEX_BUFFERS, MAX_COLOR_TARGETS, }, - hub::{GfxBackend, Global, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token}, id, pipeline::PipelineFlags, resource::TextureViewInner, @@ -281,7 +281,7 @@ impl State { // Common routines between render/compute -impl Global { +impl Global { pub fn command_encoder_run_render_pass( &self, encoder_id: id::CommandEncoderId, diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index 040eb7b79..c38bb6690 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -5,7 +5,7 @@ use crate::{ conv, device::{all_buffer_stages, all_image_stages}, - hub::{GfxBackend, Global, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token}, id::{BufferId, CommandEncoderId, TextureId}, }; @@ -69,7 +69,7 @@ impl TextureCopyView { } } -impl Global { +impl Global { pub fn command_encoder_copy_buffer_to_buffer( &self, command_encoder_id: CommandEncoderId, diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index 2fb2717a6..de3f646a9 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{ - hub::{AllIdentityFilter, GfxBackend, Global, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token}, id, resource, track::TrackerSet, @@ -204,6 +204,7 @@ impl LifetimeTracker { fn wait_idle(&self, device: &B::Device) { if !self.active.is_empty() { + log::debug!("Waiting for IDLE..."); let status = unsafe { device.wait_for_fences( self.active.iter().map(|a| &a.fence), @@ -211,6 +212,7 @@ impl LifetimeTracker { CLEANUP_WAIT_MS * 1_000_000, ) }; + log::debug!("...Done"); assert_eq!(status, Ok(true), "GPU got stuck :("); } } @@ -268,9 +270,9 @@ impl LifetimeTracker { } impl LifetimeTracker { - pub(crate) fn triage_suspected( + pub(crate) fn triage_suspected( &mut self, - global: &Global, + global: &Global, trackers: &Mutex, token: &mut Token>, ) { @@ -282,7 +284,7 @@ impl LifetimeTracker { for id in self.suspected_resources.bind_groups.drain(..) { if trackers.bind_groups.remove_abandoned(id) { - hub.bind_groups.identity.free(id); + hub.bind_groups.free_id(id); let res = guard.remove(id).unwrap(); assert!(res.used.bind_groups.is_empty()); @@ -307,7 +309,7 @@ impl LifetimeTracker { for id in self.suspected_resources.texture_views.drain(..) { if trackers.views.remove_abandoned(id) { - hub.texture_views.identity.free(id); + hub.texture_views.free_id(id); let res = guard.remove(id).unwrap(); let raw = match res.inner { @@ -334,7 +336,7 @@ impl LifetimeTracker { for id in self.suspected_resources.textures.drain(..) { if trackers.textures.remove_abandoned(id) { - hub.textures.identity.free(id); + hub.textures.free_id(id); let res = guard.remove(id).unwrap(); let submit_index = res.life_guard.submission_index.load(Ordering::Acquire); @@ -353,7 +355,7 @@ impl LifetimeTracker { for id in self.suspected_resources.samplers.drain(..) { if trackers.samplers.remove_abandoned(id) { - hub.samplers.identity.free(id); + hub.samplers.free_id(id); let res = guard.remove(id).unwrap(); let submit_index = res.life_guard.submission_index.load(Ordering::Acquire); @@ -372,7 +374,7 @@ impl LifetimeTracker { for id in self.suspected_resources.buffers.drain(..) { if trackers.buffers.remove_abandoned(id) { - hub.buffers.identity.free(id); + hub.buffers.free_id(id); let res = guard.remove(id).unwrap(); let submit_index = res.life_guard.submission_index.load(Ordering::Acquire); @@ -386,8 +388,10 @@ impl LifetimeTracker { } } - pub(crate) fn triage_mapped( - &mut self, global: &Global, token: &mut Token> + pub(crate) fn triage_mapped( + &mut self, + global: &Global, + token: &mut Token>, ) { if self.mapped.is_empty() { return; @@ -414,9 +418,9 @@ impl LifetimeTracker { } } - pub(crate) fn triage_framebuffers( + pub(crate) fn triage_framebuffers( &mut self, - global: &Global, + global: &Global, framebuffers: &mut FastHashMap, token: &mut Token>, ) { @@ -477,9 +481,9 @@ impl LifetimeTracker { } } - pub(crate) fn handle_mapping( + pub(crate) fn handle_mapping( &mut self, - global: &Global, + global: &Global, raw: &B::Device, token: &mut Token>, ) -> Vec { diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index bfcfe91c3..8e62b9238 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -6,7 +6,7 @@ use crate::{ binding_model, command, conv, - hub::{AllIdentityFilter, GfxBackend, Global, IdentityFilter, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, id, pipeline, resource, @@ -271,9 +271,9 @@ impl Device { self.life_tracker.lock() } - fn maintain<'a, F: AllIdentityFilter>( + fn maintain<'a, G: GlobalIdentityHandlerFactory>( &'a self, - global: &Global, + global: &Global, force_wait: bool, token: &mut Token<'a, Self>, ) -> Vec { @@ -490,12 +490,12 @@ impl Device { } -impl> Global { +impl Global { pub fn device_create_buffer( &self, device_id: id::DeviceId, desc: &wgt::BufferDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::BufferId { let hub = B::hub(self); let mut token = Token::root(); @@ -525,7 +525,7 @@ impl> Global { &self, device_id: id::DeviceId, desc: &wgt::BufferDescriptor, - id_in: F::Input, + id_in: Input, ) -> (id::BufferId, *mut u8) { let hub = B::hub(self); let mut token = Token::root(); @@ -644,14 +644,12 @@ impl> Global { .lock_life(&mut token) .suspected_resources.buffers.push(buffer_id); } -} -impl> Global { pub fn device_create_texture( &self, device_id: id::DeviceId, desc: &wgt::TextureDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::TextureId { let hub = B::hub(self); let mut token = Token::root(); @@ -690,14 +688,12 @@ impl> Global { .lock_life(&mut token) .suspected_resources.textures.push(texture_id); } -} -impl> Global { pub fn texture_create_view( &self, texture_id: id::TextureId, desc: Option<&wgt::TextureViewDescriptor>, - id_in: F::Input, + id_in: Input, ) -> id::TextureViewId { let hub = B::hub(self); let mut token = Token::root(); @@ -801,14 +797,12 @@ impl> Global { .lock_life(&mut token) .suspected_resources.texture_views.push(texture_view_id); } -} -impl> Global { pub fn device_create_sampler( &self, device_id: id::DeviceId, desc: &wgt::SamplerDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::SamplerId { let hub = B::hub(self); let mut token = Token::root(); @@ -866,14 +860,12 @@ impl> Global { .lock_life(&mut token) .suspected_resources.samplers.push(sampler_id); } -} -impl> Global { pub fn device_create_bind_group_layout( &self, device_id: id::DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::BindGroupLayoutId { let mut token = Token::root(); let hub = B::hub(self); @@ -942,14 +934,12 @@ impl> Global { device_guard[bgl.device_id.value].raw.destroy_descriptor_set_layout(bgl.raw); } } -} -impl> Global { pub fn device_create_pipeline_layout( &self, device_id: id::DeviceId, desc: &binding_model::PipelineLayoutDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::PipelineLayoutId { let hub = B::hub(self); let mut token = Token::root(); @@ -998,14 +988,12 @@ impl> Global { device_guard[pipeline_layout.device_id.value].raw.destroy_pipeline_layout(pipeline_layout.raw); } } -} -impl> Global { pub fn device_create_bind_group( &self, device_id: id::DeviceId, desc: &binding_model::BindGroupDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::BindGroupId { let hub = B::hub(self); let mut token = Token::root(); @@ -1211,14 +1199,12 @@ impl> Global { .lock_life(&mut token) .suspected_resources.bind_groups.push(bind_group_id); } -} -impl> Global { pub fn device_create_shader_module( &self, device_id: id::DeviceId, desc: &pipeline::ShaderModuleDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::ShaderModuleId { let hub = B::hub(self); let mut token = Token::root(); @@ -1253,14 +1239,12 @@ impl> Global { device_guard[module.device_id.value].raw.destroy_shader_module(module.raw); } } -} -impl> Global { pub fn device_create_command_encoder( &self, device_id: id::DeviceId, _desc: &wgt::CommandEncoderDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::CommandEncoderId { let hub = B::hub(self); let mut token = Token::root(); @@ -1345,17 +1329,13 @@ impl> Global { .suspected_resources.extend(&device.temp_suspected); device.com_allocator.discard(comb); } -} -impl> Global { pub fn command_buffer_destroy( &self, command_buffer_id: id::CommandBufferId ) { self.command_encoder_destroy::(command_buffer_id) } -} -impl> Global { pub fn queue_submit( &self, queue_id: id::QueueId, @@ -1504,14 +1484,12 @@ impl> Global { fire_map_callbacks(callbacks); } -} -impl> Global { pub fn device_create_render_pipeline( &self, device_id: id::DeviceId, desc: &pipeline::RenderPipelineDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::RenderPipelineId { let hub = B::hub(self); let mut token = Token::root(); @@ -1780,14 +1758,12 @@ impl> Global { //TODO: track usage by GPU hub.render_pipelines.unregister(render_pipeline_id, &mut token); } -} -impl> Global { pub fn device_create_compute_pipeline( &self, device_id: id::DeviceId, desc: &pipeline::ComputePipelineDescriptor, - id_in: F::Input, + id_in: Input, ) -> id::ComputePipelineId { let hub = B::hub(self); let mut token = Token::root(); @@ -1848,43 +1824,41 @@ impl> Global { //TODO: track usage by GPU hub.compute_pipelines.unregister(compute_pipeline_id, &mut token); } -} -fn validate_swap_chain_descriptor( - config: &mut hal::window::SwapchainConfig, - caps: &hal::window::SurfaceCapabilities, -) { - let width = config.extent.width; - let height = config.extent.height; - if width < caps.extents.start().width - || width > caps.extents.end().width - || height < caps.extents.start().height - || height > caps.extents.end().height - { - log::warn!( - "Requested size {}x{} is outside of the supported range: {:?}", - width, - height, - caps.extents - ); - } - if !caps.present_modes.contains(config.present_mode) { - log::warn!( - "Surface does not support present mode: {:?}, falling back to {:?}", - config.present_mode, - hal::window::PresentMode::FIFO - ); - config.present_mode = hal::window::PresentMode::FIFO; - } -} - -impl> Global { pub fn device_create_swap_chain( &self, device_id: id::DeviceId, surface_id: id::SurfaceId, desc: &wgt::SwapChainDescriptor, ) -> id::SwapChainId { + fn validate_swap_chain_descriptor( + config: &mut hal::window::SwapchainConfig, + caps: &hal::window::SurfaceCapabilities, + ) { + let width = config.extent.width; + let height = config.extent.height; + if width < caps.extents.start().width + || width > caps.extents.end().width + || height < caps.extents.start().height + || height > caps.extents.end().height + { + log::warn!( + "Requested size {}x{} is outside of the supported range: {:?}", + width, + height, + caps.extents + ); + } + if !caps.present_modes.contains(config.present_mode) { + log::warn!( + "Surface does not support present mode: {:?}, falling back to {:?}", + config.present_mode, + hal::window::PresentMode::FIFO + ); + config.present_mode = hal::window::PresentMode::FIFO; + } + } + log::info!("creating swap chain {:?}", desc); let hub = B::hub(self); let mut token = Token::root(); @@ -1945,9 +1919,7 @@ impl> Global { swap_chain_guard.insert(sc_id, swap_chain); sc_id } -} -impl Global { pub fn device_poll(&self, device_id: id::DeviceId, force_wait: bool) { let hub = B::hub(self); let mut token = Token::root(); @@ -1990,9 +1962,7 @@ impl Global { fire_map_callbacks(callbacks); } -} -impl> Global { pub fn device_destroy(&self, device_id: id::DeviceId) { let hub = B::hub(self); let mut token = Token::root(); @@ -2001,9 +1971,7 @@ impl> Global { drop(token); device.dispose(); } -} -impl Global { pub fn buffer_map_async( &self, buffer_id: id::BufferId, diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index a7ad5f0b5..9c4abe38b 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -71,7 +71,7 @@ impl IdentityManager { } } - pub fn free(&mut self, id: I) { + pub fn free(&mut self, id: I) { let (index, epoch, _backend) = id.unzip(); // avoid doing this check in release if cfg!(debug_assertions) { @@ -252,22 +252,13 @@ impl<'a, T> Drop for Token<'a, T> { } -pub trait IdentityFilter: Debug { +pub trait IdentityHandler: Debug { type Input: Clone + Debug; fn process(&self, id: Self::Input, backend: Backend) -> I; fn free(&self, id: I); } -impl IdentityFilter for () { - type Input = I; - fn process(&self, id: I, _backend: Backend) -> I { - //debug_assert_eq!(id.unzip().2, backend); - id - } - fn free(&self, _id: I) {} -} - -impl IdentityFilter for Mutex { +impl IdentityHandler for Mutex { type Input = PhantomData; fn process(&self, _id: Self::Input, backend: Backend) -> I { self.lock().alloc(backend) @@ -277,32 +268,55 @@ impl IdentityFilter for Mutex { } } -/// Compound trait for all the things a device cares about -/// for the matter of destruction/cleanup. -pub trait AllIdentityFilter: - IdentityFilter - + IdentityFilter - + IdentityFilter - + IdentityFilter - + IdentityFilter -{ +pub trait IdentityHandlerFactory { + type Filter: IdentityHandler; + fn spawn(&self) -> Self::Filter; } -impl AllIdentityFilter for Mutex {} -impl AllIdentityFilter for () {} +#[derive(Debug)] +pub struct IdentityManagerFactory; + +impl IdentityHandlerFactory for IdentityManagerFactory { + type Filter = Mutex; + fn spawn(&self) -> Self::Filter { + Mutex::new(IdentityManager::default()) + } +} + +pub trait GlobalIdentityHandlerFactory: + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory + + IdentityHandlerFactory +{} + +impl GlobalIdentityHandlerFactory for IdentityManagerFactory {} + +pub type Input = <>::Filter as IdentityHandler>::Input; #[derive(Debug)] -pub struct Registry { - pub(crate) identity: F, +pub struct Registry> { + identity: F::Filter, data: RwLock>, backend: Backend, } -impl Registry { - fn new(backend: Backend) -> Self { +impl> Registry { + fn new(backend: Backend, factory: &F) -> Self { Registry { - identity: F::default(), + identity: factory.spawn(), data: RwLock::new(Storage { map: VecMap::new(), _phantom: PhantomData, @@ -312,7 +326,7 @@ impl Registry { } } -impl Registry { +impl> Registry { pub fn register>(&self, id: I, value: T, _token: &mut Token) { debug_assert_eq!(id.unzip().2, self.backend); let old = self.data.write().insert(id, value); @@ -334,10 +348,10 @@ impl Registry { } } -impl> Registry { +impl> Registry { pub fn register_identity>( &self, - id_in: F::Input, + id_in: >::Input, value: T, token: &mut Token, ) -> I { @@ -356,10 +370,14 @@ impl> Registry { self.identity.free(id); (value, Token::new()) } + + pub fn free_id(&self, id: I) { + self.identity.free(id) + } } #[derive(Debug)] -pub struct Hub { +pub struct Hub { pub adapters: Registry, AdapterId, F>, pub devices: Registry, DeviceId, F>, pub swap_chains: Registry, SwapChainId, F>, @@ -376,28 +394,28 @@ pub struct Hub { pub samplers: Registry, SamplerId, F>, } -impl Default for Hub { - fn default() -> Self { +impl Hub { + fn new(factory: &F) -> Self { Hub { - adapters: Registry::new(B::VARIANT), - devices: Registry::new(B::VARIANT), - swap_chains: Registry::new(B::VARIANT), - pipeline_layouts: Registry::new(B::VARIANT), - shader_modules: Registry::new(B::VARIANT), - bind_group_layouts: Registry::new(B::VARIANT), - bind_groups: Registry::new(B::VARIANT), - command_buffers: Registry::new(B::VARIANT), - render_pipelines: Registry::new(B::VARIANT), - compute_pipelines: Registry::new(B::VARIANT), - buffers: Registry::new(B::VARIANT), - textures: Registry::new(B::VARIANT), - texture_views: Registry::new(B::VARIANT), - samplers: Registry::new(B::VARIANT), + adapters: Registry::new(B::VARIANT, factory), + devices: Registry::new(B::VARIANT, factory), + swap_chains: Registry::new(B::VARIANT, factory), + pipeline_layouts: Registry::new(B::VARIANT, factory), + shader_modules: Registry::new(B::VARIANT, factory), + bind_group_layouts: Registry::new(B::VARIANT, factory), + bind_groups: Registry::new(B::VARIANT, factory), + command_buffers: Registry::new(B::VARIANT, factory), + render_pipelines: Registry::new(B::VARIANT, factory), + compute_pipelines: Registry::new(B::VARIANT, factory), + buffers: Registry::new(B::VARIANT, factory), + textures: Registry::new(B::VARIANT, factory), + texture_views: Registry::new(B::VARIANT, factory), + samplers: Registry::new(B::VARIANT, factory), } } } -impl Drop for Hub { +impl Drop for Hub { fn drop(&mut self) { use crate::resource::TextureViewInner; use hal::device::Device as _; @@ -482,8 +500,8 @@ impl Drop for Hub { } } -#[derive(Debug, Default)] -pub struct Hubs { +#[derive(Debug)] +pub struct Hubs { #[cfg(any( not(any(target_os = "ios", target_os = "macos")), feature = "gfx-backend-vulkan" @@ -497,19 +515,37 @@ pub struct Hubs { dx11: Hub, } -#[derive(Debug)] -pub struct Global { - pub instance: Instance, - pub surfaces: Registry, - hubs: Hubs, +impl Hubs { + fn new(factory: &F) -> Self { + Hubs { + #[cfg(any( + not(any(target_os = "ios", target_os = "macos")), + feature = "gfx-backend-vulkan" + ))] + vulkan: Hub::new(factory), + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: Hub::new(factory), + #[cfg(windows)] + dx12: Hub::new(factory), + #[cfg(windows)] + dx11: Hub::new(factory), + } + } } -impl Global { - pub fn new(name: &str) -> Self { +#[derive(Debug)] +pub struct Global { + pub instance: Instance, + pub surfaces: Registry, + hubs: Hubs, +} + +impl Global { + pub fn new(name: &str, factory: G) -> Self { Global { instance: Instance::new(name, 1), - surfaces: Registry::new(Backend::Empty), - hubs: Hubs::default(), + surfaces: Registry::new(Backend::Empty, &factory), + hubs: Hubs::new(&factory), } } @@ -529,7 +565,7 @@ impl Global { pub trait GfxBackend: hal::Backend { const VARIANT: Backend; - fn hub(global: &Global) -> &Hub; + fn hub(global: &Global) -> &Hub; fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface; } @@ -539,7 +575,7 @@ pub trait GfxBackend: hal::Backend { ))] impl GfxBackend for backend::Vulkan { const VARIANT: Backend = Backend::Vulkan; - fn hub(global: &Global) -> &Hub { + fn hub(global: &Global) -> &Hub { &global.hubs.vulkan } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { @@ -550,7 +586,7 @@ impl GfxBackend for backend::Vulkan { #[cfg(any(target_os = "ios", target_os = "macos"))] impl GfxBackend for backend::Metal { const VARIANT: Backend = Backend::Metal; - fn hub(global: &Global) -> &Hub { + fn hub(global: &Global) -> &Hub { &global.hubs.metal } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { @@ -561,7 +597,7 @@ impl GfxBackend for backend::Metal { #[cfg(windows)] impl GfxBackend for backend::Dx12 { const VARIANT: Backend = Backend::Dx12; - fn hub(global: &Global) -> &Hub { + fn hub(global: &Global) -> &Hub { &global.hubs.dx12 } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { @@ -572,7 +608,7 @@ impl GfxBackend for backend::Dx12 { #[cfg(windows)] impl GfxBackend for backend::Dx11 { const VARIANT: Backend = Backend::Dx11; - fn hub(global: &Global) -> &Hub { + fn hub(global: &Global) -> &Hub { &global.hubs.dx11 } fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 9f1389249..d0265ab0c 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -5,7 +5,7 @@ use crate::{ backend, device::{Device, BIND_BUFFER_ALIGNMENT}, - hub::{GfxBackend, Global, IdentityFilter, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, id::{AdapterId, DeviceId}, power, }; @@ -184,8 +184,8 @@ impl AdapterInputs<'_, I> { } } -impl> Global { - pub fn enumerate_adapters(&self, inputs: AdapterInputs) -> Vec { +impl Global { + pub fn enumerate_adapters(&self, inputs: AdapterInputs>) -> Vec { let instance = &self.instance; let mut token = Token::root(); let mut adapters = Vec::new(); @@ -258,7 +258,7 @@ impl> Global { pub fn pick_adapter( &self, desc: &RequestAdapterOptions, - inputs: AdapterInputs, + inputs: AdapterInputs>, ) -> Option { let instance = &self.instance; let mut device_types = Vec::new(); @@ -432,12 +432,12 @@ impl> Global { } } -impl> Global { +impl Global { pub fn adapter_request_device( &self, adapter_id: AdapterId, desc: &DeviceDescriptor, - id_in: F::Input, + id_in: Input, ) -> DeviceId { let hub = B::hub(self); let mut token = Token::root(); diff --git a/wgpu-core/src/swap_chain.rs b/wgpu-core/src/swap_chain.rs index b60a33c49..aca821ece 100644 --- a/wgpu-core/src/swap_chain.rs +++ b/wgpu-core/src/swap_chain.rs @@ -34,7 +34,7 @@ use crate::{ conv, - hub::{GfxBackend, Global, IdentityFilter, Token}, + hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, id::{DeviceId, SwapChainId, TextureViewId}, resource, Features, @@ -93,11 +93,11 @@ pub enum SwapChainGetNextTextureError { GpuProcessingTimeout, } -impl> Global { +impl Global { pub fn swap_chain_get_next_texture( &self, swap_chain_id: SwapChainId, - view_id_in: F::Input, + view_id_in: Input, ) -> Result { let hub = B::hub(self); let mut token = Token::root(); diff --git a/wgpu-native/src/lib.rs b/wgpu-native/src/lib.rs index 74970826b..d86fa0530 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -10,8 +10,8 @@ mod device; pub use self::command::*; pub use self::device::*; -type Global = core::hub::Global>; +type Global = core::hub::Global; lazy_static::lazy_static! { - static ref GLOBAL: Arc = Arc::new(Global::new("wgpu")); + static ref GLOBAL: Arc = Arc::new(Global::new("wgpu", core::hub::IdentityManagerFactory)); } diff --git a/wgpu-remote/cbindgen.toml b/wgpu-remote/cbindgen.toml index 9dc41a317..af6001149 100644 --- a/wgpu-remote/cbindgen.toml +++ b/wgpu-remote/cbindgen.toml @@ -9,7 +9,6 @@ autogen_warning = """/* DO NOT MODIFY THIS MANUALLY! This file was generated usi */ typedef void WGPUEmpty; -typedef struct WGPUGlobal WGPUGlobal; """ include_version = true braces = "SameLine" diff --git a/wgpu-remote/src/identity.rs b/wgpu-remote/src/identity.rs new file mode 100644 index 000000000..6a208e392 --- /dev/null +++ b/wgpu-remote/src/identity.rs @@ -0,0 +1,201 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use core::id; + + +pub type FactoryParam = *mut std::ffi::c_void; + +#[derive(Debug)] +pub struct IdentityRecycler { + fun: extern "C" fn(I, FactoryParam), + param: FactoryParam, + kind: &'static str, +} + +impl core::hub::IdentityHandler for IdentityRecycler { + type Input = I; + fn process(&self, id: I, _backend: wgt::Backend) -> I { + log::debug!("process {} {:?}", self.kind, id); + //debug_assert_eq!(id.unzip().2, backend); + id + } + fn free(&self, id: I) { + log::debug!("free {} {:?}", self.kind, id); + (self.fun)(id, self.param); + } +} + +#[repr(C)] +pub struct IdentityRecyclerFactory { + param: FactoryParam, + free_adapter: extern "C" fn(id::AdapterId, FactoryParam), + free_device: extern "C" fn(id::DeviceId, FactoryParam), + free_swap_chain: extern "C" fn(id::SwapChainId, FactoryParam), + free_pipeline_layout: extern "C" fn(id::PipelineLayoutId, FactoryParam), + free_shader_module: extern "C" fn(id::ShaderModuleId, FactoryParam), + free_bind_group_layout: extern "C" fn(id::BindGroupLayoutId, FactoryParam), + free_bind_group: extern "C" fn(id::BindGroupId, FactoryParam), + free_command_buffer: extern "C" fn(id::CommandBufferId, FactoryParam), + free_render_pipeline: extern "C" fn(id::RenderPipelineId, FactoryParam), + free_compute_pipeline: extern "C" fn(id::ComputePipelineId, FactoryParam), + free_buffer: extern "C" fn(id::BufferId, FactoryParam), + free_texture: extern "C" fn(id::TextureId, FactoryParam), + free_texture_view: extern "C" fn(id::TextureViewId, FactoryParam), + free_sampler: extern "C" fn(id::SamplerId, FactoryParam), + free_surface: extern "C" fn(id::SurfaceId, FactoryParam), +} + +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_adapter, + param: self.param, + kind: "adapter", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_device, + param: self.param, + kind: "device", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_swap_chain, + param: self.param, + kind: "swap_chain", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_pipeline_layout, + param: self.param, + kind: "pipeline_layout", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_shader_module, + param: self.param, + kind: "shader_module", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_bind_group_layout, + param: self.param, + kind: "bind_group_layout", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_bind_group, + param: self.param, + kind: "bind_group", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_command_buffer, + param: self.param, + kind: "command_buffer", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_render_pipeline, + param: self.param, + kind: "render_pipeline", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_compute_pipeline, + param: self.param, + kind: "compute_pipeline", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_buffer, + param: self.param, + kind: "buffer", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_texture, + param: self.param, + kind: "texture", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_texture_view, + param: self.param, + kind: "texture_view", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_sampler, + param: self.param, + kind: "sampler", + } + } +} +impl core::hub::IdentityHandlerFactory for IdentityRecyclerFactory { + type Filter = IdentityRecycler; + fn spawn(&self) -> Self::Filter { + IdentityRecycler { + fun: self.free_surface, + param: self.param, + kind: "surface", + } + } +} + +impl core::hub::GlobalIdentityHandlerFactory for IdentityRecyclerFactory {} diff --git a/wgpu-remote/src/lib.rs b/wgpu-remote/src/lib.rs index ec5295e2c..7e7f5ba9e 100644 --- a/wgpu-remote/src/lib.rs +++ b/wgpu-remote/src/lib.rs @@ -18,6 +18,7 @@ use parking_lot::Mutex; use std::{ptr, slice}; +pub mod identity; pub mod server; @@ -124,21 +125,14 @@ pub unsafe extern "C" fn wgpu_client_make_adapter_ids( id_length - ids.len() } -/// # Safety -/// -/// This function is unsafe as there is no guarantee that the given pointer is -/// valid for `id_length` elements. #[no_mangle] -pub unsafe extern "C" fn wgpu_client_kill_adapter_ids( - client: &Client, - ids: *const id::AdapterId, - id_length: usize, -) { - let mut identity = client.identities.lock(); - let ids = slice::from_raw_parts(ids, id_length); - for &id in ids { - identity.select(id.backend()).adapters.free(id) - } +pub extern "C" fn wgpu_client_kill_adapter_id(client: &Client, id: id::AdapterId) { + client + .identities + .lock() + .select(id.backend()) + .adapters + .free(id) } #[no_mangle] diff --git a/wgpu-remote/src/server.rs b/wgpu-remote/src/server.rs index 3aa25ced4..18bc0cbf9 100644 --- a/wgpu-remote/src/server.rs +++ b/wgpu-remote/src/server.rs @@ -2,16 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::identity::IdentityRecyclerFactory; + use core::{gfx_select, id}; use std::slice; -pub type Global = core::hub::Global<()>; + +pub type Global = core::hub::Global; #[no_mangle] -pub extern "C" fn wgpu_server_new() -> *mut Global { +pub extern "C" fn wgpu_server_new(factory: IdentityRecyclerFactory) -> *mut Global { log::info!("Initializing WGPU server"); - Box::into_raw(Box::new(Global::new("wgpu"))) + Box::into_raw(Box::new(Global::new("wgpu", factory))) } /// # Safety