Ver código fonte

Merge branch 'day/shaders' into local/next

local 1 dia atrás
pai
commit
5bf49062d6

+ 26 - 0
apps/victory/src/main.rs

@@ -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,

+ 2 - 0
apps/victory/src/translate.rs

@@ -250,6 +250,8 @@ pub fn run(
     if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) {
         victory_shader::emit::set_host_max_wave(n);
     }
+    // `VICTORY_HOST_RDNA=1`: as for an AMD RDNA card (`VICTORY_RDNA_FLOAT`).
+    victory_shader::emit::set_host_rdna(std::env::var_os("VICTORY_HOST_RDNA").is_some_and(|v| v == "1"));
     let dll = validate.then(Validator::default_path).flatten();
     if validate {
         Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;

+ 210 - 0
apps/victory/src/warm.rs

@@ -0,0 +1,210 @@
+//! `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 = 40;
+/// A pipeline that takes longer is taken for one the compiler hangs on.
+const LONGEST: Duration = Duration::from_secs(180);
+
+/// As the runs count one that takes long.
+const SLOW_MS: f64 = 1000.0;
+
+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, the others in no order (by key).
+    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()), &keys[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)?);
+    // (Read back by the runs: these are made beside the others, not before.)
+    let slow_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(dir.join("slow-pipelines.txt"))?);
+    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| {
+                            if ms >= SLOW_MS {
+                                let _ = writeln!(lock(&slow_out), "\n{} {ms:.0}", keys[n]);
+                            }
+                            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 told = match came {
+            None => writeln!(out, "at {n}"),
+            Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)),
+        };
+        if told.and_then(|()| out.flush()).is_err() {
+            // Whoever asked is gone.
+            std::process::exit(1);
+        }
+    });
+    // Without what a run's end does (nothing to save, the host's threads).
+    let _ = out.flush();
+    std::process::exit(0)
+}

+ 30 - 1
crates/victory-gpu/src/host.rs

@@ -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);
     }

+ 4 - 0
crates/victory-gpu/src/pipeline.rs

@@ -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;

+ 10 - 10
crates/victory-gpu/src/pipeline/host.rs

@@ -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 - 0
crates/victory-gpu/src/pipeline/known.rs

@@ -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);
+    }
+}

+ 49 - 0
crates/victory-gpu/src/pipeline/library.rs

@@ -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);

+ 98 - 22
crates/victory-gpu/src/pipeline/make.rs

@@ -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));
     }
 }

+ 3 - 2
crates/victory-gpu/src/replay/play.rs

@@ -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());

+ 5 - 0
crates/victory-gpu/src/shader_cache.rs

@@ -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

+ 3 - 0
crates/victory-hle/src/lib.rs

@@ -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;
 

+ 13 - 1
crates/victory-shader/src/emit/bitcode/opt.rs

@@ -52,10 +52,22 @@ pub const LOADS: u32 = 16;
 /// half has a lane where every lane is in EXEC (`lower.rs`,
 /// `v_readfirstlane_b32`).
 pub const FIRST: u32 = 32;
+/// Not a pass over the module either: the lowering reads the dwords of one
+/// console load (`s_buffer_load_dwordx2` to `x16` from an SRV, a
+/// `global_load_dwordx2` to `x4`) by one call for every four of them, not
+/// by a call each (`lower.rs`, `raw_dwords`). The same bytes are read.
+/// From fxceless/victory-fork c36971b2. On an RX 7900 XTX it is worth nothing:
+/// the yard's frame replayed turn by turn, dispatches and draws 18.47 -> 18.45
+/// ms (12 loops) and 18.23 -> 18.16 (5 loops): the driver joins the loads.
+pub const WIDE: u32 = 64;
 /// The passes over the module.
 pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS;
 /// Every pass.
-pub const ALL: u32 = MODULE | FIRST;
+pub const ALL: u32 = MODULE | FIRST | WIDE;
+/// The passes that run when nothing says which: every one but [`WIDE`],
+/// which no card has shown a gain for yet (`VICTORY_SHADER_OPT=127` asks
+/// for it).
+pub const DEFAULT: u32 = ALL & !WIDE;
 
 /// What the instructions a module writes use, of the features a shader
 /// declares by flag (the validator's "flags must match usage").

+ 53 - 1
crates/victory-shader/src/emit/lower.rs

@@ -6050,6 +6050,47 @@ impl<'a> Lower<'a> {
         })
     }
 
+    /// Whether the dwords of one console load are read by one call for up
+    /// to four of them (`bitcode::opt::WIDE` of `VICTORY_SHADER_OPT`), not
+    /// by a call each.
+    fn wide_loads() -> bool {
+        super::shader_opt() & super::bitcode::opt::WIDE != 0
+    }
+
+    /// `count` dwords from byte `addr` on of the raw view `h`, as integers,
+    /// read in the current block by one call for every four of them
+    /// ([`Self::wide_loads`]). They are the dwords of ONE console load,
+    /// which the console reads as one (address plus 4, 8, ... without
+    /// wrapping at 32 bits): the same bytes as a call a dword reads. Loads
+    /// of different console instructions are never joined: the program
+    /// computes their offsets in 32-bit registers, and `x - 4` and `x` at
+    /// `x = 0` are one dword out of the view and its first one, where one
+    /// call from `x - 4` on would read both out of it.
+    fn raw_dwords(&mut self, h: V, addr: V, count: u32) -> Vec<V> {
+        let c = self.cur;
+        let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
+        let mut out = Vec::with_capacity(count as usize);
+        for first in (0..count).step_by(4) {
+            let n = (count - first).min(4);
+            let off = self.s.m.i32(4 * first);
+            let a = self.s.m.bin(c, Bin::Add, addr, off);
+            let mask = self.s.m.i8((1u8 << n) - 1);
+            let r = self.s.op(
+                c,
+                "rawBufferLoad.f32",
+                Attr::ReadOnly,
+                self.s.t.res_ret,
+                139,
+                &[h, a, u, mask, al],
+            );
+            for k in 0..n {
+                let x = self.s.m.extract(c, r, k);
+                out.push(self.as_int(x));
+            }
+        }
+        out
+    }
+
     fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
         let Fields::Smem {
             data,
@@ -6132,7 +6173,12 @@ impl<'a> Lower<'a> {
             let at = self.begin_guarded(Some(is_buffer));
             let h = self.handle(site, src, false, (11, 0))?;
             let mut raw = Vec::new();
-            for k in 0..count {
+            let wide = Self::wide_loads();
+            if wide {
+                let dwords = self.raw_dwords(h, addr, count);
+                raw.extend(dwords.into_iter().map(|x| (x, zero)));
+            }
+            for k in 0..if wide { 0 } else { count } {
                 let b = self.cur;
                 let off = self.s.m.i32(4 * k);
                 let a = self.s.m.bin(b, Bin::Add, addr, off);
@@ -6185,6 +6231,12 @@ impl<'a> Lower<'a> {
                 }
                 None => self.handle(site, src, false, (11, 0))?,
             };
+            if Self::wide_loads() {
+                for (k, x) in self.raw_dwords(h, addr, count).into_iter().enumerate() {
+                    self.write(inst, Reg::S(code + k as u8), x, None);
+                }
+                return Ok(());
+            }
             let c = self.cur;
             for k in 0..count {
                 let off = self.s.m.i32(4 * k);

+ 159 - 5
crates/victory-shader/src/emit/mod.rs

@@ -206,13 +206,15 @@ pub fn builder_bounds() -> bool {
 /// is exact, so the switch is for telling a translator fault from a
 /// clean-up fault, and for measuring what the clean-up is worth.
 /// `VICTORY_SHADER_OPT`:
-/// - unset: every pass.
+/// - unset: every pass but the last one below (63).
 /// - `0`: none (the module as the lowering made it).
 /// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants
 ///   and identities, 4 one instruction for one value, 8 what a branch taken
 ///   says about its condition, 16 one read for one place within a block,
 ///   32 a first-lane read of two host waves without the round that asks
 ///   which half has a lane (where every lane has one).
+///   64 the dwords of one console load read by one call for every four
+///   (not on unless asked: `127` is every pass with it).
 ///
 /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
 /// does).
@@ -310,7 +312,7 @@ fn parse_shader_opt(value: Option<&str>) -> u32 {
             Some(hex) => u32::from_str_radix(hex, 16).ok(),
             None => v.parse().ok(),
         });
-    parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL)
+    parsed.map_or(bitcode::opt::DEFAULT, |n| n & bitcode::opt::ALL)
 }
 
 /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
@@ -1080,13 +1082,15 @@ mod tests {
 
     #[test]
     fn the_clean_up_switch_parses_or_runs_every_pass() {
-        let all = super::bitcode::opt::ALL;
-        assert_eq!(parse_shader_opt(None), all);
+        let (all, usual) = (super::bitcode::opt::ALL, super::bitcode::opt::DEFAULT);
+        assert_eq!(usual, 63, "the passes of the builds before the wide loads");
+        assert_eq!(parse_shader_opt(None), usual);
         assert_eq!(parse_shader_opt(Some("0")), 0);
         assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
         assert_eq!(parse_shader_opt(Some("0x1")), 1);
+        assert_eq!(parse_shader_opt(Some("127")), all);
         assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
-        assert_eq!(parse_shader_opt(Some("on")), all);
+        assert_eq!(parse_shader_opt(Some("on")), usual);
     }
 
     #[test]
@@ -2081,6 +2085,156 @@ mod tests {
         let _ = super::emit(&c, &native, &p, &st, &io, &res);
     }
 
+    /// `s_buffer_load_dwordx4`, `x8` and `x16` from a raw SRV read the dwords
+    /// the console's range-checked load reads, a call a dword or
+    /// (`VICTORY_SHADER_OPT` with 64) a call for every four: also where a
+    /// call's four dwords lie across the view's end (the dwords out of it
+    /// are 0, the others are read). On the software adapter only: run the
+    /// test once plain and once with `VICTORY_SHADER_OPT=127`.
+    #[test]
+    #[cfg(windows)]
+    fn scalar_buffer_loads_read_the_same_dwords_one_call_or_four() {
+        // (first register, dwords) of the three loads, in order.
+        const LOADS: [(u32, u32); 3] = [(16, 8), (24, 4), (32, 16)];
+        let mut words: Vec<u32> = vec![
+            0xBE85_0380, // s_mov_b32 s5, 0
+            0xF408_0202,
+            0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (the SRV)
+            0xF408_0302,
+            0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (the UAV)
+            0xF42C_0404,
+            0x0000_0000, // s_buffer_load_dwordx8 s[16:23], s[8:11], s0
+            0xF428_0604,
+            0xFA00_0008, // s_buffer_load_dwordx4 s[24:27], s[8:11], 0x8
+            0xF430_0804,
+            0x0200_0004, // s_buffer_load_dwordx16 s[32:47], s[8:11], s1, 0x4
+        ];
+        let mut out_dword = 0u32;
+        for (first, n) in LOADS {
+            for k in 0..n {
+                // v_mov_b32 v1, s<first + k>
+                words.push(0x7E00_0000 | 1 << 17 | 0x001 << 9 | (first + k));
+                // buffer_store_dword v1, s[12:15], offset 4 * out_dword
+                words.push(0x38 << 26 | 0x1C << 18 | (4 * out_dword));
+                words.push(0x80 << 24 | (12 >> 2) << 16 | 1 << 8);
+                out_dword += 1;
+            }
+        }
+        words.push(0xBF81_0000); // s_endpgm
+        let table = |kind, at| crate::UsedResource {
+            kind,
+            root: crate::RootType::Table,
+            table_offset_dwords: at,
+            lower_bound: 0,
+            stride: 4,
+            dwords: 4,
+            user_data: 4,
+            slot: 1,
+        };
+        let native = super::NativeProgram {
+            stage: super::HwStage::Cs,
+            wave64: false,
+            vgprs: 4,
+            layout: vec![
+                crate::RootParam {
+                    root: crate::RootType::Constants,
+                    table_offset_dwords: 0,
+                    sgprs: 4,
+                    base_register: 0,
+                    user_data: 0,
+                    slot: 0,
+                },
+                crate::RootParam {
+                    root: crate::RootType::Table,
+                    table_offset_dwords: 0,
+                    sgprs: 1,
+                    base_register: 0,
+                    user_data: 4,
+                    slot: 1,
+                },
+            ],
+            used: vec![table(crate::ResourceType::Srv, 0), table(crate::ResourceType::Uav, 8)],
+            io: crate::native::StageIo::Cs(crate::native::ComputeIo {
+                rsrc2: 5 << 1,
+                threads: [1, 1, 1],
+            }),
+            code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
+        };
+        let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
+        let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
+        let io = crate::io::raise(&p, &native).unwrap();
+        let st = crate::structure::structure(&p).unwrap();
+        let l = super::lower::lower(&super::lower::Parts {
+            native: &native,
+            p: &p,
+            st: &st,
+            io: &io,
+            res: &res,
+            inputs: Vec::new(),
+            outputs: Vec::new(),
+            prims: Vec::new(),
+            mesh_stride: 0,
+        })
+        .unwrap();
+        // The calls that read the SRV: 28 a dword, 7 with four a call.
+        let wide = shader_opt() & super::bitcode::opt::WIDE != 0;
+        let mut dxil = l.dxil;
+        if let Ok(mut v) = super::validator::Validator::load(
+            super::validator::Validator::default_path().as_deref(),
+        ) {
+            v.validate(&mut dxil).unwrap();
+        }
+        let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
+        let Ok(host) = super::host::Host::new(true) else {
+            eprintln!("no software adapter; the dispatch is skipped");
+            return;
+        };
+        let cs = super::HostShader {
+            stage: super::HwStage::Cs,
+            dxil,
+            user_data: l.user_data,
+            samplers: Vec::new(),
+            static_samplers: Vec::new(),
+            root_cbvs: l.root_cbvs,
+            root_srvs: l.root_srvs,
+            root_uavs: l.root_uavs,
+            root_indexed_views: Vec::new(),
+        };
+        let (root, pso) = host.compute_pipeline(&cs).unwrap();
+        // Twelve dwords: the loads below run across the view's end.
+        let data: Vec<u32> = (0..12u32).map(|i| 0x1111_1111u32.wrapping_mul(i + 1) ^ 0x8000_0000).collect();
+        let dword = |byte: u64| -> u32 {
+            if byte.is_multiple_of(4) && byte + 4 <= 4 * data.len() as u64 { data[(byte / 4) as usize] } else { 0 }
+        };
+        for (s0, s1) in [(0u32, 0u32), (16, 0), (24, 4), (40, 28), (48, 44), (8, 12)] {
+            let out = host
+                .dispatch(
+                    &root,
+                    &pso,
+                    &super::host::Dispatch {
+                        roots: vec![(0, super::host::Root::Constants(vec![s0, s1, 0, 0, 0]))],
+                        views: &[
+                            super::host::View::Buffer {
+                                data: &data,
+                                stride: super::host::Stride::Raw,
+                            },
+                            super::host::View::RawUav(32),
+                        ],
+                        samplers: &[],
+                        groups: [1, 1, 1],
+                    },
+                )
+                .unwrap();
+            let starts = [u64::from(s0), 8, u64::from(s1) + 4];
+            let mut want = Vec::new();
+            for (&(_, n), start) in LOADS.iter().zip(starts) {
+                want.extend((0..u64::from(n)).map(|k| dword(start + 4 * k)));
+            }
+            eprintln!("offsets {s0} and {s1}, four dwords a call: {wide}: {:x?}", &out[0][..28]);
+            assert_eq!(out[0][..28], want[..], "offsets {s0} and {s1}, four dwords a call: {wide}");
+        }
+    }
+
     #[test]
     fn valu_div_f32_sequence_executes_on_gpu() {
         let words: &[u32] = &[

+ 1 - 1
docs/replay.md

@@ -69,7 +69,7 @@ with the presented one.
 | `--only 3..7` | runs these lists; of the others only barriers |
 | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
 | `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
-| `--shaders <folder>` | takes shaders from the folder where it has them: `<hash>.dxil`, by the hash the runtime names the title's shader by; with `--compare --shaders-b <folder>` a second set, turn by turn with the first |
+| `--shaders <folder>` | takes shaders from the folder where it has them: `<hash>.dxil`, by the hash the runtime names the title's shader by (a pass of ours: its own DXIL hash); with `--compare --shaders-b <folder>` a second set, turn by turn with the first |
 | `--retranslate <folder>` | only writes that folder: the capture's shaders translated by this build with the `VICTORY_*` switches of this run (`--view-limit`, `--raw-views`: the view heap's null slot and where raw views start, as the capture's shaders have them) |
 | `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) |
 | `--pace <ms>` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one |