document the d3d and win32 safety invariants

This commit is contained in:
2026-09-21 01:06:34 +03:00
parent 186337b7bb
commit e0ceb7591c
+79 -38
View File
@@ -100,6 +100,9 @@ impl TonemapPipeline {
// Vertex shader: fullscreen-triangle pass-through (no vertex buffer). // Vertex shader: fullscreen-triangle pass-through (no vertex buffer).
let mut vs = None; let mut vs = None;
unsafe { unsafe {
// SAFETY: `device` is the live ID3D11Device owned by the capture
// frame. FULLSCREEN_VS is bytecode embedded at build time, and the
// out-param points at a local Option the call writes through.
device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?; device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?;
} }
let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?; let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?;
@@ -128,6 +131,9 @@ impl TonemapPipeline {
]; ];
let mut input_layout = None; let mut input_layout = None;
unsafe { unsafe {
// SAFETY: the element descriptions and the vertex-shader bytecode
// are both valid for the duration of the call; CreateInputLayout
// validates that they match and errors if they do not.
device.CreateInputLayout( device.CreateInputLayout(
&input_elements, &input_elements,
FULLSCREEN_VS, FULLSCREEN_VS,
@@ -160,6 +166,8 @@ impl TonemapPipeline {
}; };
let mut vertex_buffer = None; let mut vertex_buffer = None;
unsafe { unsafe {
// SAFETY: both descriptions are stack locals that outlive the call,
// and vb_init.pSysMem points at the `verts` array declared above.
device.CreateBuffer(&raw const vb_desc, Some(&raw const vb_init), Some(&raw mut vertex_buffer))?; device.CreateBuffer(&raw const vb_desc, Some(&raw const vb_init), Some(&raw mut vertex_buffer))?;
} }
let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?; let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
@@ -167,6 +175,7 @@ impl TonemapPipeline {
// Pixel shader: Hable tonemap + bt709 OETF. // Pixel shader: Hable tonemap + bt709 OETF.
let mut ps = None; let mut ps = None;
unsafe { unsafe {
// SAFETY: live device, build-time-embedded bytecode, local out-param.
device.CreatePixelShader(TONEMAP_PS, None, Some(&raw mut ps))?; device.CreatePixelShader(TONEMAP_PS, None, Some(&raw mut ps))?;
} }
let ps = ps.ok_or_else(|| anyhow!("CreatePixelShader returned null"))?; let ps = ps.ok_or_else(|| anyhow!("CreatePixelShader returned null"))?;
@@ -186,6 +195,8 @@ impl TonemapPipeline {
}; };
let mut sampler = None; let mut sampler = None;
unsafe { unsafe {
// SAFETY: sampler_desc is a fully-initialized stack local and the
// out-param is a local Option.
device.CreateSamplerState(&raw const sampler_desc, Some(&raw mut sampler))?; device.CreateSamplerState(&raw const sampler_desc, Some(&raw mut sampler))?;
} }
let sampler = sampler.ok_or_else(|| anyhow!("CreateSamplerState returned null"))?; let sampler = sampler.ok_or_else(|| anyhow!("CreateSamplerState returned null"))?;
@@ -208,6 +219,8 @@ impl TonemapPipeline {
}; };
let mut rasterizer = None; let mut rasterizer = None;
unsafe { unsafe {
// SAFETY: rasterizer_desc is a fully-initialized stack local and the
// out-param is a local Option.
device.CreateRasterizerState(&raw const rasterizer_desc, Some(&raw mut rasterizer))?; device.CreateRasterizerState(&raw const rasterizer_desc, Some(&raw mut rasterizer))?;
} }
let rasterizer = let rasterizer =
@@ -228,6 +241,8 @@ impl TonemapPipeline {
}; };
let mut render_target = None; let mut render_target = None;
unsafe { unsafe {
// SAFETY: rt_desc is a fully-initialized stack local and the
// out-param is a local Option.
device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?; device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?;
} }
let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?; let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?;
@@ -241,6 +256,8 @@ impl TonemapPipeline {
}; };
let mut rtv = None; let mut rtv = None;
unsafe { unsafe {
// SAFETY: render_target was just created on this device and
// view_desc describes a valid subresource of it.
device.CreateRenderTargetView(&render_target, Some(&raw const view_desc), Some(&raw mut rtv))?; device.CreateRenderTargetView(&render_target, Some(&raw const view_desc), Some(&raw mut rtv))?;
} }
let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?; let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?;
@@ -260,6 +277,8 @@ impl TonemapPipeline {
}; };
let mut staging = None; let mut staging = None;
unsafe { unsafe {
// SAFETY: staging_desc is a fully-initialized stack local and the
// out-param is a local Option.
device.CreateTexture2D(&raw const staging_desc, None, Some(&raw mut staging))?; device.CreateTexture2D(&raw const staging_desc, None, Some(&raw mut staging))?;
} }
let staging = staging.ok_or_else(|| anyhow!("CreateTexture2D staging returned null"))?; let staging = staging.ok_or_else(|| anyhow!("CreateTexture2D staging returned null"))?;
@@ -290,6 +309,8 @@ impl TonemapPipeline {
out: &mut dyn Write, out: &mut dyn Write,
) -> Result<()> { ) -> Result<()> {
let mut desc = D3D11_TEXTURE2D_DESC::default(); let mut desc = D3D11_TEXTURE2D_DESC::default();
// SAFETY: `desc` is a zero-initialized local that GetDesc fully writes;
// `src` is the captured texture owned by this frame.
unsafe { src.GetDesc(&raw mut desc) }; unsafe { src.GetDesc(&raw mut desc) };
if desc.Width != self.width || desc.Height != self.height { if desc.Width != self.width || desc.Height != self.height {
// Resize - rebuild the RT/staging at the new dimensions. // Resize - rebuild the RT/staging at the new dimensions.
@@ -300,30 +321,54 @@ impl TonemapPipeline {
*self = Self::new(device, desc.Width, desc.Height)?; *self = Self::new(device, desc.Width, desc.Height)?;
} }
unsafe { // SRV onto the captured HDR texture.
// SRV onto the captured HDR texture. let srv_desc = D3D11_SHADER_RESOURCE_VIEW_DESC {
let srv_desc = D3D11_SHADER_RESOURCE_VIEW_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT,
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT, ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D,
ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D, Anonymous: windows::Win32::Graphics::Direct3D11::D3D11_SHADER_RESOURCE_VIEW_DESC_0 {
Anonymous: windows::Win32::Graphics::Direct3D11::D3D11_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D11_TEX2D_SRV {
Texture2D: D3D11_TEX2D_SRV { MostDetailedMip: 0,
MostDetailedMip: 0, MipLevels: 1,
MipLevels: 1,
},
}, },
}; },
let mut srv: Option<ID3D11ShaderResourceView> = None; };
let mut srv: Option<ID3D11ShaderResourceView> = None;
// SAFETY: `src` is the live capture texture and was resized to match the
// pipeline above; srv_desc is a stack local describing one mip.
unsafe {
device.CreateShaderResourceView(src, Some(&raw const srv_desc), Some(&raw mut srv))?; device.CreateShaderResourceView(src, Some(&raw const srv_desc), Some(&raw mut srv))?;
let srv = srv.ok_or_else(|| anyhow!("CreateShaderResourceView returned null"))?; }
let srv = srv.ok_or_else(|| anyhow!("CreateShaderResourceView returned null"))?;
// Canonical bind sequence: IA -> shaders -> resources -> output let vb = [Some(self.vertex_buffer.clone())];
// merger -> viewport+scissor -> draw. Every stage explicit because let strides = [16u32];
// the frame's device/context carries state from prior frames. let offsets = [0u32];
let viewport = [D3D11_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: self.width as f32,
Height: self.height as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
}];
// Scissor covering the whole RT (rasterizer has ScissorEnable=true).
let scissor = [windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: self.width.cast_signed(),
bottom: self.height.cast_signed(),
}];
// Canonical bind sequence: IA -> shaders -> resources -> output merger
// -> viewport+scissor -> draw. Every stage is set explicitly because the
// frame's device/context still carries state from prior frames.
//
// SAFETY: every resource bound here was created on this same device and
// is kept alive by `self` for the duration of the draw; the slices and
// viewport/scissor arrays are stack locals that outlive each call.
unsafe {
context.IASetInputLayout(&self.input_layout); context.IASetInputLayout(&self.input_layout);
context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
let vb = [Some(self.vertex_buffer.clone())];
let strides = [16u32];
let offsets = [0u32];
context.IASetVertexBuffers( context.IASetVertexBuffers(
0, 0,
1, 1,
@@ -337,30 +382,22 @@ impl TonemapPipeline {
context.PSSetSamplers(0, Some(&[Some(self.sampler.clone())])); context.PSSetSamplers(0, Some(&[Some(self.sampler.clone())]));
context.OMSetRenderTargets(Some(&[Some(self.rtv.clone())]), None); context.OMSetRenderTargets(Some(&[Some(self.rtv.clone())]), None);
context.RSSetState(&self.rasterizer); context.RSSetState(&self.rasterizer);
context.RSSetViewports(Some(&[D3D11_VIEWPORT { context.RSSetViewports(Some(&viewport));
TopLeftX: 0.0, context.RSSetScissorRects(Some(&scissor));
TopLeftY: 0.0,
Width: self.width as f32,
Height: self.height as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
}]));
// Scissor covering the whole RT (rasterizer has ScissorEnable=true).
context.RSSetScissorRects(Some(&[windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: self.width.cast_signed(),
bottom: self.height.cast_signed(),
}]));
context.Draw(3, 0); context.Draw(3, 0);
}
// Copy to staging and read back. // Copy to the SDR staging texture and read it back.
// SAFETY: both textures live on this device and share dimensions and
// format, so the copy is well-defined; `mapped` is a zeroed local that
// Map fills before any field of it is read.
let row_bytes = self.width * 4;
unsafe {
context.CopyResource(&self.staging, &self.render_target); context.CopyResource(&self.staging, &self.render_target);
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&raw mut mapped))?; context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&raw mut mapped))?;
let row_bytes = self.width * 4;
let src_slice = std::slice::from_raw_parts( let src_slice = std::slice::from_raw_parts(
mapped.pData as *const u8, mapped.pData.cast::<u8>(),
(mapped.RowPitch as usize) * (self.height as usize), (mapped.RowPitch as usize) * (self.height as usize),
); );
// RowPitch may exceed width*4 (alignment); copy row by row. // RowPitch may exceed width*4 (alignment); copy row by row.
@@ -558,7 +595,11 @@ fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST}; use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
let pt = POINT { x, y }; let pt = POINT { x, y };
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) }; let hmonitor = unsafe {
// SAFETY: MonitorFromPoint writes nothing and only reads the POINT by
// value; it returns the nearest monitor or null, which is checked next.
MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST)
};
if hmonitor.0.is_null() { if hmonitor.0.is_null() {
bail!("MonitorFromPoint returned null for ({x}, {y})"); bail!("MonitorFromPoint returned null for ({x}, {y})");
} }