diff --git a/README.md b/README.md index 5d2feb513e..fafec20621 100644 --- a/README.md +++ b/README.md @@ -247,10 +247,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. five seconds without progress counts as a stall, and the window shows when the last one ended. XCL prepares supported shader stages and compute pipelines, including split pieces and their whole fallback. Graphics pipelines are created during play the first - time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside - the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts - on the next launch, with their driver blobs kept, so the title makes them from those in - milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + time. The startup history records supported graphics descriptors and two-pass mesh streams with + their state (`used-graphics-pipelines.bin` beside the shader cache, capped by `XCL_GFX_RECORDS_MB` + at 64 MB by default). On the next launch, XCL builds the recorded pipelines before the title starts + and keeps their driver blobs for reuse. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Closing the window cancels the launch. A compiler or driver failure stops it and reports the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - For compute shaders that XCL can split, the runtime first tries the saved driver blob for diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index cb4b872354..552e0ecb46 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -11,9 +11,11 @@ //! entry = length u32, check u32 (the low half of fnv64 of the payload), payload //! payload = 1 key u64 shaders [u64; 5] state input* a pipeline //! | 2 key u64 bytes a shader (preparation job files only) -//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, //! `real::shader_key` of it -//! shaders = `real::shader_key` of the VS, PS, DS, HS, GS (0: none) +//! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) +//! layout = subobject count (u8), then subobject types in stream order (u8 each) //! state = every field of the description but its pointers, in `state`'s order (varints) //! input = count, then each element's semantic name (length, bytes), index, format, slot, //! offset, class, step rate (varints) @@ -34,11 +36,13 @@ use std::path::{Path, PathBuf}; use windows::Win32::Graphics::Direct3D12::*; const MAGIC: &[u8; 8] = b"XCLGFXP\0"; -/// The layout of an entry: a change makes every file of the older one read as none. +/// The file format and existing entry layouts. Optional new tags keep earlier entries readable. const VERSION: u32 = 1; const HEADER: usize = 12; const PIPELINE: u8 = 1; const SHADER: u8 = 2; +const MESH_PIPELINE: u8 = 3; +const MAX_MESH_LAYOUT: usize = 14; // root, mesh (MS or AS), PS, and eleven scalar state types /// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). pub(crate) fn path() -> PathBuf { @@ -84,6 +88,12 @@ impl Reader<'_> { fn u32var(&mut self) -> Option { self.var().and_then(|v| u32::try_from(v).ok()) } + fn bounded_var(&mut self, max: u32) -> Option { + let before = self.0.len(); + let v = self.u32var()?; + let bits = (u32::BITS - v.leading_zeros()).max(1); + (before - self.0.len() == bits.div_ceil(7) as usize && v <= max).then_some(v) + } fn u64(&mut self) -> Option { let (b, rest) = self.0.split_at_checked(8)?; self.0 = rest; @@ -100,25 +110,25 @@ impl Reader<'_> { /// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and /// reading. What the title's translated pipeline is made of beside its shaders /// (`real::graphics_blob_key` hashes the same). -fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32)) { +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32, u32)) { macro_rules! int { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u32::MAX); $x = v as i32; }}; } macro_rules! byte { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u8::MAX.into()); $x = v as u8; }}; } macro_rules! float { ($x:expr) => {{ let mut v = $x.to_bits(); - f(&mut v); + f(&mut v, u32::MAX); $x = f32::from_bits(v); }}; } @@ -137,7 +147,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(rt.LogicOp.0); byte!(rt.RenderTargetWriteMask); } - f(&mut d.SampleMask); + f(&mut d.SampleMask, u32::MAX); let r = &mut d.RasterizerState; int!(r.FillMode.0); int!(r.CullMode.0); @@ -148,7 +158,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(r.DepthClipEnable.0); int!(r.MultisampleEnable.0); int!(r.AntialiasedLineEnable.0); - f(&mut r.ForcedSampleCount); + f(&mut r.ForcedSampleCount, u32::MAX); int!(r.ConservativeRaster.0); let z = &mut d.DepthStencilState; int!(z.DepthEnable.0); @@ -165,14 +175,14 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) } int!(d.IBStripCutValue.0); int!(d.PrimitiveTopologyType.0); - f(&mut d.NumRenderTargets); + f(&mut d.NumRenderTargets, 8); for format in &mut d.RTVFormats { int!(format.0); } int!(d.DSVFormat.0); - f(&mut d.SampleDesc.Count); - f(&mut d.SampleDesc.Quality); - f(&mut d.NodeMask); + f(&mut d.SampleDesc.Count, u32::MAX); + f(&mut d.SampleDesc.Quality, u32::MAX); + f(&mut d.NodeMask, u32::MAX); int!(d.Flags.0); } @@ -187,7 +197,7 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE } // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); - state(&mut copy, &mut |v| put_var(&mut out, *v as u64)); + state(&mut copy, &mut |v, _| put_var(&mut out, *v as u64)); let il = &d.InputLayout; let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; put_var(&mut out, elems.len() as u64); @@ -202,6 +212,73 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE out } +fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { + if shaders[0] == 0 || layout.len() > MAX_MESH_LAYOUT { + return false; + } + let mut seen = 0u32; + for &id in layout { + match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(id as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS => {} + _ => return false, + } + let bit = 1 << id; + if seen & bit != 0 { + return false; + } + seen |= bit; + } + let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; + (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) + && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) == (shaders[1] != 0) +} + +/// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option> { + if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { + return None; + } + let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + BlendState: d.BlendState, + SampleMask: d.SampleMask, + RasterizerState: d.RasterizerState, + DepthStencilState: d.DepthStencilState, + IBStripCutValue: d.IBStripCutValue, + PrimitiveTopologyType: d.PrimitiveTopologyType, + NumRenderTargets: d.NumRenderTargets, + RTVFormats: d.RTVFormats, + DSVFormat: d.DSVFormat, + SampleDesc: d.SampleDesc, + NodeMask: d.NodeMask, + Flags: d.Flags, + ..Default::default() + }; + let mut out = Vec::with_capacity(256); + out.push(MESH_PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for shader in shaders { + out.extend_from_slice(&shader.to_le_bytes()); + } + out.push(layout.len() as u8); + out.extend(layout.iter().map(|&id| id as u8)); + state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + Some(out) +} + /// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { let mut out = Vec::with_capacity(9 + bytes.len()); @@ -241,11 +318,48 @@ impl Record { } } +pub(crate) struct MeshRecord { + pub key: u64, + pub shaders: [u64; 2], + pub layout: Vec, + desc: Box, +} + +// The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. +unsafe impl Send for MeshRecord {} +unsafe impl Sync for MeshRecord {} + +impl MeshRecord { + pub(crate) fn state(&self) -> &D3D12_GRAPHICS_PIPELINE_STATE_DESC { + &self.desc + } +} + pub(crate) enum Entry { Pipeline(Record), + MeshPipeline(MeshRecord), Shader(u64, Vec), } +fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { + let shaders = [r.u64()?, r.u64()?]; + let n = *r.bytes(1)?.first()? as usize; + if key == 0 || n > MAX_MESH_LAYOUT { + return None; + } + let layout: Vec = r.bytes(n)?.iter().map(|&id| id.into()).collect(); + if !valid_mesh_layout(shaders, &layout) { + return None; + } + let mut desc = Box::::default(); + let mut valid = true; + state(&mut desc, &mut |v, max| match r.bounded_var(max) { + Some(x) => *v = x, + None => valid = false, + }); + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc }) +} + /// The entry of `payload` (None: not one this version writes). pub(crate) fn decode(payload: &[u8]) -> Option { let (&tag, rest) = payload.split_first()?; @@ -254,6 +368,9 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == SHADER { return Some(Entry::Shader(key, r.0.to_vec())); } + if tag == MESH_PIPELINE { + return decode_mesh(key, r).map(Entry::MeshPipeline); + } if tag != PIPELINE { return None; } @@ -263,7 +380,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { } let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); let mut short = false; - state(&mut desc, &mut |v| match r.u32var() { + state(&mut desc, &mut |v, _| match r.u32var() { Some(x) => *v = x, None => short = true, }); @@ -578,7 +695,78 @@ mod tests { let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); - assert!(decode(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + assert!(decode(&[u8::MAX, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + #[test] + fn a_mesh_entry_preserves_moved_shader_slot_order_and_state() { + let layout = [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, + ].map(|kind| kind.0 as u32); + let shaders = [0x13, 0x27]; + let mut desc = described(); + let ps = b"pixel"; + desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; + let payload = encode_mesh(0x1234, shaders, &layout, &desc).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; + assert_eq!((record.key, record.shaders), (0x1234, shaders)); + assert_eq!(record.layout, layout); + assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); + assert_eq!(record.state().RTVFormats, desc.RTVFormats); + assert!(record.state().PS.pShaderBytecode.is_null()); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state()).unwrap(), payload); + } + + #[test] + fn mesh_entries_require_supported_unique_layout_and_exact_payload() { + let ms = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32; + let moved = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32; + let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; + let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; + let d = described(); + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps], vec![ms, input]] { + assert!(encode_mesh(1, [1, 0], &layout, &d).is_none(), "unsupported layout {layout:?}"); + } + assert!(encode_mesh(1, [1, 2], &[ms], &d).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d).unwrap(); + assert!(decode(&payload[..payload.len() - 1]).is_none()); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); + + let count_at = 1 + 3 * std::mem::size_of::(); + let mut invalid = payload.clone(); + invalid[count_at] = MAX_MESH_LAYOUT as u8 + 1; + assert!(decode(&invalid).is_none()); + invalid[count_at] = 1; + invalid[count_at + 1] = input as u8; + assert!(decode(&invalid).is_none()); + let state_at = count_at + 2; + let overlong = [&payload[..state_at], &[0x81, 0], &payload[state_at + 1..]].concat(); + assert!(decode(&overlong).is_none()); + } + + #[test] + fn legacy_pipeline_and_mesh_entries_share_version_one_history() { + let dir = directory("mesh-version-one"); + let path = dir.0.join("records.bin"); + let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; + let shader = shader_entry(5, b"mesh"); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described()).unwrap(); + let mut writer = Writer::open(&path, 1 << 20).unwrap(); + writer.add(&legacy).unwrap(); + writer.add(&mesh).unwrap(); + writer.add(&shader).unwrap(); + drop(writer); + assert_eq!(&std::fs::read(&path).unwrap()[8..HEADER], &1u32.to_le_bytes()); + assert_eq!(read(&path), vec![legacy.clone(), mesh.clone(), shader.clone()]); + assert_eq!(pipeline(&legacy).key, 3); + assert!(matches!(decode(&mesh), Some(Entry::MeshPipeline(_)))); + assert!(matches!(decode(&shader), Some(Entry::Shader(5, _)))); } /// Written, read back in order, each entry once; a file cut short in its last entry keeps the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c12d907e36..7614c96b80 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6378,6 +6378,10 @@ pub(crate) fn shader_key(blob: &[u8]) -> u64 { } pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { + shader_set_key(blobs.iter().map(Vec::as_slice)) +} + +pub(crate) fn shader_set_key<'a>(blobs: impl IntoIterator) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); @@ -6423,8 +6427,11 @@ impl OwnedDesc { } /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set - /// `key` whose shaders' keys are `parts`; None for any other. + /// `key` whose shaders' keys are `parts`, or an eligible mesh stream's entry. unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + if let OwnedDesc::Stream(_, stream, _) = self { + return record_mesh_stream(stream); + } let OwnedDesc::Graphics(d, ..) = self else { return None }; // (`own_graphics` copied the stages it has, in this order) let mut parts = parts.iter(); @@ -7029,6 +7036,118 @@ unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { shader_bytes(&b) } +/// Keep the source states the mesh translator will use again during preparation. +unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { + let subs = stream_subobjects(stream)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut layout = Vec::with_capacity(subs.len()); + let (mut ms, mut amplification, mut ps) = (None, None, None); + let (mut seen, mut size) = (0u32, 0usize); + + fn value(payload: &[u8]) -> Option { + (payload.len() == std::mem::size_of::()).then(|| unsafe { std::ptr::read_unaligned(payload.as_ptr().cast()) }) + } + + for (ty, payload) in subs { + let (_, align) = super::null::subobject_payload(ty)?; + size += (align + payload.len() + 7) & !7; + let bit = 1u32 << ty; + if seen & bit != 0 { + return None; + } + seen |= bit; + match ty { + 0 => {} // The translator supplies its own root signature. + 19 => continue, // The title's cache blob is never an input to translation. + 2 | 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 2 => ps = Some(payload_shader(payload)?), + 24 => amplification = Some(payload_shader(payload)?), + 25 => ms = Some(payload_shader(payload)?), + 8 => desc.BlendState = value(payload)?, + 9 => desc.SampleMask = value(payload)?, + 10 => desc.RasterizerState = value(payload)?, + 11 => desc.DepthStencilState = value(payload)?, + 13 => desc.IBStripCutValue = value(payload)?, + 14 => desc.PrimitiveTopologyType = value(payload)?, + 15 => { + let rt: D3D12_RT_FORMAT_ARRAY = value(payload)?; + if rt.NumRenderTargets > 8 { + return None; + } + desc.NumRenderTargets = rt.NumRenderTargets; + desc.RTVFormats = rt.RTFormats; + } + 16 => desc.DSVFormat = value(payload)?, + 17 => desc.SampleDesc = value(payload)?, + 18 => desc.NodeMask = value(payload)?, + 20 => desc.Flags = value(payload)?, + _ => return None, + } + layout.push(ty); + } + if size != stream.len() || (ms.is_some() && amplification.is_some()) { + return None; + } + let ms = ms.or(amplification)?; + if !crate::gpu::xbox::parse(ms).is_some_and(|shader| shader.stage == "MS") { + return None; + } + let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; + let key = shader_set_key(std::iter::once(ms).chain(ps)); + super::gfx_records::encode_mesh(key, shaders, &layout, &desc) +} + +/// Build both recorded mesh passes on the adopted device from `prepare_device`. +/// +/// # Safety +/// `device` must be the live adopted device returned from `prepare_device`. +pub(crate) unsafe fn replay_mesh_record( + device: usize, + record: &super::gfx_records::MeshRecord, + shaders: [Option<&[u8]>; 2], +) -> Result<(), String> { + let [Some(ms), ps] = shaders else { return Err("mesh shader missing from the job".into()) }; + if record.shaders != [shader_key(ms), ps.map_or(0, shader_key)] || + record.key != shader_set_key(std::iter::once(ms).chain(ps)) + { + return Err("mesh shaders do not match the recorded keys".into()); + } + + let d = record.state(); + let mut stream = StreamOut::default(); + for &ty in &record.layout { + let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); + match ty { + 0 => stream.put(subobject, &std::ptr::null::()), + 2 => stream.shader(subobject, ps.ok_or("pixel shader missing from the job")?), + 24 | 25 => stream.shader(subobject, ms), + 8 => stream.put(subobject, &d.BlendState), + 9 => stream.put(subobject, &d.SampleMask), + 10 => stream.put(subobject, &d.RasterizerState), + 11 => stream.put(subobject, &d.DepthStencilState), + 13 => stream.put(subobject, &d.IBStripCutValue), + 14 => stream.put(subobject, &d.PrimitiveTopologyType), + 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), + 16 => stream.put(subobject, &d.DSVFormat), + 17 => stream.put(subobject, &d.SampleDesc), + 18 => stream.put(subobject, &d.NodeMask), + 20 => stream.put(subobject, &d.Flags), + _ => return Err(format!("unsupported mesh subobject {ty}")), + } + } + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + let mut out = std::ptr::null_mut(); + let hr = unsafe { + translated_mesh_stream(device as *mut c_void, desc.as_ptr().cast(), &pc_iid(Kind::PipelineState), &mut out) + }; + super::pso_async::release(out as usize); + match hr { + Some(hr) if hr >= 0 && !out.is_null() => Ok(()), + Some(hr) => Err(format!("mesh pipeline replay failed ({hr:#x})")), + None => Err("mesh pipeline record could not be translated".into()), + } +} + /// The passthrough mesh shader emits triangles for both translated MS and GS pipelines. fn two_pass_mesh_stream(rs: *mut c_void, ms: &[u8], ps: Option<&[u8]>) -> StreamOut { let mut out = StreamOut::default(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 67fb3e0dcb..ba27edaca3 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; +use crate::hle::d3d12x::gfx_records; /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -1906,15 +1907,19 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title /// starts all the same: it builds what is missing itself. fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { - use crate::hle::d3d12x::gfx_records::{self, Entry}; let t0 = std::time::Instant::now(); let payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + let records: Vec<_> = payloads.into_iter().filter_map(|payload| { + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?; + Some((payload, record)) + }).collect(); if records.is_empty() { crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } - let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + .filter(|&key| key != 0).collect(); + let shaders = shaders_by_key(inputs, wanted, progress); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); if missing != 0 { @@ -1932,7 +1937,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: let mut keys = HashSet::new(); for &k in &part { w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; - keys.extend(records[k].1.shaders.into_iter().filter(|&s| s != 0)); + keys.extend(records[k].1.identity().1.iter().copied().filter(|&key| key != 0)); } for key in keys { w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; @@ -1982,14 +1987,37 @@ fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPrepa found.into_inner().unwrap() } +enum GraphicsHistoryRecord { + Legacy(gfx_records::Record), + Mesh(gfx_records::MeshRecord), +} + +impl GraphicsHistoryRecord { + fn from_entry(entry: gfx_records::Entry) -> Option { + match entry { + gfx_records::Entry::Pipeline(record) => Some(Self::Legacy(record)), + gfx_records::Entry::MeshPipeline(record) => Some(Self::Mesh(record)), + gfx_records::Entry::Shader(..) => None, + } + } + + fn identity(&self) -> (u64, &[u64]) { + match self { + Self::Legacy(record) => (record.key, &record.shaders), + Self::Mesh(record) => (record.key, &record.shaders), + } + } +} + /// The records (by their index) whose shaders are all in `shaders` and make their set's key, and /// how many are not. -fn buildable<'a>(records: impl Iterator, shaders: &std::collections::HashMap>) -> (Vec, usize) { +fn buildable<'a>(records: impl Iterator, shaders: &HashMap>) -> (Vec, usize) { let (mut ok, mut missing) = (Vec::new(), 0); - for (i, r) in records.enumerate() { - let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + for (i, record) in records.enumerate() { + let (key, keys) = record.identity(); + let blobs: Option> = keys.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).map(Vec::as_slice)).collect(); match blobs { - Some(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + Some(blobs) if crate::hle::d3d12x::real::shader_set_key(blobs.iter().copied()) == key => ok.push(i), _ => missing += 1, } } @@ -2006,11 +2034,11 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { } /// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics -/// pipelines of a job file built as the title builds them (`real::prepare_graphics`), with the +/// pipelines of a job file built as the title builds them, with the /// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` /// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. fn graphics_worker(job: &Path, windows: u32) -> i32 { - use crate::hle::d3d12x::gfx_records::{self, Entry}; + use crate::hle::d3d12x::real; end_with_parent(); // (no title memory here: its windows are given) crate::gpu::uma::leave_out(); @@ -2020,13 +2048,13 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { let mut records = Vec::new(); for p in gfx_records::read(job) { match gfx_records::decode(&p) { - Some(Entry::Pipeline(r)) => records.push(r), - Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } + Some(gfx_records::Entry::Shader(key, code)) => { shaders.insert(key, code); } + Some(entry) => records.extend(GraphicsHistoryRecord::from_entry(entry)), None => {} } } let device = match Pipelines::for_adapter("auto") { - Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + Ok(p) => real::prepare_device(p.dev), Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; let n = records.len(); @@ -2038,17 +2066,24 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(r) = records.get(i) else { break }; - let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); - let desc = r.desc(code); + let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) - let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); + let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { + GraphicsHistoryRecord::Legacy(record) => { + let desc = record.desc(record.shaders.map(code)); + unsafe { real::prepare_graphics(device, &desc) } + } + GraphicsHistoryRecord::Mesh(record) => { + unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } + } + })).unwrap_or(false); if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } let d = done.fetch_add(1, Ordering::Relaxed) + 1; eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); }); } }); - let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); + let (hits, _, stored) = real::driver_cache_stats(); eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); 0 } @@ -2646,25 +2681,33 @@ mod tests { /// other shaders under its keys, is left out. #[test] fn a_graphics_record_is_built_only_with_its_own_shaders() { - use crate::hle::d3d12x::gfx_records::{decode, encode, Entry}; + use crate::hle::d3d12x::gfx_records::{decode, encode, encode_mesh}; use crate::hle::d3d12x::real::{shader_key, shaders_key}; - let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); - let record = |key: u64, shaders: [u64; 5]| { - let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); - match decode(&unsafe { encode(key, shaders, &d) }) { - Some(Entry::Pipeline(r)) => r, - _ => unreachable!(), - } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + }; + let (vs, ps, ms) = (b"vertex".to_vec(), b"pixel".to_vec(), b"mesh".to_vec()); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let record = |key, shaders| { + GraphicsHistoryRecord::from_entry(decode(&unsafe { encode(key, shaders, &desc) }).unwrap()).unwrap() }; let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let mesh = |key, shaders| { + let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; + let payload = encode_mesh(key, shaders, &layout, &desc).unwrap(); + GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() + }; let records = [ record(shaders_key(&[vs.clone(), ps.clone()]), both), record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), record(shaders_key(&[ps.clone(), vs.clone()]), both), + mesh(shaders_key(&[ms.clone(), ps.clone()]), [shader_key(&ms), shader_key(&ps)]), + mesh(shaders_key(&[ps.clone(), ms.clone()]), [shader_key(&ms), shader_key(&ps)]), ]; - let shaders = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); - assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + let shaders = HashMap::from([(shader_key(&vs), vs), (shader_key(&ps), ps), (shader_key(&ms), ms)]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the