Merge branch 'day/shaders' into local/next
This commit is contained in:
commit
5aba66bced
16 files changed
+1146
-43
No files matched your search
@@ -2003,8 +2003,37 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
|
||||
lo = lo & ~15u;
|
||||
hi = (hi + 15u) & ~15u;
|
||||
uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
|
||||
uint at = lo + thread * 16u;
|
||||
// Eight loads at once: one after the other, each waits for memory.
|
||||
[loop]
|
||||
for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
|
||||
for (; at + 7168u < hi; at += 8192u) {
|
||||
uint4 v0 = now.Load4(at + 0u);
|
||||
uint4 v1 = now.Load4(at + 1024u);
|
||||
uint4 v2 = now.Load4(at + 2048u);
|
||||
uint4 v3 = now.Load4(at + 3072u);
|
||||
uint4 v4 = now.Load4(at + 4096u);
|
||||
uint4 v5 = now.Load4(at + 5120u);
|
||||
uint4 v6 = now.Load4(at + 6144u);
|
||||
uint4 v7 = now.Load4(at + 7168u);
|
||||
h = (h ^ v0) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v1) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v2) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v3) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v4) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v5) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v6) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
h = (h ^ v7) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
}
|
||||
[loop]
|
||||
for (; at < hi; at += 1024u) {
|
||||
h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
}
|
||||
|
||||
@@ -566,6 +566,8 @@ fn hand_out(
|
||||
#[cfg(windows)]
|
||||
let host = Arc::new(make::Pending::new(shaders.clone(), graphics));
|
||||
#[cfg(windows)]
|
||||
known::note(host.key(), &shaders, host.graphics.as_deref());
|
||||
#[cfg(windows)]
|
||||
make::early(&host);
|
||||
#[cfg(windows)]
|
||||
let builder = of_builder(&shaders);
|
||||
@@ -753,6 +755,8 @@ static FUNCTIONS: Table<24> = {
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod host;
|
||||
#[cfg(windows)]
|
||||
pub mod known;
|
||||
#[cfg(windows)]
|
||||
mod library;
|
||||
#[cfg(windows)]
|
||||
mod make;
|
||||
|
||||
@@ -20,19 +20,19 @@ use crate::host::host;
|
||||
/// A stream's graphics state, owned (the title's stream lives only for the
|
||||
/// creation call). Subobjects the stream leaves out keep D3D12's defaults.
|
||||
pub(crate) struct GraphicsState {
|
||||
blend: D3D12_BLEND_DESC,
|
||||
sample_mask: u32,
|
||||
rasterizer: D3D12_RASTERIZER_DESC,
|
||||
depth: D3D12_DEPTH_STENCIL_DESC,
|
||||
depth_bounds: bool,
|
||||
pub(super) blend: D3D12_BLEND_DESC,
|
||||
pub(super) sample_mask: u32,
|
||||
pub(super) rasterizer: D3D12_RASTERIZER_DESC,
|
||||
pub(super) depth: D3D12_DEPTH_STENCIL_DESC,
|
||||
pub(super) depth_bounds: bool,
|
||||
/// Input elements, their names pointing into `names`.
|
||||
inputs: Vec<D3D12_INPUT_ELEMENT_DESC>,
|
||||
names: Vec<CString>,
|
||||
strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
|
||||
pub(super) inputs: Vec<D3D12_INPUT_ELEMENT_DESC>,
|
||||
pub(super) names: Vec<CString>,
|
||||
pub(super) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
|
||||
pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
pub(crate) targets: D3D12_RT_FORMAT_ARRAY,
|
||||
depth_format: DXGI_FORMAT,
|
||||
samples: DXGI_SAMPLE_DESC,
|
||||
pub(super) depth_format: DXGI_FORMAT,
|
||||
pub(super) samples: DXGI_SAMPLE_DESC,
|
||||
}
|
||||
|
||||
impl Default for GraphicsState {
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Every pipeline the title has ever created, kept on disk
|
||||
//! (`VICTORY_PIPELINE_BOOK=1`), and their host pipelines made ahead of a run
|
||||
//! (`victory warm`), so that the driver's own cache on disk has them before
|
||||
//! a draw asks for one.
|
||||
//!
|
||||
//! The title creates 84,000 pipelines while it loads and draws with some
|
||||
//! 2,000 of them; which ones is known from earlier runs (`library`), and
|
||||
//! those are made during loading. One met for the first time (a place never
|
||||
//! seen, or everything after a change of the translator or of the driver) is
|
||||
//! compiled when a draw wants it. Making all of them in the running title
|
||||
//! (`VICTORY_EARLY_ALL=1`) ended it inside the driver's compiler; made here,
|
||||
//! a compiler that crashes or hangs ends a child process, costs that pipeline
|
||||
//! alone and is named in `warm-bad.txt`.
|
||||
//!
|
||||
//! Two files beside the library, both only ever added to (a torn end is cut
|
||||
//! off): `known-shaders.bin` (stage, hash, length, container) and
|
||||
//! `known-pipelines.bin` (length, then the key, the shaders' stages and
|
||||
//! hashes, and the graphics state). They hold the title's own code: they stay
|
||||
//! in the cache folder.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::CString;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::core::PCSTR;
|
||||
|
||||
use super::Shader;
|
||||
use super::host::{GraphicsState, HostPipeline};
|
||||
|
||||
const SHADERS: &str = "known-shaders.bin";
|
||||
const PIPELINES: &str = "known-pipelines.bin";
|
||||
/// Stages by their number in the files.
|
||||
const STAGES: [&str; 8] =
|
||||
["vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"];
|
||||
|
||||
/// `VICTORY_PIPELINE_BOOK=1`: the pipelines the title creates are kept.
|
||||
fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_BOOK").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
struct Book {
|
||||
dir: PathBuf,
|
||||
keys: HashSet<[u8; 16]>,
|
||||
shaders: HashSet<[u8; 32]>,
|
||||
/// Not yet written: shaders, then pipelines.
|
||||
new: [Vec<u8>; 2],
|
||||
added: usize,
|
||||
}
|
||||
|
||||
static BOOK: OnceLock<Option<Mutex<Book>>> = OnceLock::new();
|
||||
|
||||
fn book() -> Option<&'static Mutex<Book>> {
|
||||
BOOK.get_or_init(|| {
|
||||
let dir = super::library::folder().filter(|_| on())?;
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let mut keys = HashSet::new();
|
||||
let mut shaders = HashSet::new();
|
||||
let ends = [
|
||||
walk_shaders(&dir, |_, hash, _, _| drop(shaders.insert(hash))),
|
||||
walk_pipelines(&dir, |_, bytes| {
|
||||
keys.extend(bytes.first_chunk::<16>().copied());
|
||||
}),
|
||||
];
|
||||
for (file, end) in [SHADERS, PIPELINES].iter().zip(ends) {
|
||||
let path = dir.join(file);
|
||||
if std::fs::metadata(&path).is_ok_and(|m| m.len() > end)
|
||||
&& let Ok(f) = std::fs::OpenOptions::new().write(true).open(&path)
|
||||
{
|
||||
let _ = f.set_len(end);
|
||||
}
|
||||
}
|
||||
tracing::info!(pipelines = keys.len(), shaders = shaders.len(), "title pipelines known from earlier runs");
|
||||
let spawned = std::thread::Builder::new().name("victory-known".into()).spawn(|| {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
flush();
|
||||
}
|
||||
});
|
||||
spawned.ok()?;
|
||||
Some(Mutex::new(Book { dir, keys, shaders, new: Default::default(), added: 0 }))
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The title created a pipeline.
|
||||
pub(super) fn note(key: &str, shaders: &[Arc<Shader>], graphics: Option<&GraphicsState>) {
|
||||
let Some(book) = book() else { return };
|
||||
let mut id = [0u8; 16];
|
||||
for (at, b) in id.iter_mut().enumerate() {
|
||||
*b = key.get(2 * at..2 * at + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).unwrap_or(0);
|
||||
}
|
||||
let mut book = book.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if shaders.is_empty() || !book.keys.insert(id) {
|
||||
return;
|
||||
}
|
||||
let mut entry = id.to_vec();
|
||||
entry.push(shaders.len() as u8);
|
||||
for s in shaders {
|
||||
let hash = *blake3::hash(&s.container).as_bytes();
|
||||
let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u8;
|
||||
entry.push(stage);
|
||||
entry.extend(hash);
|
||||
if book.shaders.insert(hash) {
|
||||
let new = &mut book.new[0];
|
||||
new.push(stage);
|
||||
new.extend(hash);
|
||||
new.extend((s.container.len() as u32).to_le_bytes());
|
||||
new.extend(&s.container);
|
||||
}
|
||||
}
|
||||
entry.push(u8::from(graphics.is_some()));
|
||||
if let Some(g) = graphics {
|
||||
g.put(&mut entry);
|
||||
}
|
||||
book.new[1].extend((entry.len() as u32).to_le_bytes());
|
||||
book.new[1].extend(entry);
|
||||
book.added += 1;
|
||||
}
|
||||
|
||||
/// Writes what was noted.
|
||||
fn flush() {
|
||||
let Some(Some(book)) = BOOK.get() else { return };
|
||||
let (dir, new, added) = {
|
||||
let mut book = book.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if book.added == 0 {
|
||||
return;
|
||||
}
|
||||
(book.dir.clone(), std::mem::take(&mut book.new), std::mem::take(&mut book.added))
|
||||
};
|
||||
for (file, bytes) in [SHADERS, PIPELINES].iter().zip(&new) {
|
||||
let written = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(dir.join(file))
|
||||
.and_then(|mut f| f.write_all(bytes));
|
||||
if let Err(e) = written {
|
||||
tracing::warn!(error = %e, file, "title pipelines not written down");
|
||||
return;
|
||||
}
|
||||
}
|
||||
tracing::info!(pipelines = added, "title pipelines written down");
|
||||
}
|
||||
|
||||
/// Calls `f` with each container's stage, hash, place and length; where the
|
||||
/// last whole one ends.
|
||||
fn walk_shaders(dir: &Path, mut f: impl FnMut(u8, [u8; 32], u64, u32)) -> u64 {
|
||||
let Ok(file) = std::fs::File::open(dir.join(SHADERS)) else { return 0 };
|
||||
let len = file.metadata().map_or(0, |m| m.len());
|
||||
let mut file = std::io::BufReader::new(file);
|
||||
let mut at = 0;
|
||||
let mut head = [0u8; 37];
|
||||
while file.read_exact(&mut head).is_ok() {
|
||||
let size = u32::from_le_bytes([head[33], head[34], head[35], head[36]]);
|
||||
if at + 37 + u64::from(size) > len || file.seek_relative(i64::from(size)).is_err() {
|
||||
break;
|
||||
}
|
||||
let mut hash = [0; 32];
|
||||
hash.copy_from_slice(&head[1..33]);
|
||||
f(head[0], hash, at + 37, size);
|
||||
at += 37 + u64::from(size);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// Calls `f` with each pipeline's number and entry; where the last whole one
|
||||
/// ends.
|
||||
fn walk_pipelines(dir: &Path, mut f: impl FnMut(usize, &[u8])) -> u64 {
|
||||
let bytes = std::fs::read(dir.join(PIPELINES)).unwrap_or_default();
|
||||
let (mut at, mut n) = (0, 0);
|
||||
while let Some(head) = bytes.get(at..at + 4) {
|
||||
let size = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
|
||||
let Some(entry) = bytes.get(at + 4..at + 4 + size) else { break };
|
||||
f(n, entry);
|
||||
(at, n) = (at + 4 + size, n + 1);
|
||||
}
|
||||
at as u64
|
||||
}
|
||||
|
||||
/// How many pipelines are known in `dir`.
|
||||
pub fn count(dir: &Path) -> usize {
|
||||
let mut n = 0;
|
||||
walk_pipelines(dir, |_, _| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// The key of each pipeline known in `dir`, as the early list has it.
|
||||
pub fn keys(dir: &Path) -> Vec<String> {
|
||||
let mut all = Vec::new();
|
||||
walk_pipelines(dir, |_, e| {
|
||||
all.push(e.get(..16).unwrap_or_default().iter().map(|b| format!("{b:02x}")).collect());
|
||||
});
|
||||
all
|
||||
}
|
||||
|
||||
/// What a driver's cached pipelines depend on besides the title's: the
|
||||
/// translator with its settings, and the driver.
|
||||
pub fn fingerprint() -> String {
|
||||
let mut h = blake3::Hasher::new();
|
||||
h.update(&crate::shader_cache::translation());
|
||||
if let Some(host) = crate::host::host() {
|
||||
h.update(&host.driver().to_le_bytes());
|
||||
}
|
||||
h.finalize().to_hex()[..16].to_owned()
|
||||
}
|
||||
|
||||
/// The translations of earlier runs are in `dir` (the pipeline library is
|
||||
/// not used: what is made here is the driver's to keep).
|
||||
pub fn use_translations(dir: PathBuf) {
|
||||
crate::shader_cache::use_shader_cache(dir);
|
||||
}
|
||||
|
||||
/// Makes the host pipelines of those of `which` (numbers in the file) and
|
||||
/// lets each go again: the driver's cache on disk keeps them. `each` is told
|
||||
/// the number before, and what came of it after: milliseconds and whether
|
||||
/// there is one.
|
||||
pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64, bool)>)) {
|
||||
let mut places = HashMap::new();
|
||||
walk_shaders(dir, |stage, hash, at, len| drop(places.insert(hash, (stage, at, len))));
|
||||
let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { return };
|
||||
let wanted: HashSet<usize> = which.iter().copied().collect();
|
||||
let mut entries = HashMap::new();
|
||||
walk_pipelines(dir, |n, bytes| {
|
||||
if wanted.contains(&n) {
|
||||
entries.insert(n, bytes.to_vec());
|
||||
}
|
||||
});
|
||||
let mut read = |hash: &[u8; 32]| {
|
||||
let &(_, at, len) = places.get(hash)?;
|
||||
let mut bytes = vec![0; len as usize];
|
||||
file.seek(SeekFrom::Start(at)).ok()?;
|
||||
file.read_exact(&mut bytes).ok()?;
|
||||
Some(bytes)
|
||||
};
|
||||
for n in which {
|
||||
let Some(entry) = entries.get(n) else { continue };
|
||||
each(*n, None);
|
||||
let began = std::time::Instant::now();
|
||||
let made = parse(entry, &mut read)
|
||||
.and_then(|(shaders, g)| HostPipeline::new(&shaders, g.as_deref()))
|
||||
.is_some();
|
||||
each(*n, Some((began.elapsed().as_secs_f64() * 1e3, made)));
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn parse(
|
||||
entry: &[u8],
|
||||
read: &mut impl FnMut(&[u8; 32]) -> Option<Vec<u8>>,
|
||||
) -> Option<(Vec<Arc<Shader>>, Option<Box<GraphicsState>>)> {
|
||||
let mut rest = entry.get(16..)?;
|
||||
let (&count, after) = rest.split_first()?;
|
||||
rest = after;
|
||||
let mut shaders = Vec::new();
|
||||
for _ in 0..count {
|
||||
let (head, after) = rest.split_first_chunk::<33>()?;
|
||||
rest = after;
|
||||
let mut hash = [0; 32];
|
||||
hash.copy_from_slice(&head[1..]);
|
||||
shaders.push(super::shader(STAGES.get(usize::from(head[0]))?, &read(&hash)?));
|
||||
}
|
||||
let (&graphics, rest) = rest.split_first()?;
|
||||
let g = match graphics {
|
||||
0 => None,
|
||||
_ => Some(Box::new(GraphicsState::get(rest)?)),
|
||||
};
|
||||
Some((shaders, g))
|
||||
}
|
||||
|
||||
/// Calls `$f` with each number of a graphics state but its input elements',
|
||||
/// as a place of 32 bits, in one order.
|
||||
macro_rules! numbers {
|
||||
($g:expr, $f:ident) => {{
|
||||
$f!($g.blend.AlphaToCoverageEnable.0);
|
||||
$f!($g.blend.IndependentBlendEnable.0);
|
||||
for t in &mut $g.blend.RenderTarget {
|
||||
$f!(t.BlendEnable.0);
|
||||
$f!(t.LogicOpEnable.0);
|
||||
$f!(t.SrcBlend.0);
|
||||
$f!(t.DestBlend.0);
|
||||
$f!(t.BlendOp.0);
|
||||
$f!(t.SrcBlendAlpha.0);
|
||||
$f!(t.DestBlendAlpha.0);
|
||||
$f!(t.BlendOpAlpha.0);
|
||||
$f!(t.LogicOp.0);
|
||||
$f!(t.RenderTargetWriteMask);
|
||||
}
|
||||
$f!($g.sample_mask);
|
||||
$f!($g.rasterizer.FillMode.0);
|
||||
$f!($g.rasterizer.CullMode.0);
|
||||
$f!($g.rasterizer.FrontCounterClockwise.0);
|
||||
$f!($g.rasterizer.DepthBias);
|
||||
$f!($g.rasterizer.DepthClipEnable.0);
|
||||
$f!($g.rasterizer.MultisampleEnable.0);
|
||||
$f!($g.rasterizer.AntialiasedLineEnable.0);
|
||||
$f!($g.rasterizer.ForcedSampleCount);
|
||||
$f!($g.rasterizer.ConservativeRaster.0);
|
||||
$f!($g.depth.DepthEnable.0);
|
||||
$f!($g.depth.DepthWriteMask.0);
|
||||
$f!($g.depth.DepthFunc.0);
|
||||
$f!($g.depth.StencilEnable.0);
|
||||
$f!($g.depth.StencilReadMask);
|
||||
$f!($g.depth.StencilWriteMask);
|
||||
for face in [&mut $g.depth.FrontFace, &mut $g.depth.BackFace] {
|
||||
$f!(face.StencilFailOp.0);
|
||||
$f!(face.StencilDepthFailOp.0);
|
||||
$f!(face.StencilPassOp.0);
|
||||
$f!(face.StencilFunc.0);
|
||||
}
|
||||
$f!($g.strip_cut.0);
|
||||
$f!($g.topology.0);
|
||||
$f!($g.targets.NumRenderTargets);
|
||||
for format in &mut $g.targets.RTFormats {
|
||||
$f!(format.0);
|
||||
}
|
||||
$f!($g.depth_format.0);
|
||||
$f!($g.samples.Count);
|
||||
$f!($g.samples.Quality);
|
||||
}};
|
||||
}
|
||||
|
||||
impl GraphicsState {
|
||||
/// The state as bytes.
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
out.push(u8::from(self.depth_bounds));
|
||||
for f in [self.rasterizer.DepthBiasClamp, self.rasterizer.SlopeScaledDepthBias] {
|
||||
out.extend(f.to_le_bytes());
|
||||
}
|
||||
let mut plain = GraphicsState {
|
||||
blend: self.blend,
|
||||
sample_mask: self.sample_mask,
|
||||
rasterizer: self.rasterizer,
|
||||
depth: self.depth,
|
||||
strip_cut: self.strip_cut,
|
||||
topology: self.topology,
|
||||
targets: self.targets,
|
||||
depth_format: self.depth_format,
|
||||
samples: self.samples,
|
||||
..Default::default()
|
||||
};
|
||||
macro_rules! write {
|
||||
($x:expr) => {
|
||||
out.extend(($x as u32).to_le_bytes())
|
||||
};
|
||||
}
|
||||
numbers!(plain, write);
|
||||
out.push(self.inputs.len() as u8);
|
||||
for (e, name) in self.inputs.iter().zip(&self.names) {
|
||||
let name = name.as_bytes();
|
||||
out.push(name.len() as u8);
|
||||
out.extend(name);
|
||||
for v in [
|
||||
e.SemanticIndex,
|
||||
e.Format.0 as u32,
|
||||
e.InputSlot,
|
||||
e.AlignedByteOffset,
|
||||
e.InputSlotClass.0 as u32,
|
||||
e.InstanceDataStepRate,
|
||||
] {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get(bytes: &[u8]) -> Option<GraphicsState> {
|
||||
let mut g = GraphicsState::default();
|
||||
let (&bounds, mut rest) = bytes.split_first()?;
|
||||
g.depth_bounds = bounds != 0;
|
||||
let mut next = || {
|
||||
let (head, after) = rest.split_first_chunk::<4>()?;
|
||||
rest = after;
|
||||
Some(u32::from_le_bytes(*head))
|
||||
};
|
||||
g.rasterizer.DepthBiasClamp = f32::from_bits(next()?);
|
||||
g.rasterizer.SlopeScaledDepthBias = f32::from_bits(next()?);
|
||||
macro_rules! read {
|
||||
($x:expr) => {
|
||||
$x = next()? as _
|
||||
};
|
||||
}
|
||||
numbers!(g, read);
|
||||
let (&count, mut rest) = rest.split_first()?;
|
||||
let mut elements = Vec::new();
|
||||
for _ in 0..count {
|
||||
let (&len, after) = rest.split_first()?;
|
||||
let (name, after) = after.split_at_checked(usize::from(len))?;
|
||||
let (numbers, after) = after.split_first_chunk::<24>()?;
|
||||
rest = after;
|
||||
let mut v = [0u32; 6];
|
||||
for (v, b) in v.iter_mut().zip(numbers.chunks_exact(4)) {
|
||||
*v = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
|
||||
}
|
||||
elements.push((CString::new(name).ok()?, v));
|
||||
}
|
||||
g.names = elements.iter().map(|e| e.0.clone()).collect();
|
||||
g.inputs = g
|
||||
.names
|
||||
.iter()
|
||||
.zip(&elements)
|
||||
.map(|(name, (_, v))| D3D12_INPUT_ELEMENT_DESC {
|
||||
SemanticName: PCSTR(name.as_ptr().cast()),
|
||||
SemanticIndex: v[0],
|
||||
Format: DXGI_FORMAT(v[1] as i32),
|
||||
InputSlot: v[2],
|
||||
AlignedByteOffset: v[3],
|
||||
InputSlotClass: D3D12_INPUT_CLASSIFICATION(v[4] as i32),
|
||||
InstanceDataStepRate: v[5],
|
||||
})
|
||||
.collect();
|
||||
Some(g)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_state_comes_back_as_it_was() {
|
||||
let mut g = GraphicsState { sample_mask: 7, depth_bounds: true, ..Default::default() };
|
||||
g.rasterizer.DepthBias = -3;
|
||||
g.rasterizer.SlopeScaledDepthBias = 1.25;
|
||||
g.blend.RenderTarget[3].RenderTargetWriteMask = 5;
|
||||
g.depth.StencilReadMask = 9;
|
||||
g.targets.NumRenderTargets = 2;
|
||||
g.targets.RTFormats[1] = DXGI_FORMAT_R8_UNORM;
|
||||
g.depth_format = DXGI_FORMAT_D32_FLOAT;
|
||||
g.names = vec![CString::new("POSITION").unwrap(), CString::new("T").unwrap()];
|
||||
g.inputs = g
|
||||
.names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, name)| D3D12_INPUT_ELEMENT_DESC {
|
||||
SemanticName: PCSTR(name.as_ptr().cast()),
|
||||
SemanticIndex: n as u32,
|
||||
Format: DXGI_FORMAT_R32G32_FLOAT,
|
||||
InputSlot: 2,
|
||||
AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT,
|
||||
InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
|
||||
InstanceDataStepRate: 4,
|
||||
})
|
||||
.collect();
|
||||
let mut bytes = Vec::new();
|
||||
g.put(&mut bytes);
|
||||
let back = GraphicsState::get(&bytes).expect("whole");
|
||||
assert_eq!(back.describe(), g.describe());
|
||||
assert!(GraphicsState::get(&bytes[..bytes.len() - 1]).is_none());
|
||||
assert!(GraphicsState::get(&bytes[..9]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_end_is_not_read() {
|
||||
let dir = std::env::temp_dir().join(format!("victory-known-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
for n in 0..3u8 {
|
||||
bytes.extend(20u32.to_le_bytes());
|
||||
bytes.extend([n; 20]);
|
||||
}
|
||||
std::fs::write(dir.join(PIPELINES), &bytes[..bytes.len() - 5]).unwrap();
|
||||
assert_eq!(count(&dir), 2);
|
||||
assert_eq!(keys(&dir)[1], "01".repeat(16));
|
||||
assert_eq!(walk_pipelines(&dir, |_, _| ()), 48);
|
||||
let mut shader = vec![5u8];
|
||||
shader.extend([9; 32]);
|
||||
shader.extend(4u32.to_le_bytes());
|
||||
shader.extend([1, 2, 3, 4]);
|
||||
let one = shader.len() as u64;
|
||||
shader.extend_from_slice(&shader.clone()[..20]);
|
||||
std::fs::write(dir.join(SHADERS), &shader).unwrap();
|
||||
let mut seen = Vec::new();
|
||||
assert_eq!(walk_shaders(&dir, |stage, hash, at, len| seen.push((stage, hash[0], at, len))), one);
|
||||
assert_eq!(seen, [(5, 9, 37, 4)]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,11 @@ pub fn use_pipeline_cache(dir: PathBuf) {
|
||||
let _ = DIR.set(dir);
|
||||
}
|
||||
|
||||
/// The folder the library is kept in.
|
||||
pub(super) fn folder() -> Option<PathBuf> {
|
||||
DIR.get().cloned()
|
||||
}
|
||||
|
||||
/// Host pipelines created, loaded from the library, and title pipelines
|
||||
/// started at creation, since the start.
|
||||
pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
|
||||
@@ -628,7 +633,9 @@ pub(crate) fn save(now: bool) {
|
||||
)
|
||||
});
|
||||
}
|
||||
let slow: Vec<String> = slow_ones().iter().flatten().map(|(key, ms)| format!("{key} {ms}")).collect();
|
||||
let written = library_written
|
||||
.and_then(|()| write_atomically(&dir.join(SLOW_FILE), slow.join("\n").as_bytes()))
|
||||
.and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
|
||||
match written {
|
||||
Ok(()) => tracing::info!(
|
||||
@@ -691,6 +698,48 @@ fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()>
|
||||
res
|
||||
}
|
||||
|
||||
/// How long each title pipeline that took long to make took, in ms (beside
|
||||
/// the early list; a key may be there more than once).
|
||||
const SLOW_FILE: &str = "slow-pipelines.txt";
|
||||
/// A pipeline that takes this long is one ([`slow`]).
|
||||
pub(crate) const SLOW_MS: u64 = 1000;
|
||||
static SLOW: Mutex<Option<std::collections::HashMap<String, u64>>> = Mutex::new(None);
|
||||
|
||||
fn slow_ones() -> std::sync::MutexGuard<'static, Option<std::collections::HashMap<String, u64>>> {
|
||||
let mut slow = SLOW.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if slow.is_none() {
|
||||
let listed = DIR.get().and_then(|d| std::fs::read_to_string(d.join(SLOW_FILE)).ok()).unwrap_or_default();
|
||||
*slow = Some(
|
||||
listed
|
||||
.lines()
|
||||
.filter_map(|l| l.split_once(' '))
|
||||
.filter_map(|(key, ms)| Some((key.to_owned(), ms.parse().ok()?)))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
slow
|
||||
}
|
||||
|
||||
/// Whether making the title pipeline with `key` took [`SLOW_MS`] in this or
|
||||
/// an earlier run.
|
||||
pub(crate) fn slow(key: &str) -> bool {
|
||||
slow_ones().as_ref().is_some_and(|s| s.contains_key(key))
|
||||
}
|
||||
|
||||
/// The title pipeline with `key` took `ms` to make.
|
||||
pub(crate) fn note_time(key: &str, ms: u64) {
|
||||
if ms < SLOW_MS {
|
||||
return;
|
||||
}
|
||||
let mut slow = slow_ones();
|
||||
let known = slow.get_or_insert_default().entry(key.to_owned()).or_insert(0);
|
||||
if ms > *known {
|
||||
*known = ms;
|
||||
// With the next save of the early list.
|
||||
USED_CHANGED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Title pipeline keys requested by draws or dispatches (this run and the last).
|
||||
static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
|
||||
static USED_CHANGED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
@@ -34,6 +34,8 @@ pub(crate) struct Pending {
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
pub(crate) graphics: Option<Box<GraphicsState>>,
|
||||
queue_state: AtomicU8,
|
||||
/// Taken by a worker from [`Queue::slow`].
|
||||
was_slow: AtomicBool,
|
||||
made: OnceLock<Option<HostPipeline>>,
|
||||
/// What identifies it across runs (shader containers and state), and
|
||||
/// whether a draw or dispatch has requested it yet.
|
||||
@@ -62,15 +64,24 @@ impl Pending {
|
||||
shaders,
|
||||
graphics,
|
||||
queue_state: AtomicU8::new(NOT_QUEUED),
|
||||
was_slow: AtomicBool::new(false),
|
||||
made: OnceLock::new(),
|
||||
key: key.finalize().to_hex()[..32].to_owned(),
|
||||
used: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn key(&self) -> &str {
|
||||
&self.key
|
||||
}
|
||||
|
||||
fn make(&self) {
|
||||
self.made
|
||||
.get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref()));
|
||||
self.made.get_or_init(|| {
|
||||
let began = Instant::now();
|
||||
let made = HostPipeline::new(&self.shaders, self.graphics.as_deref());
|
||||
super::library::note_time(&self.key, began.elapsed().as_millis() as u64);
|
||||
made
|
||||
});
|
||||
let (lock, done) = &DONE;
|
||||
let _held = lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||
done.notify_all();
|
||||
@@ -258,11 +269,34 @@ const EARLY: u8 = 1;
|
||||
const REQUESTED: u8 = 2;
|
||||
const MAKING: u8 = 3;
|
||||
|
||||
/// How many workers may make pipelines at once that are known to take long
|
||||
/// and that no draw has asked for: a quarter of them. On a fresh cache (a
|
||||
/// change of the translator or the driver) the early list begins with
|
||||
/// programs that take tens of seconds each: all 16 workers were in them
|
||||
/// through the whole of the title's loading, 97 pipelines made in 20 s, and
|
||||
/// the first minute and a half of the world ran at 0.5 to 1.6 s a frame,
|
||||
/// dropping up to 2,900 draws a frame (run shaders-1).
|
||||
/// `VICTORY_PIPELINE_SLOW=0`: in the order the title creates them, as before.
|
||||
fn slow_limit() -> usize {
|
||||
static LIMIT: OnceLock<usize> = OnceLock::new();
|
||||
*LIMIT.get_or_init(|| {
|
||||
if std::env::var_os("VICTORY_PIPELINE_SLOW").is_some_and(|v| v == "0") {
|
||||
usize::MAX
|
||||
} else {
|
||||
(worker_count(None, std::thread::available_parallelism().map_or(2, |n| n.get())) / 4).max(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct Queue {
|
||||
/// Requested passes over the screen: before all others, and the only ones
|
||||
/// [`SCREEN_WORKERS`] take.
|
||||
screen: VecDeque<Arc<Pending>>,
|
||||
early: VecDeque<Arc<Pending>>,
|
||||
/// Those of the early ones known to take long, and how many of them are
|
||||
/// being made ([`slow_limit`]).
|
||||
slow: VecDeque<Arc<Pending>>,
|
||||
slow_now: usize,
|
||||
requested: VecDeque<Arc<Pending>>,
|
||||
}
|
||||
|
||||
@@ -271,6 +305,8 @@ impl Queue {
|
||||
Self {
|
||||
screen: VecDeque::new(),
|
||||
early: VecDeque::new(),
|
||||
slow: VecDeque::new(),
|
||||
slow_now: 0,
|
||||
requested: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
@@ -278,6 +314,10 @@ impl Queue {
|
||||
/// Queues an unrequested pipeline or promotes one queued at creation.
|
||||
/// Returns whether it is new to the queue, or `None` if nothing changed.
|
||||
fn push(&mut self, p: &Arc<Pending>, priority: u8) -> Option<bool> {
|
||||
self.push_as(p, priority, slow_limit() != usize::MAX && super::library::slow(&p.key))
|
||||
}
|
||||
|
||||
fn push_as(&mut self, p: &Arc<Pending>, priority: u8, slow: bool) -> Option<bool> {
|
||||
let prev = p.queue_state.load(Ordering::Relaxed);
|
||||
if prev >= priority {
|
||||
return None;
|
||||
@@ -287,20 +327,29 @@ impl Queue {
|
||||
self.screen.push_back(p.clone());
|
||||
} else if priority == REQUESTED {
|
||||
self.requested.push_back(p.clone());
|
||||
} else if slow {
|
||||
self.slow.push_back(p.clone());
|
||||
} else {
|
||||
self.early.push_back(p.clone());
|
||||
}
|
||||
Some(prev == NOT_QUEUED)
|
||||
}
|
||||
|
||||
fn pop(&mut self, screens_only: bool) -> Option<Arc<Pending>> {
|
||||
fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
let unclaimed = |list: &mut VecDeque<Arc<Pending>>| {
|
||||
std::iter::from_fn(|| list.pop_front()).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
};
|
||||
let mut p = self.screen.pop_front();
|
||||
if p.is_none() && !screens_only {
|
||||
p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
});
|
||||
p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early));
|
||||
if p.is_none() && self.slow_now < slow_limit {
|
||||
p = unclaimed(&mut self.slow);
|
||||
if let Some(p) = &p {
|
||||
p.was_slow.store(true, Ordering::Relaxed);
|
||||
self.slow_now += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let p = p?;
|
||||
p.queue_state.store(MAKING, Ordering::Relaxed);
|
||||
@@ -328,11 +377,9 @@ fn start(p: &Arc<Pending>, priority: u8) {
|
||||
if new {
|
||||
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
if p.screen {
|
||||
AVAILABLE.notify_all();
|
||||
} else {
|
||||
AVAILABLE.notify_one();
|
||||
}
|
||||
// (One woken could be a worker that takes passes over the screen
|
||||
// alone: it would leave the pipeline to nobody.)
|
||||
AVAILABLE.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +389,7 @@ const SCREEN_WORKERS: usize = 2;
|
||||
fn next(screens_only: bool) -> Arc<Pending> {
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if let Some(p) = queue.pop(screens_only) {
|
||||
if let Some(p) = queue.pop(screens_only, slow_limit()) {
|
||||
return p;
|
||||
}
|
||||
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
@@ -388,7 +435,13 @@ fn workers() -> bool {
|
||||
let _ = SetThreadPriority(GetCurrentThread(), priority);
|
||||
}
|
||||
loop {
|
||||
next(screens_only).make();
|
||||
let p = next(screens_only);
|
||||
p.make();
|
||||
if p.was_slow.load(Ordering::Relaxed) {
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
queue.slow_now -= 1;
|
||||
AVAILABLE.notify_all();
|
||||
}
|
||||
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
drained();
|
||||
} else {
|
||||
@@ -478,11 +531,34 @@ mod tests {
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &promoted));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &promoted));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &earlier));
|
||||
assert!(queue.pop(false).is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &earlier));
|
||||
assert!(queue.pop(false, 1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_known_to_take_long_leave_workers_for_the_others() {
|
||||
let new = || Arc::new(Pending::new(Vec::new(), None));
|
||||
let (long, longer, asked, quick) = (new(), new(), new(), new());
|
||||
let mut queue = Queue::new();
|
||||
for p in [&long, &longer, &asked] {
|
||||
assert_eq!(queue.push_as(p, EARLY, true), Some(true));
|
||||
}
|
||||
assert_eq!(queue.push_as(&quick, EARLY, false), Some(true));
|
||||
// The quick one first, then one long one at a time; one a draw asks
|
||||
// for waits for nobody.
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &quick));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &long));
|
||||
assert!(queue.pop(false, 1).is_none());
|
||||
assert_eq!(queue.push_as(&asked, REQUESTED, true), Some(false));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &asked));
|
||||
assert!(!asked.was_slow.load(Ordering::Relaxed));
|
||||
assert!(queue.pop(false, 1).is_none());
|
||||
queue.slow_now -= 1;
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &longer));
|
||||
assert!(queue.pop(false, 1).is_none());
|
||||
}
|
||||
|
||||
/// Passes over the screen go before all others, and workers of their own
|
||||
@@ -498,8 +574,8 @@ mod tests {
|
||||
let mut queue = Queue::new();
|
||||
assert_eq!(queue.push(&world, REQUESTED), Some(true));
|
||||
assert_eq!(queue.push(&screen, REQUESTED), Some(true));
|
||||
assert!(Arc::ptr_eq(&queue.pop(true).unwrap(), &screen));
|
||||
assert!(queue.pop(true).is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &world));
|
||||
assert!(Arc::ptr_eq(&queue.pop(true, 1).unwrap(), &screen));
|
||||
assert!(queue.pop(true, 1).is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &world));
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ pub struct Options {
|
||||
/// these in it.
|
||||
pub skip_shaders: Vec<String>,
|
||||
/// Shaders taken from this folder where it has them: `<hash>.dxil`, by
|
||||
/// the hash the runtime names the title's shader by.
|
||||
/// the hash the runtime names the title's shader by (ours: by their own).
|
||||
pub shaders: Option<PathBuf>,
|
||||
/// With `compare`: the folder the shaders of the second are from.
|
||||
pub shaders_b: Option<PathBuf>,
|
||||
@@ -948,7 +948,8 @@ impl Player {
|
||||
let taken = std::cell::Cell::new(false);
|
||||
let mut m = super::pso::make(&device, &p.parts, root, |i| {
|
||||
let other = shaders.and_then(|dir| {
|
||||
let hash = title_hash(p, i)?;
|
||||
let own = || frame.codes.get(i as usize).map(|c| c.hash[..8].iter().map(|b| format!("{b:02x}")).collect());
|
||||
let hash = title_hash(p, i).map(str::to_owned).or_else(own)?;
|
||||
std::fs::read(dir.join(format!("{hash}.dxil"))).ok()
|
||||
});
|
||||
taken.set(taken.get() || other.is_some());
|
||||
|
||||
@@ -95,6 +95,11 @@ fn build() -> [u8; 32] {
|
||||
*hash.finalize().as_bytes()
|
||||
}
|
||||
|
||||
/// What tells one set of translations from another ([`build`]).
|
||||
pub(crate) fn translation() -> [u8; 32] {
|
||||
build()
|
||||
}
|
||||
|
||||
/// Puts the translation of `container` into the cache before any title asks
|
||||
/// for it (`victory shaders`): whether it was there already, or why it does
|
||||
/// not translate. The host is opened first, as a run does: what the card
|
||||
|
||||
Reference in new issue
Block a user