Skip to content
Open
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,19 @@ title's window has focus:
| F / H | stick clicks |
| Esc, Tab | Menu, View |

### Wine / Proton / Linux

Wine's `D3DCompile` (vkd3d-shader) does not build the helper shaders in
`crates/victory-gpu/src/shaders/` (`E5005: Method 'Load' is not defined on
type 'RWByteAddressBuffer'`; the plane shaders get no root signature). Without
them indirect draws are dropped and the depth planes stay as they were: the
world stays black and empty. Cross-build with
[`dxc`](https://github.com/microsoft/DirectXShaderCompiler) on the `PATH` (or
its path in the `DXC` environment variable); `crates/victory-gpu/build.rs`
then compiles the shaders to DXIL into `OUT_DIR` and embeds them, and they are
used when `D3DCompile` fails or gives no root signature. Without `dxc` the
shaders are compiled at first use, as before. Nothing compiled is committed.

## Commands

```
Expand Down
60 changes: 60 additions & 0 deletions crates/victory-gpu/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//! Builds the title's helper shaders in `src/shaders/` ahead with `dxc`, when
//! there is one (the `DXC` environment variable, else `dxc` on the `PATH`).
//!
//! The bytecode goes to `OUT_DIR` and is embedded with `include_bytes!`;
//! nothing compiled enters the repository. Without `dxc` the files are
//! empty and the shaders are compiled at first use with `D3DCompile`, as
//! before. Wine's `D3DCompile` (vkd3d-shader) builds none of them, so a
//! build for Wine or Proton wants `dxc`.

use std::path::PathBuf;
use std::process::Command;

/// File, target profile. Every entry point is `main`; a source that
/// defines `RS` carries its root signature (`-rootsig-define RS`).
const SHADERS: &[(&str, &str)] = &[
("clamp", "cs_6_0"),
("card-compare", "cs_6_0"),
("plane-corner", "vs_6_0"),
("plane-steps", "ps_6_0"),
("plane-floats", "ps_6_0"),
];

fn main() {
println!("cargo:rerun-if-env-changed=DXC");
println!("cargo:rerun-if-env-changed=PATH");
println!("cargo:rerun-if-changed=build.rs");
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR"));
let dxc = std::env::var_os("DXC").unwrap_or_else(|| "dxc".into());
let have = Command::new(&dxc)
.arg("-help")
.output()
.is_ok_and(|o| o.status.success());
for (name, profile) in SHADERS {
let source = format!("src/shaders/{name}.hlsl");
println!("cargo:rerun-if-changed={source}");
let target = out.join(format!("{name}.dxil"));
let _ = std::fs::remove_file(&target);
let mut built = false;
if have {
let text = std::fs::read_to_string(&source).expect("shader source");
let mut cmd = Command::new(&dxc);
cmd.args(["-nologo", "-T", profile, "-E", "main"]);
if text.contains("#define RS") {
cmd.args(["-rootsig-define", "RS"]);
}
let result = cmd.arg("-Fo").arg(&target).arg(&source).output();
match result {
Ok(o) if o.status.success() => built = true,
Ok(o) => println!(
"cargo:warning=dxc failed on {source}: {}",
String::from_utf8_lossy(&o.stderr).replace('\n', " ")
),
Err(e) => println!("cargo:warning=dxc did not run on {source}: {e}"),
}
}
if !built {
std::fs::write(&target, []).expect("OUT_DIR");
}
}
}
104 changes: 35 additions & 69 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -834,27 +834,9 @@ struct TwinUse {
/// the host turns the same float into the same 24 bits. The step divided
/// by 65535 is another float for 512 of the 65,536 steps (none under 257),
/// and lands in another 24-bit step for 127 of them (none under 385).
const PLANE_CORNERS: &str = r#"
float4 corner(uint i : SV_VertexID) : SV_Position {
return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
}
"#;
const PLANE_STEPS: &str = r#"
#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
Texture2DArray<uint> twin : register(t0);
[RootSignature(RS)]
float plane(float4 p : SV_Position) : SV_Depth {
return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
}
"#;
const PLANE_FLOATS: &str = r#"
#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
Texture2DArray<float> twin : register(t0);
[RootSignature(RS)]
float plane(float4 p : SV_Position) : SV_Depth {
return twin.Load(int4(int2(p.xy), 0, 0));
}
"#;
const PLANE_CORNERS: &str = include_str!("shaders/plane-corner.hlsl");
const PLANE_STEPS: &str = include_str!("shaders/plane-steps.hlsl");
const PLANE_FLOATS: &str = include_str!("shaders/plane-floats.hlsl");

/// Views of twins the pass reads, in a heap of ours used as a ring.
/// shortcut: a view must last until its list has run; with one or two
Expand Down Expand Up @@ -986,9 +968,21 @@ impl PlanePass {
fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
use windows::core::s;
let device = &host().ok_or_else(windows::core::Error::empty)?.device;
let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
let prebuilt_ps = if steps { crate::prebuilt::PLANE_STEPS } else { crate::prebuilt::PLANE_FLOATS };
let compiled = compile(PLANE_CORNERS, s!("main"), s!("vs_5_1"))
.and_then(|vs| compile(source, s!("main"), s!("ps_5_1")).map(|ps| (vs, ps)));
let (vs, ps) = match compiled {
// SAFETY: the pixel shader's own bytes.
Ok((vs, ps)) if prebuilt_ps.is_empty() || unsafe { device.CreateRootSignature::<ID3D12RootSignature>(0, &ps[..]) }.is_ok() => (vs, ps),
// Wine's D3DCompile builds no root signature into the pixel
// shader, or no shader: use the bytecode `build.rs` made with dxc.
Err(e) if prebuilt_ps.is_empty() => return Err(e),
_ => {
tracing::warn!("depth plane pass: the system compiler gave no usable shaders; using the DXIL built with dxc");
(crate::prebuilt::PLANE_CORNER.to_vec(), prebuilt_ps.to_vec())
}
};
let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
Expand Down Expand Up @@ -1466,47 +1460,7 @@ static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
/// gets a dword per piece, 1 where a byte differs. The offsets are widened
/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
/// byte just outside the range costs a fetch that finds nothing.
pub(crate) const CARD_COMPARE: &str = r#"
#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
cbuffer Span : register(b0) {
uint first; // the first piece
uint skew; // where the copy starts in its piece 0
uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
uint pieces;
uint out_at; // the first piece's dword in `differs`, in bytes
uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
};
ByteAddressBuffer now : register(t0);
// 16 bytes per piece of the copy: the hash of its bytes when they were
// last sent up (or hashed whole, the first time).
RWByteAddressBuffer hashes : register(u0);
RWByteAddressBuffer differs : register(u1);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= pieces) return;
uint piece = first + id.x;
uint lo = piece * 65536u;
lo = lo > skew ? lo - skew : 0u;
uint hi = min((piece + 1u) * 65536u - skew, size);
lo = lo & ~15u;
hi = (hi + 15u) & ~15u;
uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu);
[loop]
for (uint at = lo; at < hi; at += 16u) {
h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
h = h.yzwx ^ (h >> 15);
}
if (compare != 0u) {
differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u);
// With the copy-back on its own thread: the next compare of the
// piece finds what is written from here on.
if (compare == 2u) hashes.Store4(piece * 16u, h);
} else {
hashes.Store4(piece * 16u, h);
}
}
"#;
pub(crate) const CARD_COMPARE: &str = include_str!("shaders/card-compare.hlsl");

/// Whether the pieces hashed again after ranges were sent up to a copy in
/// the card's memory are hashed in runs of pieces that touch, each piece
Expand Down Expand Up @@ -2927,7 +2881,7 @@ impl Host {
let mut code: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; the out
// pointer is ours.
unsafe {
let compiled = unsafe {
D3DCompile(
CARD_COMPARE.as_ptr().cast(),
CARD_COMPARE.len(),
Expand All @@ -2940,9 +2894,21 @@ impl Host {
0,
&mut code,
None,
)?;
}
let code = code.ok_or_else(windows::core::Error::empty)?;
)
};
// Wine's D3DCompile does not build it: use the bytecode `build.rs`
// made with dxc, when there is some.
let compiled_bytes: Vec<u8> = match (compiled, code) {
// SAFETY: the blob's own bytes.
(Ok(()), Some(code)) => unsafe {
std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()).to_vec()
},
(Err(e), _) if crate::prebuilt::CARD_COMPARE.is_empty() => return Err(e),
_ => {
tracing::warn!("card compare: the system compiler failed; using the DXIL built with dxc");
crate::prebuilt::CARD_COMPARE.to_vec()
}
};
let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
// A megabyte of results: 262,144 pieces, 16 GB of declared ranges
// in one submission.
Expand All @@ -2952,7 +2918,7 @@ impl Host {
// SAFETY: the blob's own bytes; the root signature is inside the
// shader.
unsafe {
let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
let bytes = &compiled_bytes[..];
let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
Expand Down
142 changes: 16 additions & 126 deletions crates/victory-gpu/src/indirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,128 +27,7 @@ use windows::core::s;

use crate::host::{HostList, host, transition};

const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
cbuffer Record : register(b0) {
uint kind;
uint stride;
uint records;
uint args_offset;
// Bit 0: a count buffer bounds the records. Bit 1: the records are a
// window clamped ahead of their draws: one that asks for more than can
// run is left empty and costs nothing. Bit 2: one dispatch, written as
// SPLIT records of at most 65,535 groups in x each.
uint has_count;
uint count_offset;
};
ByteAddressBuffer src_args : register(t0);
ByteAddressBuffer count_buf : register(t1);
RWByteAddressBuffer dst_args : register(u0);
// The list's work so far (vertex instances, threads): past the budget,
// records run empty.
RWByteAddressBuffer budget : register(u1);
static const uint BUDGET = 1u << 27;
// Groups of one dispatch; more run empty.
static const uint GROUPS = 1u << 20;
static const uint SPLIT = 2;
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
uint eff_count = records;
bool ahead = (has_count & 2u) != 0;
bool split = (has_count & 4u) != 0;
if ((has_count & 1u) != 0) {
eff_count = min(eff_count, count_buf.Load(count_offset));
}
if (id.x >= eff_count) return;
uint src_at = args_offset + id.x * stride;
uint dst_at = id.x * stride;
uint cost;
uint2 draw_counts = uint2(0, 0);
uint3 groups = uint3(0, 0, 0);
if (kind <= 1) {
// Draws: vertex or index count, then instances.
uint2 asked = src_args.Load2(src_at);
if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) {
asked = uint2(0, 0);
}
uint count = min(asked.x, 1u << 24);
uint instances = min(asked.y, (1u << 26) / max(count, 1u));
cost = count * instances;
draw_counts = uint2(count, instances);
} else if (kind == 2) {
uint3 asked = src_args.Load3(src_at);
uint3 g = min(asked, uint3(65535u, 65535u, 65535u));
// In parts: one dimension, and not the garbage of an argument
// nothing wrote.
if (split && g.y <= 1u && g.z <= 1u && asked.x <= SPLIT * 65535u) {
g.x = asked.x;
}
// x * y fits 32 bits; the whole count may not.
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
g = uint3(0, 0, 0);
}
cost = g.x * g.y * g.z * 64u;
groups = g;
} else {
// Mesh dispatches: the console's are one-dimensional.
uint3 g = src_args.Load3(src_at);
// Ahead of its draw, a record over the most a dispatch runs is a
// slot the title has not filled (the title leaves all
// ones there): empty, and not counted below either.
if (ahead && g.x > 65535u) {
g = uint3(0, 0, 0);
}
// Diagnostics, in the budget buffer's next words: the largest
// group count a mesh record asked for, and the groups asked in all.
uint was;
budget.InterlockedMax(4, g.x, was);
budget.InterlockedAdd(8, min(g.x, 1u << 24), was);
g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
cost = g.x * g.y * g.z * 128u;
groups = g;
}
bool over = false;
if (cost > 0) {
uint before;
budget.InterlockedOr(0, 0, before);
[allow_uav_condition]
while (before < BUDGET) {
uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost);
uint prev;
budget.InterlockedCompareExchange(0, before, next, prev);
if (prev == before) break;
before = prev;
}
over = before >= BUDGET || BUDGET - before < cost;
}
if (kind <= 1) {
if (over) {
draw_counts = uint2(0, 0);
}
dst_args.Store2(dst_at, draw_counts);
for (uint off = 8; off < stride; off += 4) {
dst_args.Store(dst_at + off, src_args.Load(src_at + off));
}
} else {
if (over) {
groups = uint3(0, 0, 0);
}
if (split) {
for (uint part = 0; part < SPLIT; part++) {
uint before = part * 65535u;
uint x = groups.x > before ? min(groups.x - before, 65535u) : 0u;
dst_args.Store3(dst_at + part * 12u, uint3(x, groups.yz));
}
return;
}
dst_args.Store3(dst_at, groups);
for (uint off = 12; off < stride; off += 4) {
dst_args.Store(dst_at + off, src_args.Load(src_at + off));
}
}
}
"#;
const SOURCE: &str = include_str!("shaders/clamp.hlsl");

struct Clamp {
root: ID3D12RootSignature,
Expand Down Expand Up @@ -208,13 +87,24 @@ fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
};
tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
}
return Err(e);
// Wine's D3DCompile (vkd3d-shader) does not build it: use the
// bytecode `build.rs` made with dxc, when there is some.
if crate::prebuilt::CLAMP.is_empty() {
return Err(e);
}
tracing::warn!(error = %e, "argument clamp: the system compiler failed; using the DXIL built with dxc");
return with_code(device, crate::prebuilt::CLAMP);
}
let code = code.ok_or_else(windows::core::Error::empty)?;
// SAFETY: the blob's own bytes; the root signature is inside the shader.
// SAFETY: the blob's own bytes.
with_code(device, unsafe {
std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
})
}

fn with_code(device: &ID3D12Device, bytes: &[u8]) -> windows::core::Result<Clamp> {
// SAFETY: live bytes; the root signature is inside the shader.
unsafe {
let bytes =
std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
Expand Down
1 change: 1 addition & 0 deletions crates/victory-gpu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub mod list;
pub mod object;
pub mod pipeline;
#[cfg(windows)]
mod prebuilt;
mod primitive;
pub mod query;
pub mod queue;
Expand Down
Loading