use std::sync::{
Arc,
atomic::{AtomicU8, AtomicU64, Ordering},
};
use windows::Win32::{
Foundation::{CloseHandle, GENERIC_ALL, HANDLE},
Graphics::{
Direct3D12::{
D3D12_FENCE_FLAG_SHARED, D3D12_HEAP_FLAG_SHARED, D3D12_HEAP_PROPERTIES,
D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_DESC, D3D12_RESOURCE_DIMENSION_TEXTURE2D,
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS,
D3D12_RESOURCE_STATE_COMMON, D3D12_TEXTURE_LAYOUT_UNKNOWN, ID3D12Device, ID3D12Fence,
ID3D12Resource,
},
Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC},
},
};
use crate::shader_frame::SharedTexture;
pub(crate) const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8Unorm;
const SLOTS: usize = 3;
mod state {
pub(super) const IDLE: u8 = 0;
pub(super) const RENDERING: u8 = 1;
pub(super) const DONE: u8 = 2;
pub(super) const SHOWN: u8 = 3;
}
struct Fence {
fence: ID3D12Fence,
handle: HANDLE,
next: AtomicU64,
}
impl Fence {
fn new(raw: &ID3D12Device) -> Option<Fence> {
let fence: ID3D12Fence = unsafe { raw.CreateFence(0, D3D12_FENCE_FLAG_SHARED) }
.inspect_err(|e| log::debug!("shaders: no shared fence ({e})"))
.ok()?;
let handle = unsafe { raw.CreateSharedHandle(&fence, None, GENERIC_ALL.0, None) }
.inspect_err(|e| log::debug!("shaders: the fence cannot be shared ({e})"))
.ok()?;
Some(Fence {
fence,
handle,
next: AtomicU64::new(1),
})
}
}
impl Drop for Fence {
fn drop(&mut self) {
let _ = unsafe { CloseHandle(self.handle) };
}
}
#[cfg(test)]
pub(crate) fn adapter_luid(device: &wgpu::Device) -> Option<windows_sys::Win32::Foundation::LUID> {
let raw = raw_device(device)?;
let luid = unsafe { raw.GetAdapterLuid() };
Some(windows_sys::Win32::Foundation::LUID {
LowPart: luid.LowPart,
HighPart: luid.HighPart,
})
}
fn raw_device(device: &wgpu::Device) -> Option<ID3D12Device> {
let hal = unsafe { device.as_hal::<wgpu::hal::api::Dx12>() }?;
Some(hal.raw_device().clone())
}
struct Slot {
handle: HANDLE,
texture: wgpu::Texture,
view: wgpu::TextureView,
state: Arc<AtomicU8>,
serial: u64,
released: AtomicU64,
}
impl Drop for Slot {
fn drop(&mut self) {
let _ = unsafe { CloseHandle(self.handle) };
}
}
static SETS: AtomicU64 = AtomicU64::new(0);
pub(crate) struct Surfaces {
pub(crate) width: u32,
pub(crate) height: u32,
set: u64,
slots: Vec<Slot>,
shown: Option<usize>,
fence: Option<Fence>,
}
unsafe impl Send for Surfaces {}
#[derive(Debug)]
pub(crate) struct Unavailable;
impl Surfaces {
pub(crate) fn new(width: u32, height: u32) -> Surfaces {
Surfaces {
width,
height,
set: SETS.fetch_add(1, Ordering::Relaxed) + 1,
slots: Vec::with_capacity(SLOTS),
shown: None,
fence: None,
}
}
pub(crate) fn free(&mut self, device: &wgpu::Device) -> Result<Option<usize>, Unavailable> {
let completed = self
.fence
.as_ref()
.map_or(0, |f| unsafe { f.fence.GetCompletedValue() });
let free = self.slots.iter().position(|s| {
s.state.load(Ordering::Acquire) == state::IDLE
&& s.released.load(Ordering::Acquire) <= completed
});
if free.is_some() || self.slots.len() == SLOTS {
return Ok(free);
}
let raw = raw_device(device).ok_or(Unavailable)?;
if self.fence.is_none() {
self.fence = Some(Fence::new(&raw).ok_or(Unavailable)?);
}
self.slots
.push(slot(device, &raw, self.width, self.height).ok_or(Unavailable)?);
Ok(Some(self.slots.len() - 1))
}
pub(crate) fn view(&self, i: usize) -> &wgpu::TextureView {
&self.slots[i].view
}
pub(crate) fn submitted(&mut self, i: usize, serial: u64, queue: &wgpu::Queue) {
let slot = &mut self.slots[i];
slot.serial = serial;
slot.state.store(state::RENDERING, Ordering::Release);
let flag = slot.state.clone();
queue.on_submitted_work_done(move || flag.store(state::DONE, Ordering::Release));
}
pub(crate) fn collect(&mut self) -> bool {
let shown_serial = self.shown.map_or(0, |i| self.slots[i].serial);
let newest = self
.slots
.iter()
.enumerate()
.filter(|(_, s)| s.state.load(Ordering::Acquire) == state::DONE)
.max_by_key(|(_, s)| s.serial)
.map(|(i, _)| i);
let Some(newest) = newest else {
return false;
};
let chosen_serial = self.slots[newest].serial;
for (i, s) in self.slots.iter().enumerate() {
if i != newest
&& s.serial <= chosen_serial
&& s.state.load(Ordering::Acquire) == state::DONE
{
s.state.store(state::IDLE, Ordering::Release);
}
}
if chosen_serial <= shown_serial {
self.slots[newest]
.state
.store(state::IDLE, Ordering::Release);
return false;
}
if let Some(old) = self.shown.replace(newest) {
self.slots[old].state.store(state::IDLE, Ordering::Release);
}
self.slots[newest]
.state
.store(state::SHOWN, Ordering::Release);
true
}
pub(crate) fn pending(&self) -> bool {
self.slots.iter().any(|s| {
matches!(
s.state.load(Ordering::Acquire),
state::RENDERING | state::DONE
)
})
}
pub(crate) fn shown(&self) -> Option<SharedTexture> {
let slot = &self.slots[self.shown?];
let fence = self.fence.as_ref()?;
let value = fence.next.fetch_add(1, Ordering::AcqRel);
slot.released.store(value, Ordering::Release);
Some(SharedTexture {
set: self.set,
texture: slot.handle.0,
fence: fence.handle.0,
value,
width: self.width,
height: self.height,
})
}
pub(crate) fn shown_serial(&self) -> u64 {
self.shown.map_or(0, |i| self.slots[i].serial)
}
pub(crate) fn shown_texture(&self) -> Option<&wgpu::Texture> {
self.shown.map(|i| &self.slots[i].texture)
}
#[cfg(test)]
pub(crate) fn signal(&self, value: u64) {
let Some(fence) = &self.fence else {
return;
};
let _ = unsafe { fence.fence.Signal(value) };
}
}
#[cfg(test)]
pub(crate) struct Stall(ID3D12Fence);
#[cfg(test)]
impl Stall {
pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Stall> {
use windows::Win32::Graphics::Direct3D12::D3D12_FENCE_FLAG_NONE;
let raw = raw_device(device)?;
let fence: ID3D12Fence = unsafe { raw.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
let hal = unsafe { queue.as_hal::<wgpu::hal::api::Dx12>() }?;
unsafe { hal.as_raw().Wait(&fence, 1) }.ok()?;
Some(Stall(fence))
}
}
#[cfg(test)]
impl Drop for Stall {
fn drop(&mut self) {
let _ = unsafe { self.0.Signal(1) };
}
}
fn slot(device: &wgpu::Device, raw: &ID3D12Device, width: u32, height: u32) -> Option<Slot> {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Alignment: 0,
Width: u64::from(width),
Height: height,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET
| D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS,
};
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let mut resource: Option<ID3D12Resource> = None;
let made = unsafe {
raw.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_SHARED,
&desc,
D3D12_RESOURCE_STATE_COMMON,
None,
&mut resource,
)
};
let resource = made
.inspect_err(|e| log::debug!("shaders: no shared {width}x{height} texture ({e})"))
.ok()
.and(resource)?;
let handle = unsafe { raw.CreateSharedHandle(&resource, None, GENERIC_ALL.0, None) }
.inspect_err(|e| log::debug!("shaders: the texture cannot be shared ({e})"))
.ok()?;
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let hal_texture = unsafe {
wgpu::hal::dx12::Device::texture_from_raw(
resource,
FORMAT,
wgpu::TextureDimension::D2,
size,
1,
1,
)
};
let texture = unsafe {
device.create_texture_from_hal::<wgpu::hal::api::Dx12>(
hal_texture,
&wgpu::TextureDescriptor {
label: Some("nsh shader surface"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
},
)
};
Some(Slot {
handle,
view: texture.create_view(&Default::default()),
texture,
state: Arc::new(AtomicU8::new(state::IDLE)),
serial: 0,
released: AtomicU64::new(0),
})
}