The title's pipelines written down (VICTORY_PIPELINE_BOOK=1, off) and made ahead of a run, each batch in a process of its own (victory warm)

Every pipeline the title creates goes to known-pipelines.bin beside the
pipeline library, its containers to known-shaders.bin (in the cache folder;
they are the title's code). `victory warm` makes their host pipelines in
idle-priority processes of 200 each and lets them go: the driver's cache on
disk keeps them. Those earlier runs drew with come first; what is done is
noted by translator and driver (warm-done.txt); a pipeline that ends or
hangs its process is named in warm-bad.txt and skipped. VICTORY_EARLY_ALL
does this in the running title and ended it inside the driver.

Not measured yet: how long, and how much the driver's cache grows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 13:32:18 -06:00
1 parent 35155bed9a
commit b7ab9c49c0
9 files changed
+736 -10

No files matched your search

+26
View File
@@ -10,6 +10,8 @@ mod replay;
mod run;
mod shader;
mod translate;
#[cfg(windows)]
mod warm;
use std::path::PathBuf;
@@ -103,6 +105,28 @@ enum Command {
#[arg(long)]
jobs: Option<usize>,
},
/// Make the host pipelines of every pipeline the title ever created
/// (runs with `VICTORY_PIPELINE_BOOK=1` write them down), so that the
/// driver's cache on disk has them before a run needs one: once per change
/// of the translator or the driver. Goes on where it was stopped.
#[cfg(windows)]
Warm {
/// Processes at once (default: two thirds of the logical cores).
#[arg(long)]
jobs: Option<usize>,
/// At most this many pipelines.
#[arg(long)]
limit: Option<usize>,
/// Those made before too.
#[arg(long)]
again: bool,
/// Only the pipelines earlier runs drew with.
#[arg(long)]
used: bool,
/// (What the processes it starts are given.)
#[arg(long, hide = true)]
these: Option<String>,
},
/// Prepare, map and bind a title executable; with --execute, run it.
Run {
exe: PathBuf,
@@ -190,6 +214,8 @@ fn main() -> Result<()> {
translate::run(paths, validate, pipelines, list, jobs)
}
Command::Shaders { paths, jobs } => translate::precompile(paths, jobs),
#[cfg(windows)]
Command::Warm { jobs, limit, again, used, these } => warm::run(jobs, limit, again, used, these),
Command::Run {
exe,
unimplemented,
+199
View File
@@ -0,0 +1,199 @@
//! `victory warm`: host pipelines made ahead of a run (`known_pipelines`), in
//! processes of their own: a compiler that crashes or hangs costs one pipeline.
use std::collections::HashSet;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use victory_hle::known_pipelines as known;
/// Pipelines a process makes before another takes its place: the compiler's
/// and the translations' memory goes with it.
const AT_ONCE: usize = 200;
/// A pipeline that takes longer is taken for one the compiler hangs on.
const LONGEST: Duration = Duration::from_secs(180);
fn folder() -> Result<PathBuf> {
let cfg = victory_core::Config::load()?;
Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines"))
}
pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, these: Option<String>) -> Result<()> {
let dir = folder()?;
if let Some(these) = these {
return make(&dir, &these);
}
let began = Instant::now();
victory_hle::known_pipelines::use_translations(dir.with_file_name("shaders"));
let fingerprint = known::fingerprint();
let done_file = dir.join("warm-done.txt");
let bad_file = dir.join("warm-bad.txt");
let keys = known::keys(&dir);
let listed = std::fs::read_to_string(&done_file).unwrap_or_default();
let mut done: HashSet<&str> = HashSet::new();
for line in listed.lines() {
if let Some((of, key)) = line.split_once(' ')
&& of == fingerprint
{
done.insert(key);
}
}
let bad = std::fs::read_to_string(&bad_file).unwrap_or_default();
let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect();
let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default();
let early: HashSet<&str> = early.lines().collect();
// Those earlier runs drew with first.
let mut all: Vec<usize> = (0..keys.len())
.filter(|&n| {
let key = keys[n].as_str();
(again || !done.contains(key)) && !bad.contains(key) && (!used || early.contains(key))
})
.collect();
all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), n));
all.truncate(limit.unwrap_or(usize::MAX));
let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
let jobs = jobs.unwrap_or(cores * 2 / 3).max(1);
println!(
"{} pipelines known, {} made before ({fingerprint}), {} bad; {} to make, {jobs} processes",
keys.len(),
done.len(),
bad.len(),
all.len()
);
let chunks: Vec<&[usize]> = all.chunks(AT_ONCE).collect();
let next = AtomicUsize::new(0);
let state = Mutex::new((Vec::<f64>::new(), 0usize, 0usize));
let done_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&done_file)?);
let bad_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&bad_file)?);
std::thread::scope(|s| {
for _ in 0..jobs.min(chunks.len()) {
s.spawn(|| {
while let Some(&chunk) = chunks.get(next.fetch_add(1, Ordering::Relaxed)) {
let mut rest = chunk;
while !rest.is_empty() {
let (made, ended) = child(rest, |n, ms, there| {
let mut state = lock(&state);
state.0.push(ms);
state.1 += usize::from(!there);
let count = state.0.len();
if count % 1000 == 0 {
println!("{count} of {}, {:.0} s", all.len(), began.elapsed().as_secs_f64());
}
drop(state);
let _ = writeln!(lock(&done_out), "{fingerprint} {}", keys[n]);
});
rest = &rest[made.min(rest.len())..];
match (ended, rest.split_first()) {
(Some(why), Some((&n, after))) => {
// The one it was at.
println!("pipeline {n} {}: {why}", keys[n]);
let _ = writeln!(lock(&bad_out), "{} {why}", keys[n]);
lock(&state).2 += 1;
rest = after;
}
_ => break,
}
}
}
});
}
});
let (mut times, refused, crashed) = state.into_inner().unwrap_or_else(|e| e.into_inner());
times.sort_by(f64::total_cmp);
let at = |q: f64| times.get((times.len() as f64 * q) as usize).copied().unwrap_or(0.0);
println!(
"{} made in {:.0} s ({refused} have no host pipeline, {crashed} ended their process); ms each: median {:.1}, p90 {:.1}, p99 {:.1}, most {:.0}, sum {:.0} s",
times.len(),
began.elapsed().as_secs_f64(),
at(0.5),
at(0.9),
at(0.99),
times.last().copied().unwrap_or(0.0),
times.iter().sum::<f64>() / 1e3
);
Ok(())
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// Has a process make `these`; how many it made, and how it ended if not well.
fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Option<String>) {
let list: Vec<String> = these.iter().map(usize::to_string).collect();
let spawned = std::env::current_exe().and_then(|exe| {
use std::os::windows::process::CommandExt;
const IDLE_PRIORITY_CLASS: u32 = 0x40;
Command::new(exe)
.args(["warm", "--these", &list.join(",")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.creation_flags(IDLE_PRIORITY_CLASS)
.spawn()
});
let Ok(mut process) = spawned else { return (these.len(), None) };
let Some(out) = process.stdout.take() else { return (these.len(), None) };
let process = Mutex::new(process);
let (heard, over) = (Mutex::new(Instant::now()), AtomicBool::new(false));
let hung = AtomicBool::new(false);
let mut made = 0;
std::thread::scope(|s| {
s.spawn(|| {
while !over.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(500));
if lock(&heard).elapsed() > LONGEST {
hung.store(true, Ordering::Relaxed);
let _ = lock(&process).kill();
return;
}
}
});
for line in BufReader::new(out).lines().map_while(Result::ok) {
*lock(&heard) = Instant::now();
let mut words = line.split(' ');
if words.next() == Some("made")
&& let (Some(n), Some(ms), Some(there)) = (words.next(), words.next(), words.next())
&& let (Ok(n), Ok(ms)) = (n.parse(), ms.parse())
{
made += 1;
each(n, ms, there == "1");
}
}
over.store(true, Ordering::Relaxed);
});
let status = lock(&process).wait();
let well = status.as_ref().is_ok_and(|s| s.success());
if well {
return (these.len(), None);
}
let why = if hung.load(Ordering::Relaxed) {
format!("hung for {} s", LONGEST.as_secs())
} else {
status.map_or_else(|e| e.to_string(), |s| format!("{s}"))
};
(made, Some(why))
}
/// What such a process does.
fn make(dir: &Path, these: &str) -> Result<()> {
let these: Vec<usize> = these.split(',').map(|n| n.parse().context("--these")).collect::<Result<_>>()?;
let cfg = victory_core::Config::load()?;
victory_hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?);
let mut out = std::io::stdout();
known::make(dir, &these, |n, came| {
let _ = match came {
None => writeln!(out, "at {n}"),
Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)),
};
let _ = out.flush();
});
// Without what a run's end does (nothing to save, the host's threads).
let _ = out.flush();
std::process::exit(0)
}
+4
View File
@@ -561,6 +561,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);
@@ -748,6 +750,8 @@ static FUNCTIONS: Table<24> = {
#[cfg(windows)]
pub(crate) mod host;
#[cfg(windows)]
pub mod known;
#[cfg(windows)]
mod library;
#[cfg(windows)]
mod make;
+10 -10
View File
@@ -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 {
+480
View File
@@ -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);
+4
View File
@@ -59,6 +59,10 @@ impl Pending {
}
}
pub(super) fn key(&self) -> &str {
&self.key
}
fn make(&self) {
self.made
.get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref()));
+5
View File
@@ -93,6 +93,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
+3
View File
@@ -26,6 +26,9 @@ pub use victory_gpu::console;
#[cfg(all(windows, feature = "diagnostics"))]
pub use victory_gpu::replay;
#[cfg(windows)]
pub use victory_gpu::pipeline::known as known_pipelines;
use victory_loader::{ImportResolver, Provenance, Resolution};
use victory_pe::ImportSymbol;