| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739 |
- //! Indirect execution's arguments, bounded before the GPU reads them. The
- //! title's own compute passes write most of them; a pass we drop or
- //! translate wrongly leaves whatever the memory held, and a draw of four
- //! billion vertices or a dispatch past the host's limits runs until the
- //! host resets the display driver. So active records are copied and clamped
- //! on the GPU into a device-local scratch buffer, just before execution, by a
- //! compute shader of ours (HLSL compiled by the system's compiler; a 5.1
- //! shader with its root signature inside), leaving the title's argument and
- //! count buffers untouched.
- //!
- //! The scratch buffer is left readable as indirect arguments after a clamp
- //! and stays so until the next clamp into it, which moves it straight back
- //! to unordered access; it goes back to the common state once, when the
- //! list closes. The executions that read it record no barrier of their
- //! own, so draws that read records clamped together (`crate::draw`'s
- //! windows) follow each other with nothing between them. Before, each
- //! execution was followed by a move of the scratch buffer back to the
- //! common state, which drivers may treat as a full wait.
- //!
- //! When a count buffer is given, threads at or past `min(max, count)` return
- //! immediately without charging the list's budget or reading uninitialized
- //! tail slots. Each list has a budget (2^27 vertex instances or threads,
- //! groups counted as 64 threads, mesh groups as 128): active records past it
- //! run empty, saturating without 32-bit wraparound so a list of thousands of
- //! garbage records cannot run for seconds either.
- //!
- //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
- //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
- //! dispatches, the budget) cut legitimate work beyond them; raise them if
- //! the title needs more.
- use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
- use windows::Win32::Graphics::Direct3D::ID3DBlob;
- use windows::Win32::Graphics::Direct3D12::*;
- use windows::core::s;
- use crate::host::{HostList, host, transition};
- const SOURCE: &str = r#"
- #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
- cbuffer Record : register(b0) {
- uint kind;
- uint stride;
- uint records;
- uint args_offset;
- // Bit 0: a count buffer bounds the records. Bit 1: the records are a
- // window clamped ahead of their draws: one that asks for more than can
- // run is left empty and costs nothing.
- uint has_count;
- uint count_offset;
- };
- ByteAddressBuffer src_args : register(t0);
- ByteAddressBuffer count_buf : register(t1);
- RWByteAddressBuffer dst_args : register(u0);
- // The list's work so far (vertex instances, threads): past the budget,
- // records run empty.
- RWByteAddressBuffer budget : register(u1);
- static const uint BUDGET = 1u << 27;
- // Groups of one dispatch; more run empty.
- static const uint GROUPS = 1u << 20;
- [RootSignature(RS)]
- [numthreads(64, 1, 1)]
- void main(uint3 id : SV_DispatchThreadID) {
- uint eff_count = records;
- bool ahead = (has_count & 2u) != 0;
- if ((has_count & 1u) != 0) {
- eff_count = min(eff_count, count_buf.Load(count_offset));
- }
- if (id.x >= eff_count) return;
- uint src_at = args_offset + id.x * stride;
- uint dst_at = id.x * stride;
- uint cost;
- uint2 draw_counts = uint2(0, 0);
- uint3 groups = uint3(0, 0, 0);
- if (kind <= 1) {
- // Draws: vertex or index count, then instances.
- uint2 asked = src_args.Load2(src_at);
- if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) {
- asked = uint2(0, 0);
- }
- uint count = min(asked.x, 1u << 24);
- uint instances = min(asked.y, (1u << 26) / max(count, 1u));
- cost = count * instances;
- draw_counts = uint2(count, instances);
- } else if (kind == 2) {
- uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
- // x * y fits 32 bits; the whole count may not.
- if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
- g = uint3(0, 0, 0);
- }
- cost = g.x * g.y * g.z * 64u;
- groups = g;
- } else {
- // Mesh dispatches: the console's are one-dimensional.
- uint3 g = src_args.Load3(src_at);
- // Ahead of its draw, a record over the most a dispatch runs is a
- // slot the title has not filled (the title leaves all
- // ones there): empty, and not counted below either.
- if (ahead && g.x > 65535u) {
- g = uint3(0, 0, 0);
- }
- // Diagnostics, in the budget buffer's next words: the largest
- // group count a mesh record asked for, and the groups asked in all.
- uint was;
- budget.InterlockedMax(4, g.x, was);
- budget.InterlockedAdd(8, min(g.x, 1u << 24), was);
- g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
- cost = g.x * g.y * g.z * 128u;
- groups = g;
- }
- bool over = false;
- if (cost > 0) {
- uint before;
- budget.InterlockedOr(0, 0, before);
- [allow_uav_condition]
- while (before < BUDGET) {
- uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost);
- uint prev;
- budget.InterlockedCompareExchange(0, before, next, prev);
- if (prev == before) break;
- before = prev;
- }
- over = before >= BUDGET || BUDGET - before < cost;
- }
- if (kind <= 1) {
- if (over) {
- draw_counts = uint2(0, 0);
- }
- dst_args.Store2(dst_at, draw_counts);
- for (uint off = 8; off < stride; off += 4) {
- dst_args.Store(dst_at + off, src_args.Load(src_at + off));
- }
- } else {
- if (over) {
- groups = uint3(0, 0, 0);
- }
- dst_args.Store3(dst_at, groups);
- for (uint off = 12; off < stride; off += 4) {
- dst_args.Store(dst_at + off, src_args.Load(src_at + off));
- }
- }
- }
- "#;
- struct Clamp {
- root: ID3D12RootSignature,
- pso: ID3D12PipelineState,
- }
- // SAFETY: D3D12 objects are free-threaded.
- unsafe impl Send for Clamp {}
- // SAFETY: as above.
- unsafe impl Sync for Clamp {}
- fn clamp() -> Option<&'static Clamp> {
- static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
- CLAMP
- .get_or_init(|| match make() {
- Ok(c) => Some(c),
- Err(e) => {
- tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
- None
- }
- })
- .as_ref()
- }
- fn make() -> windows::core::Result<Clamp> {
- let device = &host().ok_or_else(windows::core::Error::empty)?.device;
- make_for(device)
- }
- fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
- let mut code: Option<ID3DBlob> = None;
- let mut errors: Option<ID3DBlob> = None;
- // SAFETY: the source and names live through the call; out pointers ours.
- let compiled = unsafe {
- D3DCompile(
- SOURCE.as_ptr().cast(),
- SOURCE.len(),
- s!("clamp"),
- None,
- None,
- s!("main"),
- s!("cs_5_1"),
- 0,
- 0,
- &mut code,
- Some(&mut errors),
- )
- };
- if let Err(e) = compiled {
- if let Some(errors) = errors {
- // SAFETY: the blob's own bytes.
- let text = unsafe {
- std::slice::from_raw_parts(
- errors.GetBufferPointer().cast::<u8>(),
- errors.GetBufferSize(),
- )
- };
- tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
- }
- return Err(e);
- }
- let code = code.ok_or_else(windows::core::Error::empty)?;
- // SAFETY: the blob's own bytes; the root signature is inside the shader.
- unsafe {
- let bytes =
- std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
- let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
- let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
- pRootSignature: std::mem::transmute_copy(&root),
- CS: D3D12_SHADER_BYTECODE {
- pShaderBytecode: bytes.as_ptr().cast(),
- BytecodeLength: bytes.len(),
- },
- ..Default::default()
- })?;
- Ok(Clamp { root, pso })
- }
- }
- /// Minimum record byte stride for a supported PC indirect argument `kind`.
- fn min_stride(kind: u32) -> Option<u32> {
- match kind {
- 0 => Some(16),
- 1 => Some(20),
- 2 | 10 => Some(12),
- _ => None,
- }
- }
- /// Validates record alignment and returns the scratch byte size `stride * records`.
- fn validate_layout(
- (kind, stride, records): (u32, u32, u32),
- src_offset: u64,
- count_offset: Option<u64>,
- ) -> Option<u64> {
- let min = min_stride(kind)?;
- if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
- return None;
- }
- if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
- return None;
- }
- let bytes = u64::from(stride).checked_mul(u64::from(records))?;
- (bytes <= u64::from(u32::MAX)).then_some(bytes)
- }
- /// Records, in `list`, the non-destructive clamp of up to `records` records of
- /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
- /// by the 32-bit count in `count` when given) into a device-local scratch
- /// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT`
- /// until the next clamp into it: executions read it with no barrier of
- /// their own. Replaces the list's compute root signature and pipeline
- /// (callers bind theirs after). `None` if the clamp or alignment is not
- /// available.
- pub(crate) fn bound(
- list: &HostList,
- src: (&ID3D12Resource, u64),
- count: Option<(&ID3D12Resource, u64)>,
- spec: (u32, u32, u32),
- ) -> Option<ID3D12Resource> {
- let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
- let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
- clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst)
- }
- /// [`bound`] for a window of records clamped ahead of the draws that will
- /// read them (`crate::draw`'s windows; no count buffer). The records past
- /// the ones the title filled are whatever the buffer holds, and each
- /// record clamped charges the list's budget when it is clamped: a slot of
- /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
- /// charged a sixteenth of the budget, so sixteen of them emptied every
- /// draw of the list after them (run 93: "the largest group count asked for
- /// 4294967295", 43 to 153 such records a frame). Here a record that asks
- /// for more than can run is left empty and charges nothing; a record
- /// clamped alone is clamped and charged as before.
- pub(crate) fn bound_ahead(
- list: &HostList,
- src: (&ID3D12Resource, u64),
- spec: (u32, u32, u32),
- ) -> Option<ID3D12Resource> {
- let bytes = validate_layout(spec, src.1, None)?;
- let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
- clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst)
- }
- /// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state
- /// the list left it in; afterwards the list knows it is readable as
- /// indirect arguments.
- #[allow(clippy::too_many_arguments)]
- fn clamp_into(
- list: &HostList,
- c: &Clamp,
- dst: &ID3D12Resource,
- budget: u64,
- src: (&ID3D12Resource, u64),
- count: Option<(&ID3D12Resource, u64)>,
- spec: (u32, u32, u32),
- ahead: bool,
- ) -> bool {
- let before = list.indirect_state(dst);
- let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead);
- if recorded {
- list.indirect_readable(dst);
- }
- recorded
- }
- /// Records the clamp into `dst`, which is in state `before` (common, or
- /// indirect arguments after an earlier clamp into it), and leaves `dst` in
- /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of
- /// their draws ([`bound_ahead`]). False, with nothing recorded, if the
- /// layout or the addresses do not fit the clamp.
- #[allow(clippy::too_many_arguments)]
- fn record_clamp_as(
- c: &Clamp,
- l: &ID3D12GraphicsCommandList,
- (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
- budget: u64,
- (src, src_offset): (&ID3D12Resource, u64),
- count: Option<(&ID3D12Resource, u64)>,
- (kind, stride, records): (u32, u32, u32),
- ahead: bool,
- ) -> bool {
- let Some(bytes) = validate_layout(
- (kind, stride, records),
- src_offset,
- count.map(|(_, off)| off),
- ) else {
- return false;
- };
- // SAFETY: live D3D12 buffer resources.
- let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
- if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
- return false;
- }
- let (src_gpu, args_offset) = match src_offset
- .checked_add(bytes)
- .filter(|&end| end <= u64::from(u32::MAX))
- {
- Some(_) => (src_base, src_offset as u32),
- None => {
- let Some(rebased) = src_base.checked_add(src_offset) else {
- return false;
- };
- (rebased, 0)
- }
- };
- let (count_gpu, has_count, count_offset) = match count {
- Some((buf, off)) => {
- // SAFETY: a live D3D12 buffer resource.
- let base = unsafe { buf.GetGPUVirtualAddress() };
- if !base.is_multiple_of(4) {
- return false;
- }
- match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
- Some(_) => (base, 1u32, off as u32),
- None => {
- let Some(rebased) = base.checked_add(off) else {
- return false;
- };
- (rebased, 1u32, 0u32)
- }
- }
- }
- None => (src_gpu, 0u32, 0u32),
- };
- let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
- // SAFETY: an open list; our root signature and pipeline; live source,
- // count, scratch destination, and budget buffers. `src` and `count` stay
- // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
- // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving
- // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every
- // earlier execution's reads of the scratch buffer; nothing else writes it.
- // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
- // waits for every earlier shader write out (the state changes stay).
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
- #[cfg(feature = "diagnostics")]
- let waits = crate::copystat::barrier_test() & 2 == 0;
- #[cfg(not(feature = "diagnostics"))]
- let waits = true;
- let first = [
- uav_barrier(),
- transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
- ];
- let second = [
- uav_barrier(),
- transition(
- dst,
- D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- ),
- ];
- let skip = usize::from(!waits);
- unsafe {
- // Earlier shader writes (the title's argument and count passes) first.
- l.ResourceBarrier(&first[skip..]);
- if records > 0 {
- l.SetComputeRootSignature(&c.root);
- l.SetPipelineState(&c.pso);
- l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
- l.SetComputeRootShaderResourceView(1, src_gpu);
- l.SetComputeRootShaderResourceView(2, count_gpu);
- l.SetComputeRootUnorderedAccessView(3, dst_gpu);
- l.SetComputeRootUnorderedAccessView(4, budget);
- l.Dispatch(records.div_ceil(64), 1, 1);
- }
- l.ResourceBarrier(&second[skip..]);
- }
- true
- }
- fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
- D3D12_RESOURCE_BARRIER {
- Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
- Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
- Anonymous: D3D12_RESOURCE_BARRIER_0 {
- UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
- pResource: std::mem::ManuallyDrop::new(None),
- }),
- },
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- use windows::Win32::Foundation::HANDLE;
- use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
- use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
- use windows::Win32::Graphics::Dxgi::*;
- use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
- use windows::core::Interface;
- const WORKER_CS: &str = r#"
- #define RS "UAV(u0)"
- RWByteAddressBuffer hits : register(u0);
- [RootSignature(RS)]
- [numthreads(1, 1, 1)]
- void main() {
- uint prev;
- hits.InterlockedAdd(0, 1, prev);
- }
- "#;
- struct WarpHarness {
- device: ID3D12Device,
- queue: ID3D12CommandQueue,
- allocator: ID3D12CommandAllocator,
- list: ID3D12GraphicsCommandList,
- fence: ID3D12Fence,
- submitted: u64,
- event: HANDLE,
- clamp: Clamp,
- worker: Clamp,
- }
- impl WarpHarness {
- fn new() -> Option<Self> {
- // SAFETY: plain DXGI WARP query and D3D12 test harness setup.
- unsafe {
- let factory: IDXGIFactory4 =
- CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
- let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
- let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
- if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
- return None;
- }
- let mut device: Option<ID3D12Device> = None;
- D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
- let device = device?;
- let queue: ID3D12CommandQueue = device
- .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
- Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
- ..Default::default()
- })
- .ok()?;
- let allocator: ID3D12CommandAllocator = device
- .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
- .ok()?;
- let list: ID3D12GraphicsCommandList = device
- .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
- .ok()?;
- let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
- let event = CreateEventW(None, false, false, None).ok()?;
- let clamp = make_for(&device).expect("clamp shader must compile on WARP");
- let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
- Some(Self {
- device,
- queue,
- allocator,
- list,
- fence,
- submitted: 0,
- event,
- clamp,
- worker,
- })
- }
- }
- /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
- fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
- let heap = D3D12_HEAP_PROPERTIES {
- Type: D3D12_HEAP_TYPE_CUSTOM,
- CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
- MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
- ..Default::default()
- };
- let desc = D3D12_RESOURCE_DESC {
- Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
- Width: size.max(4),
- Height: 1,
- DepthOrArraySize: 1,
- MipLevels: 1,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
- Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
- ..Default::default()
- };
- let mut buffer: Option<ID3D12Resource> = None;
- let mut data = std::ptr::null_mut();
- // SAFETY: plain buffer creation and persistent CPU mapping.
- unsafe {
- self.device
- .CreateCommittedResource(
- &heap,
- D3D12_HEAP_FLAG_NONE,
- &desc,
- D3D12_RESOURCE_STATE_COMMON,
- None,
- &mut buffer,
- )
- .unwrap();
- let buffer = buffer.unwrap();
- buffer.Map(0, None, Some(&mut data)).unwrap();
- let gpu = buffer.GetGPUVirtualAddress();
- (buffer, data.cast(), gpu)
- }
- }
- /// Device-local `DEFAULT`-heap UAV scratch buffer.
- fn default_uav(&self, size: u64) -> ID3D12Resource {
- let heap = D3D12_HEAP_PROPERTIES {
- Type: D3D12_HEAP_TYPE_DEFAULT,
- ..Default::default()
- };
- let desc = D3D12_RESOURCE_DESC {
- Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
- Width: size.max(64 << 10),
- Height: 1,
- DepthOrArraySize: 1,
- MipLevels: 1,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
- Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
- ..Default::default()
- };
- let mut buffer: Option<ID3D12Resource> = None;
- // SAFETY: plain device-local buffer creation.
- unsafe {
- self.device
- .CreateCommittedResource(
- &heap,
- D3D12_HEAP_FLAG_NONE,
- &desc,
- D3D12_RESOURCE_STATE_COMMON,
- None,
- &mut buffer,
- )
- .unwrap();
- }
- buffer.unwrap()
- }
- fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
- let arg = D3D12_INDIRECT_ARGUMENT_DESC {
- Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
- ..Default::default()
- };
- let desc = D3D12_COMMAND_SIGNATURE_DESC {
- ByteStride: stride,
- NumArgumentDescs: 1,
- pArgumentDescs: &arg,
- NodeMask: 0,
- };
- let mut sig: Option<ID3D12CommandSignature> = None;
- // SAFETY: valid single-argument command signature description.
- unsafe {
- self.device
- .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
- .unwrap();
- }
- sig.unwrap()
- }
- fn submit_and_wait(&mut self) {
- self.submitted += 1;
- // SAFETY: closing, executing, waiting on fence, and resetting our list.
- unsafe {
- self.list.Close().unwrap();
- let cmd: ID3D12CommandList = self.list.cast().unwrap();
- self.queue.ExecuteCommandLists(&[Some(cmd)]);
- self.queue.Signal(&self.fence, self.submitted).unwrap();
- self.fence
- .SetEventOnCompletion(self.submitted, self.event)
- .unwrap();
- WaitForSingleObject(self.event, INFINITE);
- self.allocator.Reset().unwrap();
- self.list.Reset(&self.allocator, None).unwrap();
- }
- }
- }
- fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
- let mut code: Option<ID3DBlob> = None;
- // SAFETY: source and entry names outlive `D3DCompile`.
- unsafe {
- D3DCompile(
- source.as_ptr().cast(),
- source.len(),
- s!("worker"),
- None,
- None,
- s!("main"),
- s!("cs_5_1"),
- 0,
- 0,
- &mut code,
- None,
- )?;
- let code = code.unwrap();
- let bytes = std::slice::from_raw_parts(
- code.GetBufferPointer().cast::<u8>(),
- code.GetBufferSize(),
- );
- let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
- let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
- pRootSignature: std::mem::transmute_copy(&root),
- CS: D3D12_SHADER_BYTECODE {
- pShaderBytecode: bytes.as_ptr().cast(),
- BytecodeLength: bytes.len(),
- },
- ..Default::default()
- })?;
- Ok(Clamp { root, pso })
- }
- }
- /// The compare of copies in the card's memory (`crate::host`), on the
- /// software adapter. Told 1 it flags the pieces whose bytes are not
- /// what was hashed last and leaves the hashes: a piece a shader changed
- /// and a later one changed back then looks untouched, which is right
- /// only if the piece was fetched after both. Told 2 (submissions sent
- /// ahead with the relay, whose pieces are fetched flight by flight) it
- /// stores the hash it made: each compare flags what changed since the
- /// compare before it, also a change back.
- #[test]
- fn warp_card_compare_stores_the_hash_it_made_when_told() {
- let Some(mut warp) = WarpHarness::new() else {
- return;
- };
- let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
- const PIECE: usize = 64 << 10;
- const PIECES: u32 = 3;
- let size = PIECE * PIECES as usize;
- let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
- let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
- let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
- let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
- // SAFETY: the mapping holds `size` bytes.
- unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
- // One pass over the three pieces; what it left in `differs` (7s
- // where it stored nothing).
- let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
- // SAFETY: our open list, live buffers, the compare's own root
- // signature; the mappings hold what is read and written.
- unsafe {
- for piece in 0..PIECES as usize {
- differs_ptr.cast::<u32>().add(piece).write_volatile(7);
- }
- warp.list.SetComputeRootSignature(&compare.root);
- warp.list.SetPipelineState(&compare.pso);
- let constants = [0u32, 0, size as u32, PIECES, 0, mode];
- warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
- warp.list.SetComputeRootShaderResourceView(1, now_gpu);
- warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
- warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
- warp.list.Dispatch(PIECES.div_ceil(64), 1, 1);
- }
- warp.submit_and_wait();
- // SAFETY: as above.
- [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() })
- };
- let at = PIECE + 1234;
- // SAFETY (each): inside the mapping.
- let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
- // 0: the hashes are stored, nothing is flagged.
- assert_eq!(run(&mut warp, 0), [7, 7, 7]);
- assert_eq!(run(&mut warp, 1), [0, 0, 0]);
- // A change in the second piece: flagged, and with 1 flagged again
- // (the hash stays the old one).
- set(content[at] ^ 0x40);
- assert_eq!(run(&mut warp, 1), [0, 1, 0]);
- assert_eq!(run(&mut warp, 1), [0, 1, 0]);
- // Changed back: with 1 the piece looks untouched.
- set(content[at]);
- assert_eq!(run(&mut warp, 1), [0, 0, 0]);
- // With 2 the change is flagged once, and the hash is the new one.
- set(content[at] ^ 0x40);
- assert_eq!(run(&mut warp, 2), [0, 1, 0]);
- assert_eq!(run(&mut warp, 2), [0, 0, 0]);
- // Changed back: flagged, where 1 saw nothing.
- set(content[at]);
- assert_eq!(run(&mut warp, 2), [0, 1, 0]);
- assert_eq!(run(&mut warp, 2), [0, 0, 0]);
- }
- /// The clamp compiles with the system's compiler and the host takes it.
- #[test]
- fn argument_clamp_builds() {
- if super::host().is_none() {
- return; // no host GPU here
- }
- assert!(super::clamp().is_some());
- }
- #[test]
- fn rejects_unaligned_or_undersized_layouts() {
- assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
- assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
- assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
- assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
- // Undersized strides for each kind.
- assert_eq!(validate_layout((0, 12, 1), 0, None), None);
- assert_eq!(validate_layout((1, 16, 1), 0, None), None);
- assert_eq!(validate_layout((2, 8, 1), 0, None), None);
- assert_eq!(validate_layout((10, 8, 1), 0, None), None);
- // Unknown kind.
- assert_eq!(validate_layout((3, 16, 1), 0, None), None);
- // Unaligned stride, source offset, or count offset.
- assert_eq!(validate_layout((0, 18, 1), 0, None), None);
- assert_eq!(validate_layout((0, 16, 1), 2, None), None);
- assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
- // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
- assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
- }
- /// WARP D3D12 execution test proving:
- /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
- /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
- /// this or subsequent `ExecuteIndirect` calls in the same list,
- /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
- /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
- /// records into `dst_args` at offset `0`.
- #[test]
- fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
- let Some(mut warp) = WarpHarness::new() else {
- return;
- };
- const KIND_DISPATCH: u32 = 2;
- const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
- const MAX: u32 = 4096;
- const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
- const COUNT_OFFSET_1: usize = 128;
- const COUNT_OFFSET_2: usize = 192;
- let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
- let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
- let (count_buf, count_ptr, _) = warp.shared_buffer(512);
- let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
- let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
- let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
- let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
- let sig = warp.signature(KIND_DISPATCH, STRIDE);
- // Fill the entire source buffer with non-zero sentinel bytes, then
- // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
- // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
- let mut initial_src = vec![0xA5u8; src_bytes];
- let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
- let base = ARGS_OFFSET + idx * (STRIDE as usize);
- for (w, val) in words.into_iter().enumerate() {
- buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
- }
- };
- write_record(
- &mut initial_src,
- 0,
- [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
- );
- write_record(
- &mut initial_src,
- 1,
- [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
- );
- // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
- write_record(
- &mut initial_src,
- 2,
- [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
- );
- for slot in 3..MAX as usize {
- // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
- // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
- write_record(
- &mut initial_src,
- slot,
- [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
- );
- }
- // Second indirect call's source records (at offset 0 of a second buffer,
- // or later in `count_buf`): put 2 active records + garbage tail in a
- // second range to run back-to-back in the SAME command list.
- let mut initial_count = vec![0x5Au8; 512];
- initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
- initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
- // SAFETY: buffers are mapped with exact capacities above.
- unsafe {
- std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
- std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
- (budget_ptr as *mut u32).write_volatile(0);
- (hits_ptr as *mut u32).write_volatile(0);
- std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
- }
- // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
- // 5 records of `dst_buf` out for inspection, then record Call #2
- // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
- assert!(record_clamp_as(
- &warp.clamp,
- &warp.list,
- (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
- budget_gpu,
- (&src_buf, ARGS_OFFSET as u64),
- Some((&count_buf, COUNT_OFFSET_1 as u64)),
- (KIND_DISPATCH, STRIDE, MAX),
- false,
- ));
- // SAFETY: open command list, valid worker PSO/root and buffers.
- unsafe {
- warp.list.SetComputeRootSignature(&warp.worker.root);
- warp.list.SetPipelineState(&warp.worker.pso);
- warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
- warp.list.ExecuteIndirect(
- &sig,
- MAX,
- &dst_buf,
- 0,
- Some(&count_buf),
- COUNT_OFFSET_1 as u64,
- );
- }
- // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave
- // `dst_buf` readable as arguments again, as the clamp left it).
- // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`.
- unsafe {
- warp.list.ResourceBarrier(&[transition(
- &dst_buf,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- D3D12_RESOURCE_STATE_COPY_SOURCE,
- )]);
- warp.list
- .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
- warp.list.ResourceBarrier(&[transition(
- &dst_buf,
- D3D12_RESOURCE_STATE_COPY_SOURCE,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- )]);
- }
- // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
- // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
- // The scratch buffer goes straight from arguments back to unordered
- // access.
- assert!(record_clamp_as(
- &warp.clamp,
- &warp.list,
- (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
- budget_gpu,
- (&src_buf, ARGS_OFFSET as u64),
- Some((&count_buf, COUNT_OFFSET_2 as u64)),
- (KIND_DISPATCH, STRIDE, MAX),
- false,
- ));
- // SAFETY: open command list, valid worker PSO/root and buffers.
- unsafe {
- warp.list.SetComputeRootSignature(&warp.worker.root);
- warp.list.SetPipelineState(&warp.worker.pso);
- warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
- warp.list.ExecuteIndirect(
- &sig,
- MAX,
- &dst_buf,
- 0,
- Some(&count_buf),
- COUNT_OFFSET_2 as u64,
- );
- }
- warp.submit_and_wait();
- // SAFETY: GPU execution finished; read mapped host results.
- let (hits, spent, after_src, after_count, clamped_words) = unsafe {
- let hits = (hits_ptr as *const u32).read_volatile();
- let spent = (budget_ptr as *const u32).read_volatile();
- let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
- let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
- let words = std::slice::from_raw_parts(
- readback_ptr.cast::<u32>().cast_const(),
- (STRIDE as usize / 4) * 5,
- )
- .to_vec();
- (hits, spent, after_src, after_count, words)
- };
- // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
- // Call #2: (3*2*1) + (5*1*1) = 11 groups.
- let expected_groups = (6 + 5 + 65_535) + (6 + 5);
- assert_eq!(
- hits, expected_groups,
- "valid indirect dispatches must all execute"
- );
- assert_eq!(
- spent,
- expected_groups * 64,
- "budget must reflect only active records below countBuffer"
- );
- assert_eq!(
- after_src, initial_src,
- "src_args must never be mutated in-place"
- );
- assert_eq!(
- after_count, initial_count,
- "count_buf must never be mutated"
- );
- // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
- assert_eq!(
- &clamped_words[0..6],
- &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
- );
- assert_eq!(
- &clamped_words[6..12],
- &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
- );
- assert_eq!(
- &clamped_words[12..18],
- &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
- );
- // Inactive slot 3 was never copied from `src_args`.
- assert_ne!(clamped_words[21], 0xDEAD_BEEF);
- }
- /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
- /// wraparound across >64 huge indexed-draw records (`count = None`), while
- /// preserving `StartIndexLocation`, `BaseVertexLocation`,
- /// `StartInstanceLocation`, and custom stride padding, and leaving
- /// `src_args` untouched.
- /// A window of mesh records clamped ahead: the filled ones come out as
- /// they are and are charged, the slots of all ones come out empty and
- /// charge nothing; clamped as single records the same slots are clamped
- /// to the most and spend the budget.
- #[test]
- fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
- let Some(mut warp) = WarpHarness::new() else {
- return;
- };
- const KIND_MESH: u32 = 10;
- const STRIDE: u32 = 32;
- const RECORDS: u32 = 16;
- let filled = [5u32, 0, 519];
- let total = (STRIDE * RECORDS) as usize;
- let mut src = vec![0xffu8; total];
- for (i, groups) in filled.into_iter().enumerate() {
- let words = [groups, 1, 1, 0xAB00 + i as u32];
- for (w, word) in words.into_iter().enumerate() {
- let at = i * STRIDE as usize + w * 4;
- src[at..at + 4].copy_from_slice(&word.to_le_bytes());
- }
- }
- for ahead in [true, false] {
- let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
- let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
- let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
- let dst_buf = warp.default_uav(total as u64);
- // SAFETY: mapped buffers of these sizes.
- unsafe {
- std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
- std::ptr::write_bytes(budget_ptr, 0, 256);
- std::ptr::write_bytes(readback_ptr, 0, total);
- }
- assert!(record_clamp_as(
- &warp.clamp,
- &warp.list,
- (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
- budget_gpu,
- (&src_buf, 0),
- None,
- (KIND_MESH, STRIDE, RECORDS),
- ahead,
- ));
- // SAFETY: an open list; the scratch buffer, which the clamp left
- // readable as arguments, is copied for the check.
- unsafe {
- warp.list.ResourceBarrier(&[transition(
- &dst_buf,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- D3D12_RESOURCE_STATE_COPY_SOURCE,
- )]);
- warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
- }
- warp.submit_and_wait();
- // SAFETY: the work is done; mapped buffers.
- let (spent, largest, out) = unsafe {
- (
- (budget_ptr as *const u32).read_volatile(),
- (budget_ptr as *const u32).add(1).read_volatile(),
- std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
- )
- };
- for (i, groups) in filled.into_iter().enumerate() {
- let rec = &out[i * 8..i * 8 + 4];
- assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
- }
- let charged_filled = (5 + 519) * 128;
- if ahead {
- for i in filled.len()..RECORDS as usize {
- assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
- assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
- }
- assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
- assert_eq!(largest, 519, "and are not counted as asked for");
- } else {
- // Thirteen slots at 65,535 groups: sixteen would be all of it.
- assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
- assert_eq!(largest, u32::MAX);
- }
- }
- }
- #[test]
- fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
- let Some(mut warp) = WarpHarness::new() else {
- return;
- };
- const KIND_INDEXED: u32 = 1;
- const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
- const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
- const BUDGET_CAP: u32 = 1 << 27;
- let total_bytes = (STRIDE * RECORDS) as usize;
- let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
- let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
- let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
- let dst_buf = warp.default_uav(total_bytes as u64);
- let mut initial_src = vec![0u8; total_bytes];
- for i in 0..RECORDS as usize {
- let words: [u32; 6] = [
- u32::MAX, // IndexCount -> clamps to 1 << 24
- u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
- 1000 + i as u32, // StartIndexLocation
- (-200i32 + i as i32) as u32, // BaseVertexLocation
- 5000 + i as u32, // StartInstanceLocation
- 0xCAFE_0000 | (i as u32), // Extra stride word
- ];
- let base = i * (STRIDE as usize);
- for (w, val) in words.into_iter().enumerate() {
- initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
- }
- }
- // SAFETY: mapped buffers have sufficient capacity.
- unsafe {
- std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
- (budget_ptr as *mut u32).write_volatile(0);
- std::ptr::write_bytes(readback_ptr, 0, total_bytes);
- }
- assert!(record_clamp_as(
- &warp.clamp,
- &warp.list,
- (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
- budget_gpu,
- (&src_buf, 0),
- None,
- (KIND_INDEXED, STRIDE, RECORDS),
- false,
- ));
- // SAFETY: open command list; copy clamped scratch buffer (left
- // readable as arguments) for verification.
- unsafe {
- warp.list.ResourceBarrier(&[transition(
- &dst_buf,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- D3D12_RESOURCE_STATE_COPY_SOURCE,
- )]);
- warp.list
- .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
- }
- warp.submit_and_wait();
- // SAFETY: GPU work completed.
- let (spent, after_src, out_words) = unsafe {
- let spent = (budget_ptr as *const u32).read_volatile();
- let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
- let out_words = std::slice::from_raw_parts(
- readback_ptr.cast::<u32>().cast_const(),
- total_bytes / 4,
- )
- .to_vec();
- (spent, after_src, out_words)
- };
- assert_eq!(
- spent, BUDGET_CAP,
- "budget must saturate at BUDGET without wrapping"
- );
- assert_eq!(after_src, initial_src, "src_args must remain untouched");
- let mut kept = 0usize;
- let mut zeroed = 0usize;
- for i in 0..RECORDS as usize {
- let rec = &out_words[i * 6..(i + 1) * 6];
- if rec[0] == (1 << 24) && rec[1] == 4 {
- kept += 1;
- } else {
- assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
- zeroed += 1;
- }
- assert_eq!(rec[2], 1000 + i as u32);
- assert_eq!(rec[3], (-200i32 + i as i32) as u32);
- assert_eq!(rec[4], 5000 + i as u32);
- assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
- }
- assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
- }
- /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's
- /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on
- /// the host device.
- #[test]
- fn host_list_reuses_and_grows_scratch_across_submissions() {
- let Some(host) = super::host() else {
- return;
- };
- // What earlier tests left in the debug layer's queue, if it is on.
- let _ = host.log_messages();
- let Ok(list) = host.new_list() else {
- return;
- };
- let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
- return;
- };
- let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
- return;
- };
- // SAFETY: mapped host buffers.
- unsafe {
- std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
- (count_ptr as *mut u32).write_volatile(2);
- }
- let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
- // First two calls fit inside the initial 64 KiB scratch buffer and
- // must reuse the exact same `ID3D12Resource`, which stays readable
- // as arguments between them.
- let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
- assert_eq!(
- list.indirect_state(&b1),
- args,
- "a clamp leaves the scratch readable as arguments"
- );
- let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
- assert_eq!(
- b1.as_raw(),
- b2.as_raw(),
- "scratch buffer within capacity must be reused"
- );
- assert_eq!(list.indirect_state(&b2), args);
- // A call needing >64 KiB grows the scratch buffer mid-list while keeping
- // `b1` alive until reset. The new buffer starts out common.
- let grown = list.indirect_scratch(5000 * 20).unwrap();
- assert_eq!(
- list.indirect_state(&grown),
- D3D12_RESOURCE_STATE_COMMON,
- "a new scratch buffer is common"
- );
- let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
- assert_eq!(b3.as_raw(), grown.as_raw());
- assert_ne!(
- b3.as_raw(),
- b1.as_raw(),
- "larger request must grow scratch buffer"
- );
- assert_eq!(list.indirect_state(&b3), args);
- assert_eq!(
- list.indirect_state(&b1),
- D3D12_RESOURCE_STATE_COMMON,
- "the replaced buffer went back to common"
- );
- list.close();
- host.execute(&[&list]);
- list.reset();
- // After reset, requests up to the grown high-water mark reuse `b3` with
- // zero new allocations; the buffer decayed to common when the
- // submission ran.
- assert_eq!(
- list.indirect_state(&b3),
- D3D12_RESOURCE_STATE_COMMON,
- "a reset list starts with a common scratch buffer"
- );
- let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
- assert_eq!(
- b4.as_raw(),
- b3.as_raw(),
- "grown scratch buffer must persist across reset"
- );
- assert_eq!(list.indirect_state(&b4), args);
- list.close();
- host.execute(&[&list]);
- list.reset();
- // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics):
- // every barrier named the state the buffer was really in.
- assert_eq!(host.log_messages(), None, "the debug layer found an error");
- }
- /// Records the dispatch records `groups` (three words each, `step`
- /// bytes apart, the rest of each record ones) into a fresh mapped
- /// buffer of `warp`'s device.
- fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource {
- let total = groups.len() * step as usize;
- let (buffer, ptr, _) = warp.shared_buffer(total as u64);
- let mut bytes = vec![0xffu8; total];
- for (i, &g) in groups.iter().enumerate() {
- for (w, word) in [g, 1, 1].into_iter().enumerate() {
- let at = i * step as usize + w * 4;
- bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
- }
- }
- // SAFETY: the mapping holds `total` bytes.
- unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
- buffer
- }
- /// Two windows in one list, as `crate::draw` records them: each clamps
- /// its records ahead, then one execution per record reads the scratch
- /// buffer with no barrier between them; the second clamp moves the
- /// scratch buffer straight from arguments back to unordered access.
- /// Every record runs once, with the group count it asked for.
- #[test]
- fn warp_window_executions_read_their_records_with_no_barrier_between() {
- let Some(mut warp) = WarpHarness::new() else {
- return;
- };
- const KIND_DISPATCH: u32 = 2;
- // The title names 12 bytes and keeps its records 32 apart.
- const STRIDE: u32 = 12;
- const STEP: u32 = 32;
- let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
- let sources: Vec<ID3D12Resource> =
- windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect();
- let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
- let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
- let dst_buf = warp.default_uav(u64::from(STEP) * 4);
- let sig = warp.signature(KIND_DISPATCH, STRIDE);
- // SAFETY: mapped buffers of these sizes.
- unsafe {
- std::ptr::write_bytes(budget_ptr, 0, 256);
- std::ptr::write_bytes(hits_ptr, 0, 256);
- }
- let mut state = D3D12_RESOURCE_STATE_COMMON;
- for (groups, src) in windows.iter().zip(&sources) {
- assert!(record_clamp_as(
- &warp.clamp,
- &warp.list,
- (&dst_buf, state),
- budget_gpu,
- (src, 0),
- None,
- (KIND_DISPATCH, STEP, groups.len() as u32),
- true,
- ));
- state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
- // SAFETY: an open list; the worker's root signature and
- // pipeline; the scratch buffer is readable as arguments.
- unsafe {
- warp.list.SetComputeRootSignature(&warp.worker.root);
- warp.list.SetPipelineState(&warp.worker.pso);
- warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
- for i in 0..groups.len() as u64 {
- warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0);
- }
- }
- }
- warp.submit_and_wait();
- // SAFETY: the work is done; mapped buffers.
- let (hits, spent) = unsafe {
- (
- (hits_ptr as *const u32).read_volatile(),
- (budget_ptr as *const u32).read_volatile(),
- )
- };
- let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
- assert_eq!(hits, expected, "every record of both windows runs once");
- assert_eq!(spent, expected * 64, "and is charged what it asked for");
- }
- /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between`
- /// through a host list (`bound_ahead`, the list's tracked scratch state,
- /// `Host::execute`), twice: on the first recording the scratch buffer
- /// starts common, on the second (after the reset) it starts common
- /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a
- /// diagnostics build) no barrier names a state the buffer is not in.
- #[test]
- fn host_list_window_executions_need_no_barrier_of_their_own() {
- let Some(host) = super::host() else {
- return;
- };
- // What earlier tests left in the debug layer's queue, if it is on.
- let _ = host.log_messages();
- let Ok(list) = host.new_list() else {
- return;
- };
- let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
- const KIND_DISPATCH: u32 = 2;
- const STRIDE: u32 = 12;
- const STEP: u32 = 32;
- let signature = {
- let arg = D3D12_INDIRECT_ARGUMENT_DESC {
- Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
- ..Default::default()
- };
- let desc = D3D12_COMMAND_SIGNATURE_DESC {
- ByteStride: STRIDE,
- NumArgumentDescs: 1,
- pArgumentDescs: &arg,
- NodeMask: 0,
- };
- let mut sig: Option<ID3D12CommandSignature> = None;
- // SAFETY: a valid single-argument command signature description.
- unsafe {
- host.device
- .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
- .unwrap();
- }
- sig.unwrap()
- };
- let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
- let mut sources = Vec::new();
- for groups in windows {
- let total = groups.len() * STEP as usize;
- let Some((buffer, ptr)) = host.shared_buffer(total as u64) else {
- return;
- };
- let mut bytes = vec![0xffu8; total];
- for (i, &g) in groups.iter().enumerate() {
- for (w, word) in [g, 1, 1].into_iter().enumerate() {
- let at = i * STEP as usize + w * 4;
- bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
- }
- }
- // SAFETY: the mapping holds `total` bytes.
- unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
- sources.push(buffer);
- }
- let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
- return;
- };
- let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
- // SAFETY: a live buffer.
- let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
- for _ in 0..2 {
- // SAFETY: the mapping holds 256 bytes; nothing runs.
- unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
- for (groups, src) in windows.iter().zip(&sources) {
- let spec = (KIND_DISPATCH, STEP, groups.len() as u32);
- let scratch = bound_ahead(&list, (src, 0), spec).unwrap();
- assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
- // SAFETY: an open list; the worker's root signature and
- // pipeline; buffers the test holds until the list has run.
- unsafe {
- list.list.SetComputeRootSignature(&worker.root);
- list.list.SetPipelineState(&worker.pso);
- list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
- for i in 0..groups.len() as u64 {
- let at = i * u64::from(STEP);
- list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0);
- }
- }
- }
- list.close();
- host.execute(&[&list]);
- list.reset();
- // SAFETY: the list has run; a mapped buffer.
- let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
- assert_eq!(hits, expected, "every record of both windows runs once");
- assert_eq!(host.log_messages(), None, "the debug layer found an error");
- }
- }
- }
- /// A frame's worth of one-record indirect draws, recorded with the scratch
- /// buffer's old barriers (back to the common state after every execution)
- /// and with the new ones (readable until the next clamp), clamped one at a
- /// time and in windows, on the host GPU. Ignored by default; run it with
- /// `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`.
- /// It needs no title files: the draws are tiny triangles of ours.
- #[cfg(test)]
- mod bench {
- use super::*;
- use windows::Win32::Foundation::RECT;
- use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
- use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4};
- use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
- use windows::core::{Interface, PCSTR};
- /// Draws a frame (the title's gameplay frames hold about 3,200 indirect
- /// executions, #107), records a window holds, and how far apart the
- /// records are (the title keeps them 32 bytes apart).
- const DRAWS: u32 = 3200;
- const WINDOW: u32 = 32;
- const STEP: u32 = 32;
- const RUNS: usize = 9;
- const SHADERS: &str = r#"
- #define RS "RootFlags(0)"
- [RootSignature(RS)]
- float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position {
- float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5;
- return float4(p, 0.5, 1);
- }
- float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); }
- "#;
- fn compile(entry: &str, target: &str) -> Vec<u8> {
- let entry = std::ffi::CString::new(entry).unwrap();
- let target = std::ffi::CString::new(target).unwrap();
- let mut code: Option<ID3DBlob> = None;
- // SAFETY: the source and names outlive the call.
- unsafe {
- D3DCompile(
- SHADERS.as_ptr().cast(),
- SHADERS.len(),
- s!("bench"),
- None,
- None,
- PCSTR(entry.as_ptr().cast()),
- PCSTR(target.as_ptr().cast()),
- 0,
- 0,
- &mut code,
- None,
- )
- .unwrap();
- let code = code.unwrap();
- std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
- .to_vec()
- }
- }
- #[derive(Clone, Copy, PartialEq, Eq, Debug)]
- enum Barriers {
- /// Back to the common state after every execution (as before).
- Old,
- /// Readable as arguments until the next clamp, common at the end.
- New,
- }
- #[test]
- #[ignore = "benchmark; see the module notes"]
- fn bench_indirect_draw_barriers() {
- let Some(host) = super::host() else {
- eprintln!("no host GPU");
- return;
- };
- let device = &host.device;
- let clamp = make_for(device).expect("the clamp");
- // SAFETY: plain D3D12 object creation with valid descriptions; the
- // objects outlive every list recorded and run below.
- unsafe {
- let adapter = {
- let luid = device.GetAdapterLuid();
- CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
- .and_then(|f| f.EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid))
- .and_then(|a| a.GetDesc1())
- .map(|d| String::from_utf16_lossy(&d.Description).trim_end_matches('\0').to_owned())
- .unwrap_or_else(|_| "an unnamed adapter".to_owned())
- };
- let queue: ID3D12CommandQueue = device
- .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
- Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
- ..Default::default()
- })
- .unwrap();
- let allocator: ID3D12CommandAllocator =
- device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
- let list: ID3D12GraphicsCommandList = device
- .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
- .unwrap();
- list.Close().unwrap();
- let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
- let event = CreateEventW(None, false, false, None).unwrap();
- let frequency = queue.GetTimestampFrequency().unwrap() as f64;
- // The pipeline: tiny triangles into a small target.
- let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1"));
- let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
- let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
- pRootSignature: std::mem::transmute_copy(&root),
- VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() },
- PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() },
- SampleMask: u32::MAX,
- RasterizerState: D3D12_RASTERIZER_DESC {
- FillMode: D3D12_FILL_MODE_SOLID,
- CullMode: D3D12_CULL_MODE_NONE,
- DepthClipEnable: true.into(),
- ..Default::default()
- },
- PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
- NumRenderTargets: 1,
- SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
- ..Default::default()
- };
- desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
- desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
- let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
- let target_desc = D3D12_RESOURCE_DESC {
- Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
- Width: 256,
- Height: 256,
- DepthOrArraySize: 1,
- MipLevels: 1,
- Format: DXGI_FORMAT_R8G8B8A8_UNORM,
- SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
- Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
- ..Default::default()
- };
- let mut target: Option<ID3D12Resource> = None;
- device
- .CreateCommittedResource(
- &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
- D3D12_HEAP_FLAG_NONE,
- &target_desc,
- D3D12_RESOURCE_STATE_RENDER_TARGET,
- None,
- &mut target,
- )
- .unwrap();
- let target = target.unwrap();
- let rtvs: ID3D12DescriptorHeap = device
- .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
- Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
- NumDescriptors: 1,
- ..Default::default()
- })
- .unwrap();
- let rtv = rtvs.GetCPUDescriptorHandleForHeapStart();
- device.CreateRenderTargetView(&target, None, rtv);
- // The title's records: three vertices, one instance, 32 bytes apart.
- let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap();
- for i in 0..DRAWS as usize {
- let words = [3u32, 1, 0, 0];
- std::ptr::copy_nonoverlapping(words.as_ptr().cast::<u8>(), src_ptr.add(i * STEP as usize), 16);
- }
- let (budget, budget_ptr) = host.shared_buffer(256).unwrap();
- let budget_gpu = budget.GetGPUVirtualAddress();
- let scratch = host.uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)).unwrap();
- let signature = {
- let arg = D3D12_INDIRECT_ARGUMENT_DESC {
- Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW,
- ..Default::default()
- };
- let desc = D3D12_COMMAND_SIGNATURE_DESC {
- ByteStride: 16,
- NumArgumentDescs: 1,
- pArgumentDescs: &arg,
- NodeMask: 0,
- };
- let mut sig: Option<ID3D12CommandSignature> = None;
- device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap();
- sig.unwrap()
- };
- let stamps: ID3D12QueryHeap = {
- let mut heap: Option<ID3D12QueryHeap> = None;
- device
- .CreateQueryHeap(
- &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2, NodeMask: 0 },
- &mut heap,
- )
- .unwrap();
- heap.unwrap()
- };
- let mut back: Option<ID3D12Resource> = None;
- device
- .CreateCommittedResource(
- &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
- D3D12_HEAP_FLAG_NONE,
- &D3D12_RESOURCE_DESC {
- Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
- Width: 16,
- Height: 1,
- DepthOrArraySize: 1,
- MipLevels: 1,
- SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
- Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
- ..Default::default()
- },
- D3D12_RESOURCE_STATE_COPY_DEST,
- None,
- &mut back,
- )
- .unwrap();
- let back = back.unwrap();
- let mut submitted = 0u64;
- // One frame's lists: GPU ms (timestamps around the list), CPU ms
- // recording it, ms from submission to the end of its run.
- let mut frame = |barriers: Barriers, window: u32| -> [f64; 3] {
- allocator.Reset().unwrap();
- list.Reset(&allocator, None).unwrap();
- let recording = std::time::Instant::now();
- list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
- list.OMSetRenderTargets(1, Some(&rtv), false, None);
- list.RSSetViewports(&[D3D12_VIEWPORT { Width: 256.0, Height: 256.0, MaxDepth: 1.0, ..Default::default() }]);
- list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: 256, bottom: 256 }]);
- list.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
- list.SetGraphicsRootSignature(&root);
- let mut state = D3D12_RESOURCE_STATE_COMMON;
- for first in (0..DRAWS).step_by(window as usize) {
- let records = window.min(DRAWS - first);
- assert!(record_clamp_as(
- &clamp,
- &list,
- (&scratch, state),
- budget_gpu,
- (&src, u64::from(first * STEP)),
- None,
- (0, STEP, records),
- window > 1,
- ));
- state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
- list.SetPipelineState(&pso);
- for k in 0..records {
- list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0);
- if barriers == Barriers::Old {
- list.ResourceBarrier(&[transition(
- &scratch,
- D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
- D3D12_RESOURCE_STATE_COMMON,
- )]);
- state = D3D12_RESOURCE_STATE_COMMON;
- }
- }
- }
- if state != D3D12_RESOURCE_STATE_COMMON {
- list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]);
- }
- list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
- list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0);
- list.Close().unwrap();
- let recorded = recording.elapsed().as_secs_f64() * 1e3;
- let running = std::time::Instant::now();
- queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
- submitted += 1;
- queue.Signal(&fence, submitted).unwrap();
- fence.SetEventOnCompletion(submitted, event).unwrap();
- WaitForSingleObject(event, INFINITE);
- let ran = running.elapsed().as_secs_f64() * 1e3;
- let mut data = std::ptr::null_mut();
- back.Map(0, None, Some(&mut data)).unwrap();
- let t = std::slice::from_raw_parts(data.cast::<u64>(), 2);
- let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3;
- back.Unmap(0, None);
- (budget_ptr as *mut u32).write_volatile(0);
- [gpu, recorded, ran]
- };
- let cases = [
- ("clamped one at a time", Barriers::Old, 1),
- ("clamped one at a time", Barriers::New, 1),
- ("windows of 32", Barriers::Old, WINDOW),
- ("windows of 32", Barriers::New, WINDOW),
- ];
- // Warm up, then the cases in turn, so drift falls on all alike.
- for &(_, barriers, window) in &cases {
- frame(barriers, window);
- }
- let mut times: Vec<Vec<[f64; 3]>> = vec![Vec::new(); cases.len()];
- for _ in 0..RUNS {
- for (i, &(_, barriers, window)) in cases.iter().enumerate() {
- times[i].push(frame(barriers, window));
- }
- }
- let median = |v: &[[f64; 3]], k: usize| {
- let mut x: Vec<f64> = v.iter().map(|t| t[k]).collect();
- x.sort_by(f64::total_cmp);
- x[x.len() / 2]
- };
- eprintln!(
- "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \
- medians of {RUNS} frames"
- );
- for (i, (name, barriers, _)) in cases.iter().enumerate() {
- let gpu = median(×[i], 0);
- eprintln!(
- " {name:<22} {:<3} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \
- submit to done {:7.2} ms",
- format!("{barriers:?}").to_lowercase(),
- gpu * 1e3 / f64::from(DRAWS),
- median(×[i], 1),
- median(×[i], 2),
- );
- }
- for pair in [(0, 1), (2, 3)] {
- let (old, new) = (median(×[pair.0], 0), median(×[pair.1], 0));
- eprintln!(" {}: GPU time {:+.1} %", cases[pair.0].0, (new / old - 1.0) * 100.0);
- }
- }
- }
- }
|