Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
645 changes: 613 additions & 32 deletions crates/victory-gpu/src/draw.rs

Large diffs are not rendered by default.

27 changes: 26 additions & 1 deletion crates/victory-gpu/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,10 @@ pub(crate) fn note_drop(this: This) {
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn note_why(why: String) {
let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner());
*drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1;
*drops
.get_or_insert_with(HashMap::new)
.entry(why)
.or_default() += 1;
}

/// The drops counted since the last call, most first (diagnostics).
Expand Down Expand Up @@ -501,6 +504,28 @@ pub fn save_pipeline_cache() {
library::save(true);
}

#[cfg(all(test, windows))]
pub(crate) fn test_compute_pipeline(
host: victory_shader::emit::HostShader,
used: Vec<victory_shader::UsedResource>,
) -> This {
let hash = blake3::hash(&host.dxil).to_hex()[..16].to_owned();
let translated = OnceLock::new();
let _ = translated.set(Some(Translated { host, used }));
let shader = Arc::new(Shader {
stage: "compute",
hash,
container: Vec::new(),
translated,
});
let mut out = std::ptr::null();
assert_eq!(
hand_out(vec![shader], None, &PIPELINE_IIDS[0], &mut out),
crate::object::S_OK
);
out
}

#[cfg(test)]
mod tests {
#[cfg(all(windows, feature = "diagnostics"))]
Expand Down
213 changes: 187 additions & 26 deletions crates/victory-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,12 @@ impl GraphicsState {
.map(|(e, name)| {
format!(
"{name:?} {} {} {} {} {} {}",
e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate
e.SemanticIndex,
e.Format.0,
e.InputSlot,
e.AlignedByteOffset,
e.InputSlotClass.0,
e.InstanceDataStepRate
)
})
.collect();
Expand Down Expand Up @@ -251,6 +256,7 @@ pub(crate) struct Stage {
/// Root parameters of its root views: (title root parameter, ours).
pub(crate) root_cbvs: Vec<(u8, u32)>,
pub(crate) root_srvs: Vec<(u8, u32)>,
pub(crate) root_uavs: Vec<(u8, u32)>,
}

impl Stage {
Expand Down Expand Up @@ -289,6 +295,10 @@ fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline>
}

impl HostPipeline {
pub(crate) fn has_root_uavs(&self) -> bool {
self.stages.iter().any(|s| !s.root_uavs.is_empty())
}

/// A host pipeline for vertex and pixel shaders with the graphics
/// state `g`, or for one compute shader.
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
Expand Down Expand Up @@ -321,7 +331,10 @@ impl HostPipeline {
stages
};
if mesh.is_some() && !host()?.mesh_shaders() {
return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders);
return refuse(
"the host GPU has no mesh shaders (or no shader model 6.6)",
shaders,
);
}
for (s, _) in &stages {
s.translated()?;
Expand All @@ -332,13 +345,15 @@ impl HostPipeline {
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
let mut samplers = Vec::new();
let mut bound = Vec::new();
let mut root_views: Vec<((i32, u8), u32)> = Vec::new();
for &(shader, visibility) in &stages {
let t = &shader.translated()?.host;
let mut stage = Stage {
shader: shader.clone(),
user_data: None,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
};
let dwords = t.user_data_dwords();
if dwords > 0 {
Expand Down Expand Up @@ -366,20 +381,18 @@ impl HostPipeline {
D3D12_ROOT_PARAMETER_TYPE_SRV,
&mut stage.root_srvs,
),
(
&t.root_uavs,
D3D12_ROOT_PARAMETER_TYPE_UAV,
&mut stage.root_uavs,
),
] {
for &slot in slots {
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: kind,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: u32::from(slot),
RegisterSpace: ROOT_CBV_SPACE,
Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
},
},
ShaderVisibility: visibility,
});
let param =
push_root_view(&mut params, &mut root_views, kind, slot, visibility);
if !out.contains(&(slot, param)) {
out.push((slot, param));
}
}
}
for (n, s) in t.static_samplers.iter().enumerate() {
Expand All @@ -401,13 +414,14 @@ impl HostPipeline {
}
bound.push(stage);
}
let (root, root_blob) = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
Ok(root) => root,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host root signature refused");
return None;
}
};
let (root, root_blob) =
match root_signature(&host.device, &params, &samplers, compute.is_some()) {
Ok(root) => root,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host root signature refused");
return None;
}
};
let code = |i: usize| {
stages.get(i).and_then(|(s, _)| s.translated()).map_or(
D3D12_SHADER_BYTECODE::default(),
Expand Down Expand Up @@ -585,15 +599,27 @@ fn mesh_pipeline(
samples: Sub<DXGI_SAMPLE_DESC>,
}
let mut stream = Stream {
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
root: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE,
root.as_raw(),
),
ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms),
ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps),
blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend),
mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask),
mask: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK,
g.sample_mask,
),
raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer),
depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth),
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
targets: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS,
g.targets,
),
dsv: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT,
g.depth_format,
),
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
};
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
Expand All @@ -616,7 +642,40 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> {
return Vec::new();
}
// SAFETY: a translation's own bytes, alive while its shader is.
unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }.to_vec()
unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }
.to_vec()
}

/// Adds or reuses a root view parameter for `(kind, slot)`, widening its
/// visibility to `ALL` when shared across multiple shader stages so shared
/// root descriptors do not consume extra root signature dwords.
fn push_root_view(
params: &mut Vec<D3D12_ROOT_PARAMETER1>,
seen: &mut Vec<((i32, u8), u32)>,
kind: D3D12_ROOT_PARAMETER_TYPE,
slot: u8,
visibility: D3D12_SHADER_VISIBILITY,
) -> u32 {
if let Some(&(_, existing)) = seen.iter().find(|&&(k, _)| k == (kind.0, slot)) {
if params[existing as usize].ShaderVisibility != visibility {
params[existing as usize].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
}
return existing;
}
let index = params.len() as u32;
seen.push(((kind.0, slot), index));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: kind,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: u32::from(slot),
RegisterSpace: ROOT_CBV_SPACE,
Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
},
},
ShaderVisibility: visibility,
});
index
}

fn root_signature(
Expand Down Expand Up @@ -665,3 +724,105 @@ fn root_signature(
Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
}
}

#[cfg(test)]
mod tests {
use super::*;
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Dxgi::{
CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter, IDXGIFactory4,
};

#[test]
fn root_views_deduplicate_across_stages_and_create_on_warp() {
let mut params = Vec::new();
let mut seen = Vec::new();

// Vertex stage declares CBV 0, SRV 1, UAV 2.
let v_cbv = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_CBV,
0,
D3D12_SHADER_VISIBILITY_VERTEX,
);
let v_srv = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_SRV,
1,
D3D12_SHADER_VISIBILITY_VERTEX,
);
let v_uav = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_UAV,
2,
D3D12_SHADER_VISIBILITY_VERTEX,
);
assert_eq!((v_cbv, v_srv, v_uav), (0, 1, 2));
assert_eq!(params[2].ShaderVisibility, D3D12_SHADER_VISIBILITY_VERTEX);

// Pixel stage shares CBV 0 and UAV 2, declares SRV 2 (same slot,
// different kind -> separate parameter), and pixel-only UAV 5.
let p_cbv = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_CBV,
0,
D3D12_SHADER_VISIBILITY_PIXEL,
);
let p_uav_shared = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_UAV,
2,
D3D12_SHADER_VISIBILITY_PIXEL,
);
let p_srv_same_slot = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_SRV,
2,
D3D12_SHADER_VISIBILITY_PIXEL,
);
let p_uav_only = push_root_view(
&mut params,
&mut seen,
D3D12_ROOT_PARAMETER_TYPE_UAV,
5,
D3D12_SHADER_VISIBILITY_PIXEL,
);

assert_eq!(p_cbv, v_cbv);
assert_eq!(p_uav_shared, v_uav);
assert_eq!(p_srv_same_slot, 3);
assert_eq!(p_uav_only, 4);
assert_eq!(params.len(), 5);
assert_eq!(params[0].ShaderVisibility, D3D12_SHADER_VISIBILITY_ALL);
assert_eq!(params[1].ShaderVisibility, D3D12_SHADER_VISIBILITY_VERTEX);
assert_eq!(params[2].ShaderVisibility, D3D12_SHADER_VISIBILITY_ALL);
assert_eq!(params[3].ShaderVisibility, D3D12_SHADER_VISIBILITY_PIXEL);
assert_eq!(params[4].ShaderVisibility, D3D12_SHADER_VISIBILITY_PIXEL);

// Create the root signature on WARP (and on host() when available).
// SAFETY: plain DXGI/D3D12 device creation on the WARP software adapter.
let warp_device = unsafe {
CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
.and_then(|f| f.EnumWarpAdapter::<IDXGIAdapter>())
.and_then(|a| {
let mut dev: Option<ID3D12Device> = None;
D3D12CreateDevice(&a, D3D_FEATURE_LEVEL_12_0, &mut dev)?;
dev.ok_or_else(windows::core::Error::empty)
})
};
if let Ok(dev) = warp_device {
root_signature(&dev, &params, &[], false)
.expect("WARP CreateRootSignature with deduplicated CBV/SRV/UAV root views");
}
if let Some(h) = host() {
root_signature(&h.device, &params, &[], false)
.expect("host CreateRootSignature with deduplicated CBV/SRV/UAV root views");
}
}
}
9 changes: 6 additions & 3 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ fn cached(
(converter.translate)(container)
}

const MAGIC: &[u8; 4] = b"VSH1";
const MAGIC: &[u8; 4] = b"VSH2";
const STAGES: [HwStage; 8] = [
HwStage::Ls,
HwStage::Hs,
Expand Down Expand Up @@ -206,7 +206,7 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, v);
}
}
for slots in [&s.root_cbvs, &s.root_srvs] {
for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] {
word(&mut out, slots.len() as u32);
out.extend(slots);
}
Expand Down Expand Up @@ -266,6 +266,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
}
let root_cbvs = r.list()?;
let root_srvs = r.list()?;
let root_uavs = r.list()?;
r.0.is_empty().then_some(HostShader {
stage,
dxil,
Expand All @@ -274,6 +275,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
static_samplers,
root_cbvs,
root_srvs,
root_uavs,
})
}

Expand All @@ -300,6 +302,7 @@ mod tests {
])],
root_cbvs: vec![2],
root_srvs: vec![0, 3],
root_uavs: vec![1],
}
}

Expand All @@ -324,7 +327,7 @@ mod tests {

// A damaged entry is a miss, translated and stored again.
for e in walk(dir.path()) {
std::fs::write(e, b"VSH1 broken").unwrap();
std::fs::write(e, b"VSH2 broken").unwrap();
}
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
assert_eq!(runs.load(Ordering::Relaxed), 3);
Expand Down
Loading