| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775 |
- //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
- //! window to present on.
- //!
- //! shortcut: every submission is waited for, so CPU and GPU never overlap;
- //! overlap them with per-submission fences once more than clears run.
- use std::sync::atomic::{AtomicU32, Ordering};
- use std::sync::{Mutex, OnceLock};
- use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
- use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
- use windows::Win32::Graphics::Direct3D12::*;
- use windows::Win32::Graphics::Dxgi::Common::*;
- use windows::Win32::Graphics::Dxgi::*;
- use windows::Win32::System::LibraryLoader::GetModuleHandleW;
- use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
- use windows::Win32::UI::WindowsAndMessaging::*;
- use windows::core::{Interface, PCWSTR, w};
- /// Resource states without the console's own bits (compression hints from
- /// bit 25 up), which the host rejects.
- pub(crate) fn pc_state(state: u32) -> u32 {
- state & 0x01ff_ffff
- }
- /// A console state as a host texture state: PC bits only, and none of the
- /// buffer-only ones the console allows on textures (vertex, constant and
- /// index buffer, stream out, indirect arguments, as in "generic read").
- pub(crate) fn texture_state(state: u32) -> u32 {
- const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
- pc_state(state) & !BUFFER_ONLY
- }
- /// Render target views live only until their command is recorded, so a
- /// ring of host descriptors is enough.
- const RTV_RING: u32 = 1024;
- pub(crate) struct Host {
- pub(crate) device: ID3D12Device,
- queue: ID3D12CommandQueue,
- fence: ID3D12Fence,
- /// The last value signalled on `fence`, behind the submission lock.
- submitted: Mutex<u64>,
- event: HANDLE,
- rtvs: ID3D12DescriptorHeap,
- rtv_size: u32,
- /// A ring of depth views, used as `rtvs`.
- dsvs: ID3D12DescriptorHeap,
- dsv_size: u32,
- next_dsv: AtomicU32,
- /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
- /// layer's messages.
- messages: Option<ID3D12InfoQueue>,
- next_rtv: AtomicU32,
- presenter: Mutex<Option<Presenter>>,
- }
- // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
- // free-threaded; the event handle is only waited on under `submitted`.
- unsafe impl Send for Host {}
- // SAFETY: as above.
- unsafe impl Sync for Host {}
- /// Time spent in submissions since the last frame-rate line, in
- /// microseconds: preparing them on the CPU (title memory copies, texture
- /// detiling), then waiting for the GPU.
- static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
- [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
- /// After submissions: shader-written ranges compared and copied back into
- /// title memory (microseconds, bytes that differed), since the last
- /// frame-rate line.
- static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
- [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
- /// Of the preparing: title memory copies (microseconds, bytes) and texture
- /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
- pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
- std::sync::atomic::AtomicU64::new(0),
- std::sync::atomic::AtomicU64::new(0),
- std::sync::atomic::AtomicU64::new(0),
- std::sync::atomic::AtomicU64::new(0),
- ];
- /// What the runtime does when the host GPU fails for good: report it like a
- /// crash and end the run. The console has no such state, and carrying on
- /// draws nothing at seconds per frame.
- static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
- /// Sets what a host GPU failure does (the runtime's crash report).
- pub fn on_failure(report: fn(&str) -> !) {
- let _ = ON_FAILURE.set(report);
- }
- /// Ends the run on a host GPU failure: what failed, the removal reason and
- /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
- /// diagnostics build names the command).
- pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
- let mut text = what.to_string();
- if let Some(host) = host() {
- // SAFETY: a plain query.
- if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
- text.push_str(&format!("; device removed: {e}"));
- }
- match host.log_messages() {
- Some(first) => text.push_str(&format!("; debug layer: {first}")),
- None if host.messages.is_none() => text.push_str(
- "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
- ),
- None => {}
- }
- }
- tracing::error!("{text}");
- match ON_FAILURE.get() {
- Some(report) => report(&text),
- None => std::process::abort(),
- }
- }
- /// The host GPU, created on first use; `None` without one (a run then
- /// behaves as before: nothing executes).
- pub(crate) fn host() -> Option<&'static Host> {
- static HOST: OnceLock<Option<Host>> = OnceLock::new();
- HOST.get_or_init(|| match create() {
- Ok(host) => Some(host),
- Err(e) => {
- tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
- None
- }
- })
- .as_ref()
- }
- fn create() -> windows::core::Result<Host> {
- // SAFETY: plain D3D12 object creation with valid descriptions.
- unsafe {
- // The debug layer only in builds with diagnostics.
- let debug =
- cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
- if debug {
- let mut layer: Option<ID3D12Debug> = None;
- match D3D12GetDebugInterface(&mut layer) {
- Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
- Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
- }
- // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
- // descriptor heap indices and the like become messages naming
- // the command instead of page faults. Without state tracking
- // (directly indexed textures are not transitioned).
- if std::env::var_os("VICTORY_D3D12_GBV").is_some()
- && let Some(l) = &layer
- {
- if let Ok(d1) = l.cast::<ID3D12Debug1>() {
- d1.SetEnableGPUBasedValidation(true);
- }
- if let Ok(d2) = l.cast::<ID3D12Debug2>() {
- d2.SetGPUBasedValidationFlags(
- D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
- );
- }
- tracing::info!("GPU-based validation on");
- }
- }
- // Diagnostics: device-removed data (the command that faulted, the
- // faulting address), read when the device is removed.
- if dred_on() {
- let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
- if D3D12GetDebugInterface(&mut dred).is_ok()
- && let Some(dred) = dred
- {
- dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
- dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
- }
- }
- let mut device: Option<ID3D12Device> = None;
- // Diagnostics: the software adapter, on which a shader's wild access
- // is an access violation in this process (a crash report with the
- // address and instruction) instead of a GPU fault and driver reset.
- if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
- let adapter = warp_adapter()?;
- D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
- tracing::info!("host device on the software adapter (WARP)");
- } else {
- D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
- }
- let device = device.ok_or_else(windows::core::Error::empty)?;
- let messages = debug
- .then(|| device.cast::<ID3D12InfoQueue>().ok())
- .flatten();
- let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
- Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
- ..Default::default()
- })?;
- let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
- let event = CreateEventW(None, false, false, None)?;
- let rtvs: ID3D12DescriptorHeap =
- device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
- Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
- NumDescriptors: RTV_RING,
- ..Default::default()
- })?;
- let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
- let dsvs: ID3D12DescriptorHeap =
- device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
- Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
- NumDescriptors: RTV_RING,
- ..Default::default()
- })?;
- let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
- tracing::info!("host D3D12 device ready");
- Ok(Host {
- device,
- queue,
- fence,
- submitted: Mutex::new(0),
- event,
- rtvs,
- rtv_size,
- dsvs,
- dsv_size,
- next_dsv: AtomicU32::new(0),
- messages,
- next_rtv: AtomicU32::new(0),
- presenter: Mutex::new(None),
- })
- }
- }
- /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
- /// Reject it before creating a device in diagnostics' software-only mode.
- fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
- // SAFETY: plain DXGI adapter queries.
- unsafe {
- let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
- let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
- let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
- if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
- tracing::warn!(
- vendor = format_args!("{:#x}", desc.VendorId),
- flags = format_args!("{:#x}", desc.Flags),
- "DXGI did not identify the WARP adapter as software; refusing device"
- );
- return Err(windows::core::Error::from_hresult(
- windows::Win32::Foundation::E_FAIL,
- ));
- }
- Ok(adapter)
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn warp_adapter_accepts_only_software() {
- // This probes DXGI without creating a D3D12 device or running a title.
- // SAFETY: plain DXGI adapter queries.
- let raw = unsafe {
- let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
- else {
- return;
- };
- factory.EnumWarpAdapter::<IDXGIAdapter>()
- };
- let Ok(raw) = raw else { return };
- let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
- eprintln!(
- "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
- desc.VendorId, desc.Flags
- );
- assert_eq!(
- warp_adapter().is_ok(),
- desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
- );
- }
- }
- /// A host command list and its allocator, always used together.
- pub(crate) struct HostList {
- allocator: ID3D12CommandAllocator,
- pub(crate) list: ID3D12GraphicsCommandList,
- /// Work for submission time, in recorded order.
- deferred: Mutex<Deferred>,
- /// Upload memory for data the list's draws make (expanded vertices),
- /// reused after a reset.
- scratch: Mutex<Scratch>,
- /// Host texture states the list assumes, by host copy: at its start and
- /// at its end. Lists are recorded on many threads and run in submission
- /// order, so the transitions from a texture's real state are made at
- /// submission, in `prelude`. Holding the copies keeps every texture the
- /// list names alive until it is reset, even if the title releases the
- /// resource first.
- states: Mutex<States>,
- /// The list that runs those transitions just before this one.
- prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
- /// The pipelines the list binds, for reports of slow submissions.
- pipelines: Mutex<std::collections::BTreeSet<String>>,
- /// The work its indirect executions may still do (`indirect`): a
- /// shader-writable word, zeroed when the list is submitted.
- budget: OnceLock<Option<(ID3D12Resource, usize)>>,
- /// The texts of the markers `note_op` set, in order (for device-removed
- /// data without marker texts), with the host GPU range a copy reads.
- #[cfg(feature = "diagnostics")]
- notes: Mutex<Vec<Note>>,
- }
- /// A marker's text and the host range its command reads (diagnostics).
- #[cfg(feature = "diagnostics")]
- type Note = (String, Option<(u64, u64)>);
- type States = std::collections::HashMap<
- usize,
- (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
- >;
- /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
- /// builds).
- pub(crate) fn dred_on() -> bool {
- static ON: OnceLock<bool> = OnceLock::new();
- *ON.get_or_init(|| {
- cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
- })
- }
- /// Names a host object for the device-removed report, which names the
- /// allocations a page fault hit (only with device-removed data on).
- pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
- if dred_on()
- && let Ok(object) = object.cast::<ID3D12Object>()
- {
- // SAFETY: a plain call on a live object.
- let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
- }
- }
- /// Upload chunks handed out front to back: the chunks, the one in use and
- /// the bytes used in it.
- #[derive(Default)]
- struct Scratch {
- chunks: Vec<(ID3D12Resource, usize, u64)>,
- current: usize,
- used: u64,
- }
- // SAFETY: the chunk pointers are persistent mappings of upload buffers.
- unsafe impl Send for Scratch {}
- const SCRATCH_CHUNK: u64 = 4 << 20;
- /// One piece of submission-time work, in recorded order.
- enum Step {
- /// A copy into title memory (destination, source, bytes): the title's
- /// buffer copies, which later refreshes must see.
- Copy(usize, usize, usize),
- /// A copy of title memory into the list's own upload memory.
- Fill(usize, usize, usize),
- /// Brings a range (address, bytes) of a buffer's host copy up to date:
- /// once per submission, whichever lists ask, until a `Copy` or `Run`
- /// intervenes.
- Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
- /// Work that may write title memory.
- Run(Box<dyn Fn() + Send>),
- /// Work that writes host memory only.
- Host(Box<dyn Fn() + Send>),
- /// Shaders write a range (address, bytes) of a buffer's host copy.
- GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
- }
- /// What a list does on the CPU when it is submitted: copies between host
- /// memory regions (title buffers, upload buffers and buffer copies), and
- /// the upload buffers its GPU commands read, kept until the list is reset.
- #[derive(Default)]
- struct Deferred {
- /// Destination, source, bytes.
- copies: Vec<Step>,
- uploads: Vec<ID3D12Resource>,
- /// Host objects the list's commands name (pipelines, root signatures,
- /// descriptor heaps): the title may release its objects before it
- /// submits the list.
- kept: Vec<windows::core::IUnknown>,
- /// Buffer ranges refreshed since the last title copy (host copy,
- /// address, bytes): refreshing them again would find the same bytes.
- refreshed: std::collections::HashSet<(usize, usize, usize)>,
- /// Textures whose contents the list brings up to date.
- textures: std::collections::HashSet<usize>,
- /// Bottom-of-pipe writes, done once the list has run: address, what,
- /// bytes.
- writes: Vec<(usize, crate::queue::Written, usize)>,
- /// Whether a step zeroes the indirect-work budget.
- budget_zeroed: bool,
- }
- impl Host {
- /// Whether the host runs mesh shaders at shader model 6.6 (translated
- /// mesh shaders need both); logged once.
- pub(crate) fn mesh_shaders(&self) -> bool {
- static MESH: OnceLock<bool> = OnceLock::new();
- *MESH.get_or_init(|| {
- let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
- let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
- HighestShaderModel: D3D_SHADER_MODEL_6_6,
- };
- // SAFETY: each query writes its own structure of the given size.
- let ok = unsafe {
- self.device
- .CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS7,
- (&raw mut options).cast(),
- size_of_val(&options) as u32,
- )
- .is_ok()
- && self
- .device
- .CheckFeatureSupport(
- D3D12_FEATURE_SHADER_MODEL,
- (&raw mut model).cast(),
- size_of_val(&model) as u32,
- )
- .is_ok()
- };
- let mesh = ok
- && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
- && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
- tracing::info!(mesh, "host mesh shader support");
- mesh
- })
- }
- /// A new list, open for recording.
- pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
- // SAFETY: plain object creation.
- unsafe {
- let allocator: ID3D12CommandAllocator = self
- .device
- .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
- let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
- 0,
- D3D12_COMMAND_LIST_TYPE_DIRECT,
- &allocator,
- None,
- )?;
- let prelude_allocator: ID3D12CommandAllocator = self
- .device
- .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
- let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList(
- 0,
- D3D12_COMMAND_LIST_TYPE_DIRECT,
- &prelude_allocator,
- None,
- )?;
- prelude.Close()?;
- Ok(HostList {
- allocator,
- list,
- deferred: Mutex::default(),
- scratch: Mutex::default(),
- states: Mutex::default(),
- prelude: (prelude_allocator, prelude),
- pipelines: Mutex::default(),
- budget: OnceLock::new(),
- #[cfg(feature = "diagnostics")]
- notes: Mutex::default(),
- })
- }
- }
- /// Runs closed lists and waits for them.
- pub(crate) fn execute(&self, runs: &[&HostList]) {
- let started = std::time::Instant::now();
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::Submissions, 1);
- let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
- let mut batch = Batch::default();
- for list in runs {
- list.run_deferred(&mut batch);
- if let Some(prelude) = list.prelude() {
- lists.push(Some(prelude));
- }
- lists.push(list.list.cast().ok());
- }
- batch.flush();
- let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
- *submitted += 1;
- let prepared = std::time::Instant::now();
- // SAFETY: closed lists; the fence and event are ours.
- unsafe {
- self.queue.ExecuteCommandLists(&lists);
- let waited = self
- .queue
- .Signal(&self.fence, *submitted)
- .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
- match waited {
- Ok(()) => {
- WaitForSingleObject(self.event, INFINITE);
- }
- Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
- }
- }
- let gpu = prepared.elapsed();
- SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
- SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
- // The host resets a device whose submission runs for about 2 s.
- if gpu > std::time::Duration::from_millis(250) {
- let pipelines: std::collections::BTreeSet<String> = runs
- .iter()
- .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
- .collect();
- tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
- }
- // SAFETY: a plain query.
- if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
- fail(format_args!(
- "host GPU device removed after a submission of {} lists{}{}",
- runs.len(),
- self.removal_data(runs),
- last_notes(runs)
- ));
- }
- // What shaders wrote goes back before the bottom-of-pipe writes,
- // which tell the title the GPU is done; each range once per
- // submission, however many dispatches declared it (the world's
- // passes declare the same big ranges dozens of times).
- let copying = std::time::Instant::now();
- // One list's lock at a time: a submission may name a list twice.
- let mut back: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
- for list in runs {
- for step in &list.deferred().copies {
- if let Step::GpuWrite(shadow, address, len) = step
- && !back
- .iter()
- .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len))
- {
- back.push((shadow.clone(), *address, *len));
- }
- }
- }
- for (shadow, address, len) in &back {
- let (address, len) = (*address, *len);
- let written = shadow.copy_back(address, len);
- COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
- }
- COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
- for list in runs {
- for &(at, what, bytes) in &list.deferred().writes {
- what.write(at as *mut u8, bytes);
- }
- }
- self.log_messages();
- }
- /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
- /// it lies in (by the names we give them) or the title memory copy just
- /// below it; for each list that did not finish, the command it stopped
- /// at and what the draws and dispatches in flight there run (or, in
- /// lists that never started, the pipelines they bind).
- fn removal_data(&self, runs: &[&HostList]) -> String {
- let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
- return String::new();
- };
- let mut text = String::new();
- let mut fault_va = None;
- // SAFETY: the outputs are the runtime's, valid while the device
- // lives; nodes are walked as linked, histories have their counts.
- unsafe {
- if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
- && fault.PageFaultVA != 0
- {
- let va = fault.PageFaultVA;
- fault_va = Some(va);
- text.push_str(&format!("; page fault at {va:#x}"));
- for (what, head) in [
- ("inside", fault.pHeadExistingAllocationNode),
- ("inside freed", fault.pHeadRecentFreedAllocationNode),
- ] {
- let mut names = Vec::new();
- let mut node = head;
- while let Some(n) = node.as_ref()
- && names.len() < 8
- {
- let name = if n.ObjectNameW.is_null() {
- "unnamed".to_owned()
- } else {
- n.ObjectNameW.to_string().unwrap_or_default()
- };
- names.push(format!("{name} (type {})", n.AllocationType.0));
- node = n.pNext;
- }
- if !names.is_empty() {
- text.push_str(&format!("; {what} {names:?}"));
- }
- }
- text.push_str(&crate::shadow::near(va));
- text.push_str(&crate::descriptor::host::near_heaps(va));
- }
- // The plain output: the extended one (with marker texts) came
- // back without stopped lists on this host.
- let crumbs = match dred.GetAutoBreadcrumbsOutput() {
- Ok(crumbs) => crumbs,
- Err(e) => {
- text.push_str(&format!("; no breadcrumbs ({e})"));
- return text;
- }
- };
- // Every list's progress (done/count), in the runtime's order.
- let mut progress = Vec::new();
- let mut node = crumbs.pHeadAutoBreadcrumbNode;
- while let Some(p) = node.as_ref() {
- let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
- let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
- let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
- progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
- node = p.pNext;
- }
- text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
- let mut plain = crumbs.pHeadAutoBreadcrumbNode;
- while let Some(p) = plain.as_ref() {
- let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
- if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
- let history =
- std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
- text.push_str(&format!(
- "; a list stopped at command {done} of {} (op {})",
- p.BreadcrumbCount, history[done as usize].0
- ));
- let list = p.pCommandList.as_ref().map(|l| l.as_raw());
- let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
- // The k-th marker command is the k-th note.
- #[cfg(feature = "diagnostics")]
- let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
- let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
- history
- .iter()
- .enumerate()
- .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
- .zip(notes.iter())
- .map(|((at, _), (note, range))| {
- let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
- (at as u32, format!("{note}{}", place.unwrap_or_default()))
- })
- .collect()
- });
- #[cfg(not(feature = "diagnostics"))]
- let markers: Vec<(u32, String)> = Vec::new();
- #[cfg(not(feature = "diagnostics"))]
- let _ = fault_va;
- if done > 0 {
- text.push_str(&in_flight(history, &markers, done as usize));
- } else if let Some(r) = run {
- let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
- text.push_str(&format!(", its pipelines {pipelines:?}"));
- }
- }
- plain = p.pNext;
- }
- }
- text
- }
- /// Moves the debug layer's messages into our log; returns the first
- /// error among them.
- pub(crate) fn log_messages(&self) -> Option<String> {
- let Some(queue) = &self.messages else {
- return None;
- };
- let mut first_error = None;
- // SAFETY: each message is read into a buffer of the size the queue
- // reports, then the queue is emptied.
- unsafe {
- for i in 0..queue.GetNumStoredMessages() {
- let mut size = 0;
- if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
- continue;
- }
- let mut buffer = vec![0u64; size.div_ceil(8)];
- let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
- if queue.GetMessage(i, Some(message), &mut size).is_ok() {
- let m = &*message;
- let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
- let text = String::from_utf8_lossy(text);
- let text = text.trim_end_matches('\0');
- tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
- if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
- first_error = Some(text.to_owned());
- }
- }
- }
- queue.ClearStoredMessages();
- }
- first_error
- }
- /// A host render target view of `resource`, valid until it is recorded.
- pub(crate) fn rtv(
- &self,
- resource: &ID3D12Resource,
- desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
- ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
- let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
- // SAFETY: a slot of our heap and a live resource.
- unsafe {
- let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
- handle.ptr += (slot * self.rtv_size) as usize;
- self.device
- .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
- handle
- }
- }
- /// A host depth view of `resource`, valid until it is recorded.
- pub(crate) fn dsv(
- &self,
- resource: &ID3D12Resource,
- desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
- ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
- let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
- // SAFETY: a slot of our heap and a live resource.
- unsafe {
- let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
- handle.ptr += (slot * self.dsv_size) as usize;
- self.device
- .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
- handle
- }
- }
- }
- impl HostList {
- pub(crate) fn close(&self) {
- // SAFETY: our list.
- if let Err(e) = unsafe { self.list.Close() } {
- fail(format_args!(
- "a host command list did not close ({e}): a command recorded into it was invalid"
- ));
- }
- }
- /// Only after the list's last submission finished (every one is waited
- /// for).
- pub(crate) fn reset(&self) {
- *self.deferred() = Deferred::default();
- self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
- self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
- #[cfg(feature = "diagnostics")]
- self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
- {
- let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
- (scratch.current, scratch.used) = (0, 0);
- }
- // SAFETY: the list is not executing.
- let reset = unsafe {
- self.allocator
- .Reset()
- .and_then(|()| self.list.Reset(&self.allocator, None))
- };
- if let Err(e) = reset {
- fail(format_args!("a host command list did not reset ({e})"));
- }
- }
- /// Moves a title texture's host copy to `wanted` (a host state) in this
- /// list: the host texture and the state it leaves, if that is a change.
- /// The list's first use of a texture records nothing: its prelude brings
- /// the texture there at submission.
- pub(crate) fn transition(
- &self,
- resource: crate::object::This,
- wanted: u32,
- ) -> Option<(&'static ID3D12Resource, u32)> {
- let texture = crate::resource::host_resource(resource)?;
- let copy = crate::resource::host_copy(resource)?;
- let wanted = legal_state(texture, wanted);
- let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
- match states.entry(std::sync::Arc::as_ptr(©) as usize) {
- std::collections::hash_map::Entry::Vacant(v) => {
- v.insert((wanted, wanted, copy));
- None
- }
- std::collections::hash_map::Entry::Occupied(mut o) => {
- let before = std::mem::replace(&mut o.get_mut().1, wanted);
- (before != wanted).then_some((texture, before))
- }
- }
- }
- /// At submission: the list that moves each texture this list uses from
- /// its real state to the one the list starts with; the textures' real
- /// states become those the list ends with.
- fn prelude(&self) -> Option<ID3D12CommandList> {
- let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
- let barriers: Vec<D3D12_RESOURCE_BARRIER> = states
- .values()
- .filter_map(|(first, last, copy)| {
- let real = copy.state.swap(*last, Ordering::Relaxed);
- (real != *first).then(|| {
- transition(
- ©.texture,
- D3D12_RESOURCE_STATES(real as i32),
- D3D12_RESOURCE_STATES(*first as i32),
- )
- })
- })
- .collect();
- if barriers.is_empty() {
- return None;
- }
- let (allocator, list) = &self.prelude;
- // SAFETY: the prelude is not executing (every submission is waited
- // for); the textures are live.
- let recorded = unsafe {
- allocator.Reset().and_then(|()| {
- list.Reset(allocator, None)?;
- list.ResourceBarrier(&barriers);
- list.Close()
- })
- };
- if let Err(e) = recorded {
- fail(format_args!("a host state prelude did not record ({e})"));
- }
- list.cast().ok()
- }
- /// Notes what the command about to be recorded does, as a marker
- /// command whose text the list keeps (diagnostics, with device-removed
- /// data on): the report pairs the breadcrumbs' marker commands with the
- /// texts in order and names the commands a fault stopped among.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
- self.note(what, None);
- }
- /// As [`HostList::note_op`], for a copy that reads the host GPU range
- /// `(address, bytes)`: the report places the faulting address in it.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
- self.note(what, Some(range));
- }
- #[cfg(feature = "diagnostics")]
- fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
- if dred_on() {
- let what = what();
- let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
- const UNICODE: u32 = 0;
- // SAFETY: an open list; the marker is copied when recorded.
- unsafe {
- self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
- };
- self.notes
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .push((what, range));
- }
- }
- /// Notes a pipeline the list binds.
- pub(crate) fn used_pipeline(&self, name: &str) {
- let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
- if !pipelines.contains(name) {
- pipelines.insert(name.to_owned());
- }
- }
- fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
- self.deferred.lock().unwrap_or_else(|e| e.into_inner())
- }
- /// Copies `len` bytes from `src` to `dst` when the list is submitted.
- pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
- let mut deferred = self.deferred();
- deferred
- .copies
- .push(Step::Copy(dst as usize, src as usize, len));
- deferred.refreshed.clear();
- }
- /// Copies `len` bytes of title memory at `src` into the list's upload
- /// memory at `dst` when the list is submitted.
- pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
- self.deferred()
- .copies
- .push(Step::Fill(dst as usize, src as usize, len));
- }
- /// Brings `[address, address + len)` of a buffer's host copy up to date
- /// when the list is submitted (once per range until a title copy
- /// intervenes), keeping the copy alive until the list is reset.
- pub(crate) fn defer_refresh(
- &self,
- shadow: &std::sync::Arc<crate::shadow::Shadow>,
- address: usize,
- len: usize,
- ) {
- let mut deferred = self.deferred();
- let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
- if deferred.refreshed.insert(key) {
- deferred
- .copies
- .push(Step::Refresh(shadow.clone(), address, len));
- }
- }
- /// Shaders of the list write `[address, address + len)` of a buffer's
- /// host copy: copied back into title memory once the list has run.
- pub(crate) fn defer_gpu_write(
- &self,
- shadow: &std::sync::Arc<crate::shadow::Shadow>,
- address: usize,
- len: usize,
- ) {
- self.deferred()
- .copies
- .push(Step::GpuWrite(shadow.clone(), address, len));
- }
- /// Stores `what` (`bytes` of it) at `dst` once the list has run.
- pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
- self.deferred().writes.push((dst as usize, what, bytes));
- }
- /// A mapped upload buffer of `size` bytes, alive until the list is
- /// reset.
- ///
- /// shortcut: one buffer per copy; pool them once uploads are frequent.
- pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
- let (buffer, data) = host.upload_buffer(size)?;
- name(&buffer, || format!("list upload {size:#x}"));
- self.deferred().uploads.push(buffer.clone());
- Some((buffer, data))
- }
- /// `len` bytes of upload memory (256-byte aligned) until the list is
- /// reset: the host GPU address and the CPU pointer.
- pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
- let host = host()?;
- let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
- let len = len.max(1).next_multiple_of(256);
- if len > SCRATCH_CHUNK {
- let (buffer, data) = host.upload_buffer(len)?;
- name(&buffer, || format!("list scratch {len:#x}"));
- // SAFETY: a live buffer.
- let gpu = unsafe { buffer.GetGPUVirtualAddress() };
- self.deferred().uploads.push(buffer);
- return Some((gpu, data));
- }
- if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() {
- (s.current, s.used) = (s.current + 1, 0);
- }
- if s.current == s.chunks.len() {
- let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?;
- name(&buffer, || "list scratch".into());
- // SAFETY: a live buffer.
- let gpu = unsafe { buffer.GetGPUVirtualAddress() };
- s.chunks.push((buffer, data as usize, gpu));
- s.used = 0;
- }
- let (_, data, gpu) = s.chunks[s.current];
- let at = s.used;
- s.used += len;
- Some((gpu + at, (data + at as usize) as *mut u8))
- }
- /// The host address of the list's indirect-work budget, zeroed at each
- /// submission of the list from the first use after a reset on.
- pub(crate) fn budget(&self) -> Option<u64> {
- let (buffer, data) = self
- .budget
- .get_or_init(|| {
- let (b, d) = host()?.shared_buffer(256)?;
- Some((b, d as usize))
- })
- .as_ref()?;
- let mut deferred = self.deferred();
- if !deferred.budget_zeroed {
- deferred.budget_zeroed = true;
- let at = *data;
- // SAFETY: the list's own mapped word, written before it runs.
- deferred
- .copies
- .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) })));
- }
- // SAFETY: a live buffer.
- Some(unsafe { buffer.GetGPUVirtualAddress() })
- }
- /// Keeps `object` alive until the list is reset.
- pub(crate) fn keep(&self, object: &impl Interface) {
- if let Ok(object) = object.cast::<windows::core::IUnknown>() {
- self.deferred().kept.push(object);
- }
- }
- /// Whether this is the first time since the reset that the list asks
- /// about `key` (a texture to bring up to date).
- pub(crate) fn first_use(&self, key: usize) -> bool {
- self.deferred().textures.insert(key)
- }
- /// Runs `work` when the list is submitted, in order with its copies.
- /// `work` may write title memory (refreshes after it copy again).
- pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
- self.deferred().copies.push(Step::Run(Box::new(work)));
- self.deferred().refreshed.clear();
- }
- /// As [`HostList::defer`], for work that writes only host memory.
- pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
- self.deferred().copies.push(Step::Host(Box::new(work)));
- }
- /// Runs the list's submission-time steps; refreshes go into `batch`
- /// (the title's big buffers, a 174 MB one among them, are read by most
- /// lists of a submission, through many ranges).
- fn run_deferred(&self, batch: &mut Batch) {
- #[cfg(feature = "diagnostics")]
- use crate::copystat::{C, add};
- for step in &self.deferred().copies {
- let started = std::time::Instant::now();
- let copied = match step {
- &Step::Copy(dst, src, len) => {
- #[cfg(feature = "diagnostics")]
- {
- add(C::Copies, 1);
- add(C::CopyBytes, len as u64);
- }
- batch.flush();
- copy_mapped(dst as *mut u8, src as *const u8, len, true);
- len
- }
- &Step::Fill(dst, src, len) => {
- #[cfg(feature = "diagnostics")]
- {
- add(C::Copies, 1);
- add(C::CopyBytes, len as u64);
- }
- copy_mapped(dst as *mut u8, src as *const u8, len, false);
- len
- }
- Step::Refresh(shadow, address, len) => {
- #[cfg(feature = "diagnostics")]
- {
- add(C::Refreshes, 1);
- add(C::RefreshBytes, *len as u64);
- }
- batch.add(shadow, *address, *len);
- continue;
- }
- Step::Run(work) | Step::Host(work) => {
- if matches!(step, Step::Run(_)) {
- batch.flush();
- }
- work();
- #[cfg(feature = "diagnostics")]
- {
- add(C::Runs, 1);
- add(C::RunUs, started.elapsed().as_micros() as u64);
- }
- continue;
- }
- Step::GpuWrite(shadow, address, len) => {
- // The shaders start from the title's data.
- batch.flush();
- shadow.writing(*address, *len);
- continue;
- }
- };
- PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
- PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
- }
- }
- }
- /// A submission's refreshes not done yet, merged per buffer copy into the
- /// range that covers them: done before a step that writes title memory or
- /// gives a range to shaders, and before the lists run.
- #[derive(Default)]
- struct Batch(Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>);
- impl Batch {
- fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
- let end = address + len;
- match self.0.iter_mut().find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) {
- Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)),
- None => self.0.push((shadow.clone(), address, end)),
- }
- }
- fn flush(&mut self) {
- for (shadow, from, to) in self.0.drain(..) {
- let started = std::time::Instant::now();
- let copied = shadow.update(from, to - from);
- let us = started.elapsed().as_micros() as u64;
- #[cfg(feature = "diagnostics")]
- crate::copystat::range(from, to - from, us, 0);
- PREPARING[0].fetch_add(us, Ordering::Relaxed);
- PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
- }
- }
- }
- /// Copies title memory at submission. The ranges were checked against their
- /// resources when recorded, but the title may since have unmapped pages of
- /// them (tiled memory, page mappings), which read as zeros here; a title
- /// destination (`title_dst`) that is not all mapped is left alone.
- ///
- /// The source is read through the kernel (`ReadProcessMemory`), which
- /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
- /// cost about 2 ms per copy in the title's big pools (it walks the page
- /// tables to the region's end), which made copies run at 100-200 MB/s.
- pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
- #[cfg(feature = "diagnostics")]
- match crate::copystat::mode() {
- 1 => {
- // SAFETY: timing only: the caller vouches for the source.
- unsafe { std::ptr::copy(src, dst, len) };
- return;
- }
- 2 => return,
- _ => {}
- }
- if len == 0 || title_dst && !crate::texture::committed(dst, len) {
- return;
- }
- if title_dst {
- // The kernel writes the destination: it must not be guarded.
- crate::watch::writing(dst as usize, len);
- }
- #[cfg(feature = "diagnostics")]
- let moved = std::time::Instant::now();
- let whole = read(src, dst, len);
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
- if whole {
- return;
- }
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::Fallbacks, 1);
- // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
- // that fails), zeros for what cannot be read.
- for_pieces(src as usize, len, 64 << 10, |at, n| {
- let to = dst.wrapping_add(at - src as usize);
- if !read(at as *const u8, to, n) {
- for_pieces(at, n, 4 << 10, |at, n| {
- let to = dst.wrapping_add(at - src as usize);
- if !read(at as *const u8, to, n) {
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
- // SAFETY: inside the destination, which is mapped.
- unsafe { to.write_bytes(0, n) };
- }
- });
- }
- });
- }
- /// Reads title memory at `src` into `dst`; false if a page of it is not
- /// readable.
- pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
- read(src, dst.as_mut_ptr(), dst.len())
- }
- /// Copies `len` bytes from `src` to `dst` unless a source page is not
- /// readable.
- fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
- use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- let mut done = 0;
- // SAFETY: the destination is mapped writable memory of `len` bytes; the
- // kernel checks the source.
- unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
- }
- /// Copies host memory into title memory after a submission (what shaders
- /// wrote), leaving pages that are not mapped alone.
- pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
- use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- let write = |at: usize, n: usize| {
- let from = src.wrapping_add(at - dst as usize);
- let mut done = 0;
- // SAFETY: the source is our mapped host copy; the kernel checks the
- // destination.
- unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
- };
- if len == 0 || write(dst as usize, len) {
- return;
- }
- for_pieces(dst as usize, len, 64 << 10, |at, n| {
- if !write(at, n) {
- for_pieces(at, n, 4 << 10, |at, n| {
- write(at, n);
- });
- }
- });
- }
- /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
- /// `step`.
- fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
- let end = start + len;
- let mut at = start;
- while at < end {
- let next = ((at / step + 1) * step).min(end);
- f(at, next - at);
- at = next;
- }
- }
- impl Host {
- /// A buffer in the upload heap, mapped for writing.
- pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
- let heap = D3D12_HEAP_PROPERTIES {
- Type: D3D12_HEAP_TYPE_UPLOAD,
- ..Default::default()
- };
- let desc = D3D12_RESOURCE_DESC {
- Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
- Width: size.max(1),
- Height: 1,
- DepthOrArraySize: 1,
- MipLevels: 1,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
- ..Default::default()
- };
- let mut buffer: Option<ID3D12Resource> = None;
- let mut data = std::ptr::null_mut();
- // SAFETY: plain creation and mapping of an upload buffer.
- let made = unsafe {
- self.device
- .CreateCommittedResource(
- &heap,
- D3D12_HEAP_FLAG_NONE,
- &desc,
- D3D12_RESOURCE_STATE_GENERIC_READ,
- None,
- &mut buffer,
- )
- .and_then(|()| {
- let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
- b.Map(0, None, Some(&mut data))
- })
- };
- match made {
- Ok(()) => Some((buffer?, data.cast())),
- Err(e) => {
- tracing::warn!(error = %e, size, "no upload buffer");
- None
- }
- }
- }
- }
- /// The swap chain formats a presented texture can be copied into: its own
- /// family's.
- fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
- Some(match format.0 {
- 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
- 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
- 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
- 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
- _ => return None,
- })
- }
- const BUFFERS: u32 = 2;
- struct Presenter {
- swap_chain: IDXGISwapChain3,
- width: u32,
- height: u32,
- format: DXGI_FORMAT,
- copy: HostList,
- hwnd: HWND,
- meter: Meter,
- }
- /// The frame rate, shown in the window's caption every second and logged
- /// every few seconds.
- struct Meter {
- since: std::time::Instant,
- frames: u32,
- drawn: u64,
- logged: std::time::Instant,
- /// The caption the window had, once read.
- caption: Option<Vec<u16>>,
- }
- impl Meter {
- fn new() -> Self {
- let now = std::time::Instant::now();
- Meter {
- since: now,
- frames: 0,
- drawn: crate::draw::drawn(),
- logged: now,
- caption: None,
- }
- }
- /// Counts a presented frame.
- fn frame(&mut self, hwnd: HWND) {
- #[cfg(feature = "diagnostics")]
- tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
- self.frames += 1;
- let elapsed = self.since.elapsed();
- if elapsed < std::time::Duration::from_secs(1) {
- return;
- }
- let drawn = crate::draw::drawn();
- let frames = f64::from(self.frames);
- let fps = frames / elapsed.as_secs_f64();
- let ms = elapsed.as_secs_f64() * 1000.0 / frames;
- let draws = (drawn - self.drawn) as f64 / frames;
- (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
- // Of a frame, ms preparing submissions and ms waiting for the GPU.
- let [cpu, gpu] = [0, 1].map(|i| {
- SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
- });
- let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
- let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
- PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
- });
- let [back_ms, back_mb] = [0, 1].map(|i| {
- COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
- });
- let dropped = crate::draw::take_dropped() as f64 / frames;
- let indirect = crate::list::take_indirect() as f64 / frames;
- if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
- self.logged = std::time::Instant::now();
- tracing::info!(
- "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
- {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
- GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
- dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect"
- );
- #[cfg(feature = "diagnostics")]
- crate::copystat::log(frames);
- }
- if self.caption.is_none() {
- // The window's own text, read without a message.
- let mut buffer = vec![0u16; 512];
- // SAFETY: a window handle and a buffer of that length.
- let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
- buffer.truncate(n.max(0) as usize);
- self.caption = Some(buffer);
- }
- let Some(caption) = &self.caption else { return };
- let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
- let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
- text.push(0);
- // Setting the text waits for the window's thread (a title thread,
- // which may not pump for a while), so a thread of ours does it and
- // presenting never waits; it takes the newest text when free.
- static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
- static SETTER: std::sync::Once = std::sync::Once::new();
- *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
- SETTER.call_once(|| {
- let _ = std::thread::Builder::new()
- .name("victory-caption".into())
- .spawn(|| {
- loop {
- let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
- match next {
- // SAFETY: a window handle and a NUL-terminated text.
- Some((hwnd, text)) => unsafe {
- let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
- },
- None => std::thread::sleep(std::time::Duration::from_millis(100)),
- }
- }
- });
- });
- }
- }
- impl Host {
- /// Shows `texture`, which is in `state` (a host state) and stays in it,
- /// as frame `frame` (saved if captures are on). `None` if nothing was
- /// shown; else, in diagnostics builds, whether the frame was black.
- pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
- // SAFETY: a live resource.
- let desc = unsafe { texture.GetDesc() };
- let Some(format) = swap_format(desc.Format) else {
- tracing::warn!(format = desc.Format.0, "cannot present this format");
- return None;
- };
- let (width, height) = (desc.Width as u32, desc.Height);
- let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
- if presenter.is_none() {
- *presenter = match self.presenter(width, height, format) {
- Ok(p) => Some(p),
- Err(e) => {
- tracing::warn!(error = %e, "no swap chain");
- return None;
- }
- };
- }
- let p = presenter.as_mut()?;
- if (p.width, p.height, p.format) != (width, height, format) {
- // SAFETY: no back buffer is held; every submission was waited for.
- let resized = unsafe {
- p.swap_chain
- .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
- };
- match resized {
- Ok(()) => (p.width, p.height, p.format) = (width, height, format),
- Err(e) => {
- tracing::warn!(error = %e, width, height, "swap chain not resized");
- return None;
- }
- }
- }
- let state = D3D12_RESOURCE_STATES(state as i32);
- // SAFETY: our swap chain, list and a live source texture.
- unsafe {
- let index = p.swap_chain.GetCurrentBackBufferIndex();
- let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
- return None;
- };
- p.copy.reset();
- let list = &p.copy.list;
- list.ResourceBarrier(&[
- transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
- transition(
- &back,
- D3D12_RESOURCE_STATE_PRESENT,
- D3D12_RESOURCE_STATE_COPY_DEST,
- ),
- ]);
- list.CopyResource(&back, texture);
- #[cfg(feature = "diagnostics")]
- let capture = crate::capture::wanted(frame)
- .then(|| crate::capture::read_back(&self.device, list, texture))
- .flatten();
- #[cfg(feature = "diagnostics")]
- let probe = crate::capture::probe(&self.device, list, texture);
- #[cfg(not(feature = "diagnostics"))]
- let _ = frame;
- list.ResourceBarrier(&[
- transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
- transition(
- &back,
- D3D12_RESOURCE_STATE_COPY_DEST,
- D3D12_RESOURCE_STATE_PRESENT,
- ),
- ]);
- p.copy.close();
- self.execute(&[&p.copy]);
- #[cfg(feature = "diagnostics")]
- if let Some((buffer, footprint)) = capture {
- crate::capture::save_read_back(frame, &buffer, &footprint);
- }
- let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
- p.meter.frame(p.hwnd);
- #[cfg(feature = "diagnostics")]
- return Some(probe.is_some_and(|b| crate::capture::black(&b)));
- #[cfg(not(feature = "diagnostics"))]
- Some(false)
- }
- }
- fn presenter(
- &self,
- width: u32,
- height: u32,
- format: DXGI_FORMAT,
- ) -> windows::core::Result<Presenter> {
- let hwnd = match title_window() {
- Some(hwnd) => hwnd,
- None => window(width, height)?,
- };
- // SAFETY: plain object creation for our window.
- unsafe {
- let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
- let desc = DXGI_SWAP_CHAIN_DESC1 {
- Width: width,
- Height: height,
- Format: format,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
- BufferCount: BUFFERS,
- SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
- ..Default::default()
- };
- let swap_chain = factory
- .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
- .cast::<IDXGISwapChain3>()?;
- let copy = self.new_list()?;
- copy.close();
- tracing::info!(width, height, format = format.0, "presenting to a window");
- Ok(Presenter {
- swap_chain,
- width,
- height,
- format,
- copy,
- hwnd,
- meter: Meter::new(),
- })
- }
- }
- }
- /// A visible top-level window of this process: the one the title made, if
- /// it made one.
- fn title_window() -> Option<HWND> {
- extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
- let mut process = 0;
- // SAFETY: a window handle from the enumeration; `found` is ours.
- unsafe {
- GetWindowThreadProcessId(hwnd, Some(&mut process));
- if process == windows::Win32::System::Threading::GetCurrentProcessId()
- && IsWindowVisible(hwnd).as_bool()
- {
- *(found.0 as *mut Option<HWND>) = Some(hwnd);
- return false.into();
- }
- }
- true.into()
- }
- let mut found: Option<HWND> = None;
- // SAFETY: the callback only writes `found`, which outlives the call.
- let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
- found
- }
- /// `state` without the bits the host texture's flags forbid: the console
- /// lets the title name states its own resources allow (unordered access on
- /// a depth target, whose host copy cannot have both).
- pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
- // SAFETY: a plain query.
- legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
- }
- /// [`legal_state`] for a texture with resource flags `flags`.
- pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
- // (flag, set or clear forbids, state bits): render target, unordered
- // access, depth, denied shader resource.
- const FORBIDDEN: [(u32, bool, u32); 4] = [
- (0x1, false, 0x4),
- (0x4, false, 0x8),
- (0x2, false, 0x10 | 0x20),
- (0x8, true, 0x40 | 0x80),
- ];
- FORBIDDEN
- .iter()
- .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
- .fold(state, |s, &(_, _, bits)| s & !bits)
- }
- impl Host {
- /// A buffer in system memory that the CPU maps (write-back, so reading
- /// it is fast too) and shaders read and write: for host copies of title
- /// memory that shaders write, which upload memory cannot be. Starts in
- /// the common state (buffers move out of it implicitly).
- pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
- 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(1),
- 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 creation and mapping of a CPU-visible buffer.
- let made = unsafe {
- self.device
- .CreateCommittedResource(
- &heap,
- D3D12_HEAP_FLAG_NONE,
- &desc,
- D3D12_RESOURCE_STATE_COMMON,
- None,
- &mut buffer,
- )
- .and_then(|()| {
- let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
- b.Map(0, None, Some(&mut data))
- })
- };
- match made {
- Ok(()) => Some((buffer?, data.cast())),
- Err(e) => {
- tracing::warn!(error = %e, size, "no shared buffer");
- None
- }
- }
- }
- }
- /// For adapters without device-removed data (the software one): the last
- /// commands each list of the failed submission noted (diagnostics, with
- /// `VICTORY_D3D12_DRED`).
- fn last_notes(runs: &[&HostList]) -> String {
- #[cfg(feature = "diagnostics")]
- {
- let mut text = String::new();
- for (i, r) in runs.iter().enumerate() {
- let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
- for (n, _) in notes.iter().rev().take(6).rev() {
- text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
- }
- }
- text
- }
- #[cfg(not(feature = "diagnostics"))]
- {
- let _ = runs;
- String::new()
- }
- }
- /// Where the faulting address `va` lies against a range `(start, bytes)` a
- /// command reads (diagnostics).
- #[cfg(feature = "diagnostics")]
- fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
- let end = start + bytes;
- if va < start {
- format!(" (fault {:#x} below its source)", start - va)
- } else if va < end {
- format!(" (fault at source +{:#x})", va - start)
- } else {
- format!(" (fault {:#x} past its source's end)", va - end)
- }
- }
- /// The commands that may have been running where a list stopped at
- /// command `done`: those between the barriers around it (work between
- /// barriers overlaps on the GPU), by kind, and what the markers just
- /// before them say (`HostList::note_op`: diagnostics builds with
- /// device-removed data on).
- fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
- let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
- let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
- let to = history[done..]
- .iter()
- .position(barrier)
- .map_or(history.len(), |b| (done + b).max(done + 1));
- let mut text = format!(", commands {from}..{to} between its barriers:");
- let mut shown = 0;
- for i in from..to {
- let op = history[i];
- if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
- continue;
- }
- shown += 1;
- let marker = i
- .checked_sub(1)
- .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
- .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
- .map_or("no marker", |(_, s)| s.as_str());
- text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
- }
- text
- }
- pub(crate) fn transition(
- resource: &ID3D12Resource,
- before: D3D12_RESOURCE_STATES,
- after: D3D12_RESOURCE_STATES,
- ) -> D3D12_RESOURCE_BARRIER {
- D3D12_RESOURCE_BARRIER {
- Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
- Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
- Anonymous: D3D12_RESOURCE_BARRIER_0 {
- Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
- // SAFETY: a borrowed pointer; the barrier never releases it.
- pResource: unsafe { std::mem::transmute_copy(resource) },
- Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
- StateBefore: before,
- StateAfter: after,
- }),
- },
- }
- }
- /// A window of the given client size, owned by its own message thread.
- fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
- let (sender, receiver) = std::sync::mpsc::channel();
- std::thread::Builder::new()
- .name("victory-window".into())
- .spawn(move || {
- let made = make_window(width, height);
- let ok = made.is_ok();
- let _ = sender.send(made.map(|h| h.0 as usize));
- if ok {
- pump();
- }
- })
- .map_err(|_| windows::core::Error::empty())?;
- let hwnd = receiver
- .recv()
- .map_err(|_| windows::core::Error::empty())??;
- Ok(HWND(hwnd as *mut _))
- }
- extern "system" fn window_proc(
- hwnd: HWND,
- message: u32,
- wparam: WPARAM,
- lparam: LPARAM,
- ) -> LRESULT {
- // SAFETY: the default handling for our window.
- unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
- }
- fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
- const CLASS: PCWSTR = w!("VIctory");
- // SAFETY: registers our class once and creates a window of it.
- unsafe {
- let instance = GetModuleHandleW(None)?;
- let class = WNDCLASSEXW {
- cbSize: size_of::<WNDCLASSEXW>() as u32,
- lpfnWndProc: Some(window_proc),
- hInstance: instance.into(),
- lpszClassName: CLASS,
- hCursor: LoadCursorW(None, IDC_ARROW)?,
- ..Default::default()
- };
- RegisterClassExW(&class);
- let mut rect = RECT {
- left: 0,
- top: 0,
- right: width as i32,
- bottom: height as i32,
- };
- AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
- CreateWindowExW(
- WINDOW_EX_STYLE(0),
- CLASS,
- w!("VIctory"),
- WS_OVERLAPPEDWINDOW | WS_VISIBLE,
- CW_USEDEFAULT,
- CW_USEDEFAULT,
- rect.right - rect.left,
- rect.bottom - rect.top,
- None,
- None,
- Some(instance.into()),
- None,
- )
- }
- }
- fn pump() {
- let mut message = MSG::default();
- // SAFETY: the standard message loop of this thread's window.
- unsafe {
- while GetMessageW(&mut message, None, 0, 0).as_bool() {
- let _ = TranslateMessage(&message);
- DispatchMessageW(&message);
- }
- }
- }
|