| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987 |
- //! Draws on the host GPU (decision 0007, step 3). A list keeps the state
- //! the title sets for its draws (pipeline, descriptor heaps, root
- //! arguments, vertex and index buffers, targets); each draw then brings the
- //! host list up to date: the host pipeline and our root signature, the
- //! user data the translated shaders read, the host copies of the buffers
- //! and descriptors they read, and the states of the textures involved.
- //! State the host keeps across draws (viewports, scissors, blend factor,
- //! stencil reference, topology, targets) is set on the host list as the
- //! title sets it.
- use std::sync::atomic::{AtomicU64, Ordering};
- use victory_shader::{ResourceType, RootType, UsedResource};
- use crate::descriptor::View;
- use windows::Win32::Foundation::RECT;
- use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
- use windows::Win32::Graphics::Direct3D12::*;
- use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
- use windows::core::Interface;
- use crate::host::HostList;
- use crate::object::This;
- use crate::pipeline::host::HostPipeline;
- /// A root argument as the title set it.
- #[derive(Debug, Clone, Default)]
- enum Root {
- #[default]
- None,
- /// A descriptor table's first descriptor (an address in a heap).
- Table(u64),
- Constants(Vec<u32>),
- /// A root view's GPU address.
- View(u64),
- }
- #[repr(C)]
- #[derive(Debug, Clone, Copy, Default)]
- pub(crate) struct VertexView {
- address: u64,
- size: u32,
- stride: u32,
- }
- #[repr(C)]
- #[derive(Debug, Clone, Copy, Default)]
- pub(crate) struct IndexView {
- address: u64,
- size: u32,
- format: u32,
- }
- /// What one title list has set, and what its host list was last given.
- #[derive(Default)]
- pub(crate) struct State {
- pipeline: usize,
- /// View heap, sampler heap.
- heaps: [usize; 2],
- graphics: Vec<Root>,
- compute: Vec<Root>,
- vertex: [VertexView; 32],
- index: IndexView,
- /// Bound render target and depth resources, for their host states.
- targets: Vec<usize>,
- depth: usize,
- /// The title's primitive topology (the host's may differ).
- topology: u32,
- /// What the host list has: pipeline, root signature, heaps.
- host_pipeline: usize,
- /// Graphics, compute.
- host_roots: [usize; 2],
- host_heaps: [usize; 2],
- /// Tables made afresh in this list: (table, what it holds) → first
- /// dynamic slot.
- fresh_tables: std::collections::HashMap<(u64, u64), u32>,
- /// The dynamic slots the list holds: title heap, first, count; given
- /// back when the list is reset or released.
- dynamic: Vec<(usize, u32, u32)>,
- }
- impl Drop for State {
- fn drop(&mut self) {
- for &(heap, first, n) in &self.dynamic {
- crate::descriptor::release_dynamic(heap, first, n);
- }
- }
- }
- /// Draws recorded on the host GPU since the last frame line.
- static DRAWN: AtomicU64 = AtomicU64::new(0);
- /// Draws run on the host so far.
- pub(crate) fn drawn() -> u64 {
- DRAWN.load(Ordering::Relaxed)
- }
- /// The draws traced since the last present (diagnostics builds, with
- /// debug logging for this module): logged when the frame comes out black.
- #[cfg(feature = "diagnostics")]
- static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
- /// The draws traced since the last call.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn take_frame() -> Vec<String> {
- std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
- }
- /// Marks the last traced draw as not run on the host.
- #[cfg(feature = "diagnostics")]
- fn dropped() {
- if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
- last.push_str(" DROPPED");
- }
- }
- /// Dispatches run on the host so far.
- static DISPATCHED: AtomicU64 = AtomicU64::new(0);
- pub(crate) fn dispatched() -> u64 {
- DISPATCHED.load(Ordering::Relaxed)
- }
- /// The host address of a root view: its buffer's host copy, or for a
- /// constant buffer not 256-byte aligned there (the console needs 16) a
- /// copy in upload memory.
- /// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
- /// other views as 1 MiB (both cut at their buffer's end).
- fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
- let shadow = crate::shadow::find(address, 1)?;
- let len = shadow
- .left(address)
- .min(if srv { 1 << 20 } else { 1 << 16 });
- let gpu = shadow.gpu(address);
- if srv || gpu % 256 == 0 {
- shadow.refresh(list, address, len);
- return Some(gpu);
- }
- let (gpu, to) = list.scratch(len)?;
- list.defer_fill(to, address as *const u8, len as usize);
- Some(gpu)
- }
- macro_rules! once {
- ($($arg:tt)*) => {{
- static ONCE: std::sync::Once = std::sync::Once::new();
- ONCE.call_once(|| tracing::warn!($($arg)*));
- }};
- }
- fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
- let slot = slot as usize;
- if roots.len() <= slot {
- roots.resize(slot + 1, Root::None);
- }
- roots[slot] = root;
- }
- impl State {
- pub(crate) fn reset(&mut self, pipeline: This) {
- *self = State::default();
- self.pipeline = pipeline as usize;
- }
- /// The title's topology; console-only ones become host lists (see
- /// [`crate::primitive`]).
- pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
- self.topology = topology;
- let host = match topology {
- RECTANGLES => 4,
- TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
- once!(topology, "console topology drawn as a triangle list");
- 4
- }
- t => t,
- };
- // SAFETY: an open list.
- unsafe {
- list.list
- .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
- };
- }
- pub(crate) fn set_pipeline(&mut self, pipeline: This) {
- self.pipeline = pipeline as usize;
- }
- pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
- self.heaps = [0; 2];
- for &h in heaps {
- if !h.is_null() {
- let samplers = crate::descriptor::heap(h).samplers();
- self.heaps[usize::from(samplers)] = h as usize;
- }
- }
- }
- fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
- if compute {
- &mut self.compute
- } else {
- &mut self.graphics
- }
- }
- pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
- set(self.roots(compute), slot, Root::Table(handle));
- }
- pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
- set(self.roots(compute), slot, Root::View(address));
- }
- pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
- let roots = self.roots(compute);
- let s = slot as usize;
- if !matches!(roots.get(s), Some(Root::Constants(_))) {
- set(roots, slot, Root::Constants(Vec::new()));
- }
- if let Root::Constants(c) = &mut roots[s] {
- let end = offset as usize + values.len();
- if c.len() < end {
- c.resize(end, 0);
- }
- c[offset as usize..end].copy_from_slice(values);
- }
- }
- pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
- for (i, v) in views.iter().enumerate() {
- if let Some(slot) = self.vertex.get_mut(start as usize + i) {
- *slot = *v;
- }
- }
- }
- pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
- self.index = view.copied().unwrap_or_default();
- }
- /// Render targets and depth, set on the host list at once.
- pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
- let Some(host) = crate::host::host() else {
- return;
- };
- self.targets.clear();
- let mut rtvs = Vec::new();
- for &h in handles {
- let Some(record) = crate::descriptor::rtv_record(h) else {
- once!(
- handle = format_args!("{h:#x}"),
- "render target without a recorded view"
- );
- continue;
- };
- let Some(texture) = crate::resource::host_resource(record.resource) else {
- continue;
- };
- self.targets.push(record.resource as usize);
- #[cfg(feature = "diagnostics")]
- crate::capture::note_target(record.resource);
- rtvs.push(host.rtv(texture, record.desc().as_ref()));
- }
- self.depth = 0;
- let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
- let texture = crate::resource::host_resource(record.resource)?;
- self.depth = record.resource as usize;
- #[cfg(feature = "diagnostics")]
- crate::capture::note_target(record.resource);
- Some(host.dsv(texture, record.depth_desc().as_ref()))
- });
- // SAFETY: an open list; the views were just made.
- unsafe {
- list.list.OMSetRenderTargets(
- rtvs.len() as u32,
- (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
- false,
- dsv.as_ref().map(std::ptr::from_ref),
- )
- };
- }
- /// The user-data value of a root argument, as translated shaders read
- /// it: a table's byte offset in its heap, a constant's value.
- fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
- match (self.roots_ref(compute).get(usize::from(slot)), root) {
- (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
- Some(heap) => (handle - heap.start) as u32,
- None => {
- once!(
- handle = format_args!("{handle:#x}"),
- "descriptor table outside the bound heaps"
- );
- 0
- }
- },
- (Some(Root::Constants(c)), RootType::Constants) => {
- c.get(dword as usize).copied().unwrap_or(0)
- }
- _ => {
- once!(
- slot,
- ?root,
- "a shader reads a root argument the title did not set"
- );
- 0
- }
- }
- }
- /// The bound heap holding `handle`.
- fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
- self.heaps
- .iter()
- .filter(|&&h| h != 0)
- .map(|&h| crate::descriptor::heap(h as This))
- .find(|h| h.index(handle).is_some())
- }
- /// Brings the host list up to date for a draw; false if the draw cannot
- /// run on the host.
- fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
- self.prepare_for(list, indexed, false)
- }
- /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
- fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
- let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
- return false;
- };
- if p.compute || p.mesh != mesh {
- once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
- return false;
- }
- self.bind(list, p, false);
- let l = &list.list;
- // Vertex buffers the input layout reads.
- let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
- let mut count = 0;
- for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
- if p.slots & 1 << slot == 0 {
- continue;
- }
- count = slot + 1;
- if v.address == 0 || v.size == 0 {
- continue;
- }
- let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
- continue;
- };
- shadow.refresh(list, v.address, u64::from(v.size));
- *view = D3D12_VERTEX_BUFFER_VIEW {
- BufferLocation: shadow.gpu(v.address),
- SizeInBytes: v.size,
- StrideInBytes: v.stride,
- };
- }
- // SAFETY: an open list; the views name live host buffers.
- unsafe {
- if count > 0 {
- l.IASetVertexBuffers(0, Some(&views[..count]));
- }
- }
- if indexed {
- let v = self.index;
- let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
- return false;
- };
- shadow.refresh(list, v.address, u64::from(v.size));
- let view = D3D12_INDEX_BUFFER_VIEW {
- BufferLocation: shadow.gpu(v.address),
- SizeInBytes: v.size,
- Format: DXGI_FORMAT(v.format as i32),
- };
- // SAFETY: an open list; the view names a live host buffer.
- unsafe { l.IASetIndexBuffer(Some(&view)) };
- }
- const RENDER_TARGET: u32 = 0x4;
- const DEPTH_WRITE: u32 = 0x10;
- for &t in &self.targets {
- crate::list::ensure_state(list, t as This, RENDER_TARGET);
- }
- if self.depth != 0 {
- crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
- }
- true
- }
- /// A descriptor a shader reads through a table: its host slot made if
- /// it changed, constant data copied, textures made readable.
- /// What draws and dispatches share: heaps, our root signature, the
- /// pipeline, and per stage the user data, root views and the
- /// descriptors its tables hold.
- fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
- let l = &list.list;
- // Heaps first: a root signature with directly indexed heaps must be
- // set after them.
- if self.host_heaps != self.heaps {
- let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
- .heaps
- .iter()
- .filter(|&&h| h != 0)
- .filter_map(|&h| crate::descriptor::heap(h as This).host())
- .map(|h| Some(h.heap.clone()))
- .collect();
- // SAFETY: an open list and shader-visible heaps.
- unsafe { l.SetDescriptorHeaps(&heaps) };
- self.host_heaps = self.heaps;
- self.host_roots = [0; 2];
- }
- let root = p.root.as_raw() as usize;
- if self.host_roots[usize::from(compute)] != root {
- // SAFETY: an open list and a live root signature.
- unsafe {
- if compute {
- l.SetComputeRootSignature(&p.root);
- } else {
- l.SetGraphicsRootSignature(&p.root);
- }
- }
- self.host_roots[usize::from(compute)] = root;
- }
- if self.host_pipeline != self.pipeline {
- // SAFETY: an open list and a live pipeline.
- unsafe { l.SetPipelineState(&p.pso) };
- self.host_pipeline = self.pipeline;
- list.used_pipeline(&p.name);
- }
- for stage in &p.stages {
- let t = stage.translated();
- let made = self.tables(list, &t.used, compute);
- if let Some((param, dwords)) = stage.user_data {
- let mut values = vec![0u32; dwords as usize];
- for u in &t.host.user_data {
- let fresh = made
- .iter()
- .find(|m| m.0 == u.slot && u.root == RootType::Table);
- values[u.index as usize] = match fresh {
- Some(&(_, offset)) => offset,
- None => self.user_value(compute, u.slot, u.root, u.dword),
- };
- }
- // SAFETY: an open list; `values` covers the parameter.
- unsafe {
- if compute {
- l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
- } else {
- l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
- }
- }
- }
- for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
- for &(slot, param) in views {
- let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
- else {
- once!(slot, "a shader reads a root view the title did not set");
- continue;
- };
- let Some(gpu) = root_view(list, *address, srv) else {
- continue;
- };
- // SAFETY: an open list; the address is in live memory.
- unsafe {
- match (compute, srv) {
- (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
- (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
- (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
- (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
- }
- }
- }
- }
- }
- }
- /// Runs a dispatch on the host.
- pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
- let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
- once!(
- pipeline = format_args!("{:#x}", self.pipeline),
- "a dispatch without a host pipeline dropped"
- );
- return;
- };
- if !p.compute {
- once!("a dispatch with a graphics pipeline");
- return;
- }
- self.bind(list, p, true);
- #[cfg(feature = "diagnostics")]
- list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
- // SAFETY: an open list with everything set.
- unsafe { list.list.Dispatch(x, y, z) };
- DISPATCHED.fetch_add(1, Ordering::Relaxed);
- }
- /// What a draw or dispatch runs, for the device-removed report
- /// (diagnostics): the pipeline, then per stage the user data it gets
- /// (with the view at that heap index, if one is), the host addresses
- /// of its root views and the views its tables name.
- #[cfg(feature = "diagnostics")]
- fn op_text(&self, kind: String, compute: bool) -> String {
- use std::fmt::Write;
- let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
- return kind;
- };
- let mut text = format!("{kind} {}", p.name);
- let views = (self.heaps[0] != 0)
- .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
- .flatten();
- for stage in &p.stages {
- let t = stage.translated();
- let _ = write!(text, " | {}:", stage.shader.hash);
- for u in &t.host.user_data {
- let v = self.user_value(compute, u.slot, u.root, u.dword);
- let _ = write!(text, " u{}={v:#x}", u.index);
- let index = if u.root == RootType::Table { v / 32 } else { v };
- if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
- let _ = write!(text, " [heap {index}: {slot}]");
- }
- }
- for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
- if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
- let host = crate::shadow::find(*address, 1)
- .map(|s| (s.gpu(*address), s.left(*address)));
- let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
- }
- }
- }
- let _ = write!(text, " tables {:?}", self.reads(compute));
- text
- }
- /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
- /// programs are one-dimensional).
- pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
- #[cfg(feature = "diagnostics")]
- self.trace("mesh", x, 0);
- let ran = self.prepare_for(list, false, true)
- && match list.list.cast::<ID3D12GraphicsCommandList6>() {
- Ok(l6) => {
- #[cfg(feature = "diagnostics")]
- list.note_op(|| self.op_text(format!("mesh {x}"), false));
- // SAFETY: an open list with everything set.
- unsafe { l6.DispatchMesh(x, 1, 1) };
- DRAWN.fetch_add(1, Ordering::Relaxed);
- true
- }
- Err(_) => false,
- };
- #[cfg(feature = "diagnostics")]
- if !ran {
- dropped();
- }
- #[cfg(not(feature = "diagnostics"))]
- let _ = ran;
- }
- fn roots_ref(&self, compute: bool) -> &Vec<Root> {
- if compute {
- &self.compute
- } else {
- &self.graphics
- }
- }
- fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
- let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
- return;
- };
- let handle = table + u64::from(u.table_offset_dwords) * 4;
- let Some(heap) = self.heap_of(handle) else {
- return;
- };
- let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
- return;
- };
- if let Some(view) = host.mirror(index, handle, true) {
- readable(list, u, &view);
- }
- }
- /// The descriptors a shader reads through tables. Tables holding a
- /// constant buffer are made afresh for the draw in dynamic slots, with
- /// the constant data copied to upload memory when the list is
- /// submitted: the host wants constant buffers 256-byte aligned, the
- /// console only 16. Returns those tables' new byte offsets by root
- /// parameter; the other tables' slots are made from the title's.
- ///
- /// Within a list, the same table holding the same descriptors is made
- /// once: its constant data is copied at submission either way, and the
- /// big tables the world binds would otherwise take hundreds of slots per
- /// draw, wrapping the dynamic slots onto lists not yet submitted.
- fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
- let tables = |u: &&UsedResource| u.root == RootType::Table;
- let mut fresh: Vec<u8> = used
- .iter()
- .filter(tables)
- .filter(|u| u.kind == ResourceType::Cbv)
- .map(|u| u.slot)
- .collect();
- fresh.sort_unstable();
- fresh.dedup();
- for u in used.iter().filter(tables) {
- if !fresh.contains(&u.slot) {
- self.table_entry(list, u, compute);
- }
- }
- let mut made = Vec::new();
- for slot in fresh {
- let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
- continue;
- };
- let entries: Vec<&UsedResource> = used
- .iter()
- .filter(tables)
- .filter(|u| u.slot == slot)
- .collect();
- let Some(heap) = self.heap_of(table) else {
- continue;
- };
- let Some(host) = heap.host() else {
- continue;
- };
- let n = entries
- .iter()
- .map(|u| u.table_offset_dwords / 8 + 1)
- .max()
- .unwrap_or(1);
- // The table and what its entries hold (record words).
- let key = {
- use std::hash::{Hash, Hasher};
- let mut h = std::collections::hash_map::DefaultHasher::new();
- for k in 0..n {
- let at = table + u64::from(k) * 32;
- // SAFETY: a descriptor slot in title memory.
- unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
- }
- (table, h.finish())
- };
- if let Some(&first) = self.fresh_tables.get(&key) {
- for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
- let handle = table + u64::from(u.table_offset_dwords) * 4;
- if let Some(view) = crate::descriptor::view(handle) {
- readable(list, u, &view);
- }
- }
- made.push((slot, first * 32));
- continue;
- }
- let Some(first) = host.dynamic(n) else {
- continue;
- };
- self.fresh_tables.insert(key, first);
- self.dynamic
- .push((std::ptr::from_ref(heap) as usize, first, n));
- // The whole range: a shader may index past the entries its
- // used-resource list names (descriptor arrays).
- for k in 0..n {
- let index = first + k;
- let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
- match crate::descriptor::view(table + u64::from(k) * 32) {
- Some(View::Constant(address, size)) => {
- let Some((gpu, to)) = list.scratch(u64::from(size)) else {
- host.make_null(index);
- continue;
- };
- list.defer_fill(to, address as *const u8, size as usize);
- host.constant_at(index, gpu, size);
- }
- Some(view) => {
- host.make_at(index, &view);
- if let Some(u) = used {
- readable(list, u, &view);
- }
- }
- None => {
- host.make_null(index);
- if used.is_some() {
- once!(slot, "a table entry without a view");
- }
- }
- }
- }
- made.push((slot, first * 32));
- }
- made
- }
- /// The first draws, at debug level: what they bind and read
- /// (diagnostics builds).
- #[cfg(feature = "diagnostics")]
- fn trace(&self, kind: &str, count: u32, first: u32) {
- static TRACED: AtomicU64 = AtomicU64::new(0);
- if !tracing::enabled!(tracing::Level::DEBUG) {
- return;
- }
- let listed = crate::capture::listed(crate::queue::presented() + 1);
- let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
- let targets: Vec<String> = self
- .targets
- .iter()
- .filter_map(|&t| crate::resource::host_resource(t as This))
- .map(|t| {
- // SAFETY: a live resource.
- let d = unsafe { t.GetDesc() };
- format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
- })
- .collect();
- let v = self.vertex[0];
- let line = format!(
- "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
- self.topology,
- self.pipeline,
- v.address,
- v.size,
- v.stride,
- self.reads(false)
- );
- if logged {
- tracing::debug!("draw {line}");
- }
- let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
- if frame.len() < 256 {
- frame.push(line);
- }
- }
- /// What a draw's shaders read, one line per used resource (diagnostics
- /// builds).
- #[cfg(feature = "diagnostics")]
- fn reads(&self, compute: bool) -> Vec<String> {
- let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
- return vec!["no host pipeline".into()];
- };
- let mut out = Vec::new();
- for stage in &p.stages {
- let t = stage.translated();
- for u in &t.used {
- let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
- (RootType::Table, Some(Root::Table(table))) => {
- let handle = table + u64::from(u.table_offset_dwords) * 4;
- describe(crate::descriptor::view(handle).as_ref())
- }
- (root, _) => format!("{root:?}"),
- };
- out.push(format!(
- "{} {:?} s{}+{}: {what}",
- stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
- ));
- }
- }
- out
- }
- pub(crate) fn draw(
- &mut self,
- list: &HostList,
- vertices: u32,
- instances: u32,
- first: u32,
- first_instance: u32,
- ) {
- #[cfg(feature = "diagnostics")]
- self.trace("draw", vertices, first);
- let rects = self.topology == RECTANGLES;
- let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
- if ran {
- // Rectangles were expanded into their own vertex buffers.
- let (count, from) = if rects {
- (vertices / 3 * 6, 0)
- } else {
- (vertices, first)
- };
- #[cfg(feature = "diagnostics")]
- list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
- // SAFETY: an open list with everything set.
- unsafe {
- list.list
- .DrawInstanced(count, instances, from, first_instance)
- };
- DRAWN.fetch_add(1, Ordering::Relaxed);
- }
- #[cfg(feature = "diagnostics")]
- if !ran {
- dropped();
- }
- }
- /// Binds vertex buffers holding the rectangles of vertices `first..first
- /// + count` as triangles, made when the list is submitted.
- fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
- let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
- return false;
- };
- let rects = u64::from(count / 3);
- for slot in 0..32 {
- let elements: Vec<(u32, u32)> = p
- .inputs
- .iter()
- .filter(|e| e.slot == slot && !e.per_instance)
- .map(|e| (e.offset, e.format))
- .collect();
- if elements.is_empty() {
- continue;
- }
- let v = self.vertex[slot as usize];
- let stride = u64::from(v.stride);
- let from = v.address + u64::from(first) * stride;
- if v.address == 0
- || stride == 0
- || u64::from(first + count) * stride > u64::from(v.size)
- || crate::shadow::find(from, rects * 3 * stride).is_none()
- {
- once!(slot, "rectangle vertices outside their buffer");
- return false;
- }
- let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
- return false;
- };
- let (from, to, stride) = (from as usize, to as usize, stride as usize);
- let n = rects as usize;
- list.defer_host(move || {
- // SAFETY: the vertices lie in a title buffer (checked when
- // recorded) and the scratch memory is the list's.
- let (src, dst) = unsafe {
- (
- std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
- std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
- )
- };
- crate::primitive::expand_rects(src, dst, stride, &elements);
- });
- let view = D3D12_VERTEX_BUFFER_VIEW {
- BufferLocation: gpu,
- SizeInBytes: (rects * 6 * stride as u64) as u32,
- StrideInBytes: v.stride,
- };
- // SAFETY: an open list; the view names live scratch memory.
- unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
- }
- true
- }
- pub(crate) fn draw_indexed(
- &mut self,
- list: &HostList,
- indices: u32,
- instances: u32,
- first: u32,
- base: i32,
- first_instance: u32,
- ) {
- #[cfg(feature = "diagnostics")]
- self.trace("indexed", indices, first);
- if self.topology == RECTANGLES {
- once!("indexed rectangles not drawn");
- }
- let ran = self.topology != RECTANGLES && self.prepare(list, true);
- if ran {
- #[cfg(feature = "diagnostics")]
- list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
- // SAFETY: an open list with everything set.
- unsafe {
- list.list
- .DrawIndexedInstanced(indices, instances, first, base, first_instance)
- };
- DRAWN.fetch_add(1, Ordering::Relaxed);
- }
- #[cfg(feature = "diagnostics")]
- if !ran {
- dropped();
- }
- }
- }
- /// Gets what a shader reads or writes through a view ready: buffer data
- /// copied, textures moved to the state they need.
- fn readable(list: &HostList, u: &UsedResource, view: &View) {
- const SHADER_RESOURCE: u32 = 0x40 | 0x80;
- const UNORDERED_ACCESS: u32 = 0x8;
- let placed = crate::descriptor::host::placed_texture(view);
- let view = placed.as_ref().unwrap_or(view);
- // Buffer views read title memory: their range is copied at submission;
- // what shaders write through unordered access goes back to it after.
- if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
- && len > 0
- && let Some(shadow) = crate::shadow::find(address, len)
- {
- shadow.refresh(list, address, len);
- if u.kind == ResourceType::Uav {
- shadow.gpu_writes(list, address, len);
- }
- }
- match (view, u.kind) {
- (View::Shader(resource, _), ResourceType::Srv) => {
- if let Some(t) = crate::resource::host_resource(*resource as This)
- && crate::texture::title_written(t)
- {
- crate::texture::upload(list, *resource as This, t);
- }
- crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
- #[cfg(feature = "diagnostics")]
- if let Some(t) = crate::resource::host_resource(*resource as This) {
- // SAFETY: a live resource.
- let d = unsafe { t.GetDesc() };
- if d.Flags.0 & 7 == 0 {
- tracing::debug!(
- resource = format_args!("{resource:#x}"),
- ?d,
- "a shader reads a texture the title fills"
- );
- }
- }
- }
- (View::Unordered(resource, _, _), ResourceType::Uav) => {
- #[cfg(feature = "diagnostics")]
- crate::capture::note_target(*resource as This);
- crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
- }
- _ => {}
- }
- }
- /// A view in a few words (diagnostics builds).
- #[cfg(feature = "diagnostics")]
- fn describe(view: Option<&View>) -> String {
- let texture = |r: This| {
- crate::resource::host_resource(r).map(|t| {
- // SAFETY: a live resource.
- let d = unsafe { t.GetDesc() };
- format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
- })
- };
- match view {
- None => "no view".into(),
- Some(v @ View::Shader(r, _)) => texture(*r as This)
- .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
- Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
- Some(View::Placed(u, r, d)) => format!(
- "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
- r[0],
- u64::from(r[4]) | u64::from(r[5]) << 32,
- r[6],
- r[8],
- r[11],
- u64::from(d[10]) | u64::from(d[11]) << 32
- ),
- // The first four values, as a colour rectangle's constants are.
- Some(View::Constant(address, size))
- if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
- {
- // SAFETY: 16 committed bytes of title memory.
- let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
- format!("Constant({address:#x}, {size}) {v:?}")
- }
- Some(v) => format!("{v:?}").chars().take(60).collect(),
- }
- }
- /// The console's own primitive topologies.
- const TRIANGLE_FAN: u32 = 6;
- const RECTANGLES: u32 = 17;
- const LINE_LOOP: u32 = 18;
- const QUADS: u32 = 19;
- const QUAD_STRIP: u32 = 20;
- /// Fixed-function state, straight onto the host list.
- pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
- // SAFETY: an open list.
- unsafe { list.list.RSSetViewports(viewports) };
- }
- pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
- // SAFETY: an open list.
- unsafe { list.list.RSSetScissorRects(rects) };
- }
- pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
- // SAFETY: an open list.
- unsafe { list.list.OMSetBlendFactor(factor) };
- }
- pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
- // SAFETY: an open list.
- unsafe { list.list.OMSetStencilRef(reference) };
- }
|