diff --git a/README.md b/README.md index f55cad72e..cf8f6ea7e 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,10 @@ A **gamepad is recommended**: console games are made for one, and their menus an E / Q Y / X, Shift / Ctrl the stick clicks, Tab View, P Menu. `keyboard_mouse` and `mouse_sensitivity` in the game's `xcl.toml` turn it off or change the mouse speed. A gamepad and the keyboard / mouse can be used together. +- **Fullscreen:** Alt+Enter or F11 puts the XCL window in borderless fullscreen on its monitor and back + (Alt+Enter does not press A). `fullscreen = true` in `xcl.toml` starts in it. When the window's shape + differs from the game image's and the window is smaller than the image, the image keeps its aspect + ratio, centred with black bars. ## Building and usage diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 1503e550a..20d3718e5 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -60,6 +60,9 @@ pub struct Config { /// "center" (the primary monitor's work area), or "x,y" (top-left of the window, screen /// coordinates; clamped into the nearest monitor's work area). `XCL_WINDOW_POS` overrides. pub window_pos: String, + /// Start the XCL window in borderless fullscreen on its monitor (Alt+Enter / F11 toggle it + /// while the game runs; see `hle::d3d12x::window_mode`). + pub fullscreen: bool, /// Answer `XUserGetTokenAndSignature*` with XCL's local placeholder token (for a backend of /// your own that accepts it). Off: the request fails as on a console that cannot reach Xbox /// Live (0x80072EFD), and titles go their offline way – Xbox Live's and the titles' own @@ -184,6 +187,7 @@ impl Default for Config { window_width: 1280, window_height: 720, window_pos: "auto".into(), + fullscreen: false, xbox_live_tokens: false, keyboard_mouse: true, mouse_sensitivity: 1.0, @@ -304,6 +308,9 @@ mod tests { assert!(c.is_series_s()); assert_eq!(c.gamertag, "Player1"); assert_eq!(c.raytracing, "auto"); + assert!(!c.fullscreen, "windowed unless xcl.toml says fullscreen"); + let c: Config = toml::from_str("fullscreen = true\n").unwrap(); + assert!(c.fullscreen); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 3d0619897..db3b82cec 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,7 @@ pub mod sparse; pub mod title_list; pub mod title_textures; pub mod vram; +pub mod window_mode; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 83a909468..4363de5e8 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -34,6 +34,9 @@ use windows::Win32::UI::WindowsAndMessaging::*; use crate::gpu::fence::{self, FenceError}; use crate::stubs::StubInfo; +pub(super) mod downscale; +use downscale::Route; + static RTVS: Mutex>> = Mutex::new(None); static LISTS: Mutex>> = Mutex::new(None); static CANDIDATE: Mutex> = Mutex::new(None); // (queue, resource) – resource AddRef'd @@ -311,6 +314,13 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) if crate::hle::kbm::on_message(hwnd.0, msg, wp.0, lp.0) { return LRESULT(0); } + // Alt+Enter / F11: borderless fullscreen on / off + if let Some(k) = super::window_mode::key(msg, wp.0, lp.0) { + if k == super::window_mode::Key::Toggle { + super::window_mode::toggle(hwnd); + } + return LRESULT(0); + } match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); @@ -451,6 +461,9 @@ fn window_thread() { HWND_RAW.store(hwnd.0 as isize, Ordering::Release); crate::xlog_info!("XCL window created ({}x{})", cfg.window_width, cfg.window_height); crate::hle::kbm::attach(hwnd.0); + if cfg.fullscreen { + super::window_mode::toggle(hwnd); + } SetTimer(Some(hwnd), COMPILE_TIMER, 500, None); let mut msg = MSG::default(); while GetMessageW(&mut msg, None, 0, 0).as_bool() { @@ -530,6 +543,14 @@ struct Presenter { fence: ID3D12Fence, copy_source: Option, dumps: Vec, + /// the area filter for a window smaller than the image (`downscale`); failed: copy only + scaler: Option, + scaler_failed: bool, + /// the route last logged, with the image size + route: Option<(Route, (u32, u32))>, + /// the swap chain size (and format) ResizeBuffers last refused, and when: logged once, + /// asked for again twice a second + resize_failed: Option<((u32, u32, DXGI_FORMAT), Instant)>, disabled: bool, value: u64, event: HANDLE, @@ -566,6 +587,11 @@ unsafe fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: unsafe fn new_presenter(queue: usize) -> Option { let dev_raw = super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&dev_raw)?; + presenter_for(dev, queue) +} + +/// A presenter on `dev` for the title's `queue` (its swap chain is made at the first frame). +unsafe fn presenter_for(dev: &ID3D12Device, queue: usize) -> Option { let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; list.Close().ok()?; @@ -573,24 +599,41 @@ unsafe fn new_presenter(queue: usize) -> Option { let event = CreateEventW(None, false, false, None).ok()?; Some(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence, - copy_source: None, dumps: Vec::new(), disabled: false, value: 0, event, + copy_source: None, dumps: Vec::new(), scaler: None, scaler_failed: false, route: None, resize_failed: None, disabled: false, value: 0, event, last: Instant::now() - Duration::from_secs(1), }) } unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: DXGI_FORMAT) -> bool { - if let Some(sc) = &p.sc { + if let Some(sc) = p.sc.clone() { if p.w == w && p.h == h && p.fmt == fmt { return true; } - if sc.ResizeBuffers(2, w, h, fmt, DXGI_SWAP_CHAIN_FLAG(0)).is_ok() { - p.w = w; - p.h = h; - p.fmt = fmt; - crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt); - return true; + let want = (w, h, fmt); + // a size refused just now is not asked for again every frame + if p.resize_failed.is_some_and(|(f, t)| f == want && t.elapsed() < Duration::from_millis(500)) { + return false; + } + // the GPU is done with the back buffers: every draw into them came before the previous + // copy's signal on this queue, waited for in `present_frame` + match sc.ResizeBuffers(2, w, h, fmt, DXGI_SWAP_CHAIN_FLAG(0)) { + Ok(()) => { + p.w = w; + p.h = h; + p.fmt = fmt; + p.resize_failed = None; + crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt); + return true; + } + Err(e) => { + if p.resize_failed.map(|(f, _)| f) != Some(want) { + let why = e.message(); + crate::xlog_warn!("present: ResizeBuffers to {w}x{h} {fmt:?}: {:#010x} {} – the swap chain stays {}x{}", e.code().0 as u32, why.lines().next().unwrap_or_default(), p.w, p.h); + } + p.resize_failed = Some((want, Instant::now())); + return false; + } } - return false; } let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return false }; let qraw = p.queue as *mut c_void; @@ -668,36 +711,85 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { return; } let Some(desc) = backbuffer_like(src.as_raw() as usize) else { return }; - let Some(fmt) = swap_format(desc.Format) else { return }; let Some(hwnd) = ensure_window() else { return }; if p.queue != queue { return; // swap chain is bound to the first queue we presented from } + if !present_frame(p, hwnd, src, &desc) { + return; + } + let n = PRESENTS.fetch_add(1, Ordering::Relaxed); + if n == 0 { + crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); + } +} + +/// Show `src` (described by `desc`) in `hwnd` through `p`'s swap chain, on `p.queue`: false when +/// no frame was shown (minimized, the previous copy not done in time, an error). +unsafe fn present_frame(p: &mut Presenter, hwnd: HWND, src: ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> bool { + let Some(fmt) = swap_format(desc.Format) else { return false }; // wait for the previous copy so the allocator can be reused if let Err(e) = fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 100) { p.disabled = matches!(&e, FenceError::Removed(_)); if !matches!(&e, FenceError::Timeout(_)) { crate::xlog_error!("present: previous copy: {e}"); } - return; + return false; } p.copy_source = None; p.dumps.clear(); - if !ensure_swapchain(p, hwnd, desc.Width as u32, desc.Height, fmt) { - return; + let image = (desc.Width as u32, desc.Height); + let client = client_size(hwnd); + let mut route = downscale::route(image, client); + if route == Route::Filter && !scaler_ready(p, fmt) { + route = Route::Copy; + } + if p.route != Some((route, image)) { + let how = match route { + Route::Filter => "area filter into a swap chain of the client size", + Route::Copy => "copy, the window stretches it", + Route::Skip => "nothing shown, the swap chain keeps its size", + }; + crate::xlog_info!("present: {}x{} image in a {}x{} client area – {how}", image.0, image.1, client.0, client.1); + p.route = Some((route, image)); } - let Some(sc) = p.sc.clone() else { return }; - let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return }; + if route == Route::Skip { + return false; + } + let (mut sw, mut sh) = if route == Route::Filter { client } else { image }; + if !ensure_swapchain(p, hwnd, sw, sh, fmt) { + // the swap chain keeps its size this frame and the filter draws the image into it (the + // window stretches it): a resize never costs a frame + if p.sc.is_none() || !scaler_ready(p, p.fmt) { + return false; + } + (route, sw, sh) = (Route::Filter, p.w, p.h); + } + let Some(sc) = p.sc.clone() else { return false }; + let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return false }; if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { - return; + return false; } - let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; - p.list.ResourceBarrier(&b1); - p.list.CopyResource(&bb, &src); + // the back buffer's state while it is written + let written = match (route, &p.scaler) { + (Route::Filter, Some(scaler)) => { + p.list.ResourceBarrier(&[transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + // the title's image is promoted from COMMON to a shader resource, as for the copy + // at the image's aspect, centred, black bars around it + scaler.record(&p.dev, &p.list, &src, &bb, super::window_mode::letterbox(image, (sw, sh))); + D3D12_RESOURCE_STATE_RENDER_TARGET + } + _ => { + let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; + p.list.ResourceBarrier(&b1); + p.list.CopyResource(&bb, &src); + D3D12_RESOURCE_STATE_COPY_DEST + } + }; let due = frame_dump_due(); let mut dumps = Vec::new(); if due { - if let Some((buffer, footprint)) = readback_copy(&p.list, &src, &desc) { + if let Some((buffer, footprint)) = readback_copy(&p.list, &src, desc) { dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format: desc.Format, tag: "frame".into() }); } } @@ -724,14 +816,14 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { dumps.push(FrameDump { _source: res, buffer, footprint, format, tag }); } } - let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; + let b2 = [transition(&bb, written, D3D12_RESOURCE_STATE_PRESENT)]; p.list.ResourceBarrier(&b2); if p.list.Close().is_err() { - return; + return false; } - let qraw = queue as *mut c_void; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; - let Ok(cl) = p.list.cast::() else { return }; + let qraw = p.queue as *mut c_void; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return false }; + let Ok(cl) = p.list.cast::() else { return false }; q.ExecuteCommandLists(&[Some(cl)]); p.copy_source = Some(src); p.dumps = dumps; @@ -741,13 +833,13 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { p.disabled = true; let e = fence::api_error(&p.dev, "Signal", e); crate::xlog_error!("present: submit copy: {e}"); - return; + return false; } if let Err(e) = sc.Present(0, DXGI_PRESENT(0)).ok() { let e = fence::api_error(&p.dev, "Present", e); p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: {e}"); - return; + return false; } p.last = Instant::now(); if !p.dumps.is_empty() { @@ -761,15 +853,41 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: frame dump copy: {e}"); if p.disabled { - return; + return false; } } } } - let n = PRESENTS.fetch_add(1, Ordering::Relaxed); - if n == 0 { - crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); + true +} + +/// The XCL window's client area (0x0 when minimized or unknown). +unsafe fn client_size(hwnd: HWND) -> (u32, u32) { + let mut rc = RECT::default(); + if GetClientRect(hwnd, &mut rc).is_err() { + return (0, 0); + } + ((rc.right - rc.left).max(0) as u32, (rc.bottom - rc.top).max(0) as u32) +} + +/// The area filter for back buffers of `fmt` is made (once per format; a failure – no DXC – +/// leaves the copy for good, with one log line). +unsafe fn scaler_ready(p: &mut Presenter, fmt: DXGI_FORMAT) -> bool { + if p.scaler.as_ref().is_some_and(|s| s.fmt == fmt) { + return true; + } + // inside a non-blocking pipeline creation nothing may compile: the copy this time + if p.scaler_failed || crate::gpu::recomp::dxc::in_cached_only() { + return false; + } + match downscale::Scaler::new(&p.dev, fmt) { + Ok(s) => p.scaler = Some(s), + Err(e) => { + p.scaler_failed = true; + crate::xlog_warn!("present: no area filter for a window smaller than the image ({e}) – the window stretches the copy"); + } } + p.scaler.is_some() } /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`, diff --git a/crates/xcl/src/hle/d3d12x/present/downscale.rs b/crates/xcl/src/hle/d3d12x/present/downscale.rs new file mode 100644 index 000000000..966b3e398 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/present/downscale.rs @@ -0,0 +1,544 @@ +//! The title's image shrunk to the XCL window's client area by XCL itself. +//! +//! A 3840x2160 frame copied into a swap chain of its own size is shrunk by DWM with a single +//! bilinear tap per window pixel: at 3x (1280x720) or 1.5x it skips texels, and thin strokes and +//! text stair-step. Here the swap chain is the client size instead, and a full-screen triangle's +//! pixel shader averages the whole footprint of each window pixel in the game image (an area / +//! box filter, exact partial-texel weights), in linear light. +//! +//! Linear light: 8- and 10-bit UNORM images are decoded with the sRGB curve before averaging +//! and encoded again after – the swap chain has the default (sRGB) colour space, so that is how +//! the window shows those values; an _SRGB source is decoded by its view. FP16 is scRGB, linear +//! already. + +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use crate::hle::d3d12x::window_mode::Area; + +/// How the title's image reaches the window. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + /// copied into a swap chain of the image's size, DWM stretches it (the window is as large) + Copy, + /// drawn into a swap chain of the client size through the area filter + Filter, + /// not shown: the client area is empty (minimized), the swap chain keeps its size + Skip, +} + +/// `Skip` when the client area is empty (minimized); `Filter` when it is smaller than the image +/// on either side; `Copy` when it is as large or larger. +pub fn route(image: (u32, u32), client: (u32, u32)) -> Route { + if client.0 == 0 || client.1 == 0 { + Route::Skip + } else if client.0 >= image.0 && client.1 >= image.1 { + Route::Copy + } else { + Route::Filter + } +} + +const SHADER: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL)" +Texture2D src : register(t0); +// dst: the drawn rectangle's size, org: its top-left in the back buffer +cbuffer C : register(b0) { uint2 dst; uint flags; uint pad; uint2 org; }; + +[RootSignature(RS)] +float4 vs(uint id : SV_VertexID) : SV_Position { + float2 t = float2((id << 1) & 2, id & 2); + return float4(t * float2(2, -2) + float2(-1, 1), 0, 1); +} + +float3 decode(float3 c) { return select(c <= 0.04045, c / 12.92, pow((c + 0.055) / 1.055, 2.4)); } +float3 encode(float3 c) { return select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0 / 2.4) - 0.055); } + +// the mean of the texels under this window pixel, each weighted by the area it covers +[RootSignature(RS)] +float4 ps(float4 pos : SV_Position) : SV_Target { + uint sw, sh; + src.GetDimensions(sw, sh); + float2 s = float2(sw, sh) / float2(dst); + float2 lo = (floor(pos.xy) - float2(org)) * s; + float2 hi = min(lo + s, float2(sw, sh)); + int2 a = (int2)floor(lo); + int2 b = (int2)ceil(hi); + float4 sum = 0; + float total = 0; + for (int y = a.y; y < b.y; y++) { + float wy = min(hi.y, y + 1) - max(lo.y, y); + for (int x = a.x; x < b.x; x++) { + float w = wy * (min(hi.x, x + 1) - max(lo.x, x)); + float4 c = src.Load(int3(x, y, 0)); + if (flags & 1) c.rgb = decode(saturate(c.rgb)); + sum += c * w; + total += w; + } + } + float4 r = sum / max(total, 1e-6); + if (flags & 2) r.rgb = encode(saturate(r.rgb)); + return r; +} +"#; + +/// The area-filter pipeline for one back buffer format, with its two descriptors. +pub struct Scaler { + pub fmt: DXGI_FORMAT, + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + srv: ID3D12DescriptorHeap, + rtv: ID3D12DescriptorHeap, +} + +/// The SRV format for a source of `f` (a typeless one is read as UNORM / FLOAT, like the copy). +fn view_format(f: DXGI_FORMAT) -> DXGI_FORMAT { + match f { + DXGI_FORMAT_R8G8B8A8_TYPELESS => DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_B8G8R8A8_TYPELESS => DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_R10G10B10A2_TYPELESS => DXGI_FORMAT_R10G10B10A2_UNORM, + DXGI_FORMAT_R16G16B16A16_TYPELESS => DXGI_FORMAT_R16G16B16A16_FLOAT, + f => f, + } +} + +impl Scaler { + /// The pipeline drawing into a `fmt` render target on `dev` (Err: no DXC, or the device + /// refused it). + pub unsafe fn new(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> Result { + use crate::gpu::recomp::dxc::compile_cached; + let (vs, _) = compile_cached(SHADER, "vs", "vs_6_0")?; + let (ps, _) = compile_cached(SHADER, "ps", "ps_6_0")?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &ps).map_err(|e| format!("CreateRootSignature: {e}"))?; + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RTVFormats[0] = fmt; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|e| format!("CreateGraphicsPipelineState: {e}"))?; + let heap = |ty, flags| { + dev.CreateDescriptorHeap::(&D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: 1, Flags: flags, NodeMask: 0 }) + .map_err(|e| format!("CreateDescriptorHeap: {e}")) + }; + let srv = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + let rtv = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?; + Ok(Scaler { fmt, rs, pso, srv, rtv }) + } + + /// Record on `list` the draw of `src` (subresource 0, readable as a pixel shader resource) + /// into `area` of `dst` (`self.fmt`, in RENDER_TARGET state), the rest of `dst` cleared to + /// opaque black (`window_mode::letterbox`). The descriptors are rewritten: the previous + /// recording must have finished on the GPU. + pub unsafe fn record(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, dst: &ID3D12Resource, area: Area) { + let view = view_format(src.GetDesc().Format); + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: view, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, ..Default::default() } }, + }; + dev.CreateShaderResourceView(src, Some(&srv_desc), self.srv.GetCPUDescriptorHandleForHeapStart()); + let rtv = self.rtv.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(dst, None, rtv); + // `dev` is the title's (adopted) device: its CreateRenderTargetView hook keeps a reference + // to the view's resource for guessing the title's frame (`note_rtv`). Held on a swap chain + // buffer, that reference makes every ResizeBuffers fail (DXGI_ERROR_INVALID_CALL): the + // presenter's own view is forgotten at once. + super::note_rtv(rtv.ptr, std::ptr::null_mut()); + let decode = matches!(view, DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM); + let encode = self.fmt != DXGI_FORMAT_R16G16B16A16_FLOAT; + let constants = [area.w, area.h, decode as u32 | (encode as u32) << 1, 0, area.x, area.y]; + list.ClearRenderTargetView(rtv, &[0.0, 0.0, 0.0, 1.0], None); + list.SetGraphicsRootSignature(&self.rs); + list.SetDescriptorHeaps(&[Some(self.srv.clone())]); + list.SetGraphicsRoot32BitConstants(0, 6, constants.as_ptr() as _, 0); + list.SetGraphicsRootDescriptorTable(1, self.srv.GetGPUDescriptorHandleForHeapStart()); + list.SetPipelineState(&self.pso); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + let (x, y, w, h) = (area.x as f32, area.y as f32, area.w as f32, area.h as f32); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: x, TopLeftY: y, Width: w, Height: h, MinDepth: 0.0, MaxDepth: 1.0 }]); + let (x, y) = (area.x as i32, area.y as i32); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: x, top: y, right: x + area.w as i32, bottom: y + area.h as i32 }]); + list.OMSetRenderTargets(1, Some(&rtv as *const _), false, None); + list.DrawInstanced(3, 1, 0, 0); + } +} + +#[cfg(test)] +pub(in crate::hle::d3d12x) mod tests { + use super::*; + use windows::core::{w, Interface, PCWSTR}; + use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::LibraryLoader::GetModuleHandleW; + use windows::Win32::UI::WindowsAndMessaging::*; + + #[test] + fn route_filters_only_when_the_window_is_smaller() { + let uhd = (3840, 2160); + for client in [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2000), (3000, 2160)] { + assert_eq!(route(uhd, client), Route::Filter, "{client:?}"); + } + for client in [(3840, 2160), (5120, 2880)] { + assert_eq!(route(uhd, client), Route::Copy, "{client:?}"); + } + // minimized: nothing shown – not a copy into a swap chain resized to the image + for client in [(0, 0), (1280, 0), (0, 720)] { + assert_eq!(route(uhd, client), Route::Skip, "{client:?}"); + } + } + + fn srgb_to_linear(c: f64) -> f64 { + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + } + + fn linear_to_srgb(c: f64) -> f64 { + if c <= 0.0031308 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } + } + + /// 1-pixel lines and a 1-pixel checker, the hard case for a single bilinear tap. + pub(in crate::hle::d3d12x) fn pattern(w: usize, h: usize) -> Vec { + let mut v = vec![0u8; w * h * 4]; + for y in 0..h { + for x in 0..w { + let t = &mut v[(y * w + x) * 4..][..4]; + t[0] = if (x + y) % 2 == 0 { 255 } else { 0 }; + t[1] = if x % 7 == 0 || y % 5 == 0 { 255 } else { 16 }; + t[2] = ((x * 3 + y * 5) % 256) as u8; + t[3] = 255; + } + } + v + } + + /// The area filter on the CPU, in linear light (sRGB curve), as 8-bit sRGB. + pub(in crate::hle::d3d12x) fn reference(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<[f64; 3]> { + let lut: Vec = (0..256).map(|v| srgb_to_linear(v as f64 / 255.0)).collect(); + let (sx, sy) = (sw as f64 / dw as f64, sh as f64 / dh as f64); + let mut out = Vec::with_capacity(dw * dh); + for oy in 0..dh { + let (ly, hy) = (oy as f64 * sy, (oy as f64 + 1.0) * sy); + for ox in 0..dw { + let (lx, hx) = (ox as f64 * sx, (ox as f64 + 1.0) * sx); + let (mut sum, mut total) = ([0.0; 3], 0.0); + for y in ly.floor() as usize..(hy.ceil() as usize).min(sh) { + let wy = hy.min(y as f64 + 1.0) - ly.max(y as f64); + for x in lx.floor() as usize..(hx.ceil() as usize).min(sw) { + let wt = wy * (hx.min(x as f64 + 1.0) - lx.max(x as f64)); + for c in 0..3 { + sum[c] += wt * lut[src[(y * sw + x) * 4 + c] as usize]; + } + total += wt; + } + } + out.push(sum.map(|s| 255.0 * linear_to_srgb(s / total))); + } + } + out + } + + fn buffer(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() + } + + fn texture(dev: &ID3D12Device, w: u32, h: u32, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() + } + + fn copy_location(r: &ID3D12Resource, fp: Option) -> D3D12_TEXTURE_COPY_LOCATION { + unsafe { + match fp { + Some(fp) => D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }, + None => D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }, + } + } + } + + /// A `w`x`h` RGBA8 texture holding `src`, left in `after`: the upload is recorded on `list` + /// (the upload buffer returned with it must live until the list ran). + unsafe fn upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &[u8], w: u32, h: u32, after: D3D12_RESOURCE_STATES) -> (ID3D12Resource, ID3D12Resource) { + let tex = texture(dev, w, h, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let (mut fp, mut size) = (D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(), 0u64); + dev.GetCopyableFootprints(&tex.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut size)); + let up = buffer(dev, size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..h as usize { + let row = &src[y * w as usize * 4..][..w as usize * 4]; + std::ptr::copy_nonoverlapping(row.as_ptr(), (p as *mut u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row.len()); + } + up.Unmap(0, None); + list.CopyTextureRegion(©_location(&tex, None), 0, 0, 0, ©_location(&up, Some(fp)), None); + list.ResourceBarrier(&[super::super::transition(&tex, D3D12_RESOURCE_STATE_COPY_DEST, after)]); + (tex, up) + } + + /// `list` closed, run on `queue` and waited for. + unsafe fn run(dev: &ID3D12Device, queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) { + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 30_000).unwrap(); + } + + /// The `w`x`h` RGBA8 texels of a readback (`readback_copy`) that ran. + unsafe fn texels(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, w: u32, h: u32) -> Vec { + let mut out = vec![0u8; (w * h * 4) as usize]; + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..h as usize { + let row = &mut out[y * w as usize * 4..][..w as usize * 4]; + std::ptr::copy_nonoverlapping((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row.as_mut_ptr(), row.len()); + } + rb.Unmap(0, None); + out + } + + /// `src` (sw x sh RGBA8) through the scaler into all of a dw x dh target, read back as RGBA8. + unsafe fn downscale(dev: &ID3D12Device, scaler: &Scaler, src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec { + draw(dev, scaler, src, sw, sh, dw, dh, Area { x: 0, y: 0, w: dw, h: dh }) + } + + /// `src` (sw x sh RGBA8) through the scaler into `area` of a dw x dh target, read back as RGBA8. + #[allow(clippy::too_many_arguments)] + pub(in crate::hle::d3d12x) unsafe fn draw(dev: &ID3D12Device, scaler: &Scaler, src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32, area: Area) -> Vec { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let (tex, _up) = upload(dev, &list, src, sw, sh, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + let rt = texture(dev, dw, dh, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + scaler.record(dev, &list, &tex, &rt, area); + list.ResourceBarrier(&[super::super::transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = super::super::readback_copy(&list, &rt, &rt.GetDesc()).unwrap(); + run(dev, &queue, &list); + texels(&rb, &fp, dw, dh) + } + + /// `got` (dw pixels a row, RGBA8) is the CPU area filter's `want` within 1.5 of 255. + fn check(got: &[u8], want: &[[f64; 3]], dw: usize, what: &str) { + let mut worst = (0.0f64, 0usize); + for (i, w) in want.iter().enumerate() { + for c in 0..3 { + let d = (got[i * 4 + c] as f64 - w[c]).abs(); + if d > worst.0 { + worst = (d, i); + } + } + } + let i = worst.1; + assert!(worst.0 <= 1.5, "{what}: pixel ({}, {}) is {:?}, the area filter gives {:?}", i % dw, i / dw, &got[i * 4..i * 4 + 3], want[i]); + } + + /// A device on the GPU, else on WARP. + fn device() -> Option { + let mut dev: Option = None; + unsafe { + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()).ok()?; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + } + } + dev + } + + /// 3840x2160 → 1280x720 (3x) and 1920x1080 → 1280x720 (1.5x) match the CPU area filter. + #[test] + fn downscale_matches_a_cpu_area_filter() { + unsafe { + let Some(dev) = device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let scaler = Scaler::new(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + for (sw, sh) in [(3840u32, 2160u32), (1920, 1080)] { + let (dw, dh) = (1280u32, 720u32); + let src = pattern(sw as usize, sh as usize); + let got = downscale(&dev, &scaler, &src, sw, sh, dw, dh); + let want = reference(&src, sw as usize, sh as usize, dw as usize, dh as usize); + check(&got, &want, dw as usize, &format!("{sw}x{sh} → {dw}x{dh}")); + } + } + } + + /// A hidden popup window (no frame: the client area is the whole window) on a thread of its + /// own that pumps its messages, as the XCL window is. + struct TestWindow { + hwnd: HWND, + thread: Option>, + } + + unsafe extern "system" fn test_wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if msg == WM_DESTROY { + PostQuitMessage(0); + return LRESULT(0); + } + DefWindowProcW(hwnd, msg, wp, lp) + } + + impl TestWindow { + fn new() -> TestWindow { + let (tx, rx) = std::sync::mpsc::channel(); + let thread = std::thread::spawn(move || unsafe { + let inst = GetModuleHandleW(PCWSTR::null()).unwrap(); + let class = w!("XCLPresentTestWindow"); + let wc = WNDCLASSW { + lpfnWndProc: Some(test_wndproc), + hInstance: inst.into(), + lpszClassName: class, + ..Default::default() + }; + RegisterClassW(&wc); + let hwnd = CreateWindowExW(WINDOW_EX_STYLE(0), class, w!("XCL present test"), WS_POPUP, 0, 0, 1280, 720, None, None, Some(inst.into()), None).unwrap(); + tx.send(hwnd.0 as isize).unwrap(); + let mut msg = MSG::default(); + while GetMessageW(&mut msg, None, 0, 0).as_bool() { + DispatchMessageW(&msg); + } + }); + TestWindow { + hwnd: HWND(rx.recv().unwrap() as *mut std::ffi::c_void), + thread: Some(thread), + } + } + + /// The client area made `w`x`h` (0x0: as when minimized). + unsafe fn resize(&self, w: u32, h: u32) { + SetWindowPos(self.hwnd, None, 0, 0, w as i32, h as i32, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE).unwrap(); + assert_eq!(super::super::client_size(self.hwnd), (w, h)); + } + } + + impl Drop for TestWindow { + fn drop(&mut self) { + unsafe { + let _ = PostMessageW(Some(self.hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } + } + + /// The swap chain follows the window while a title presents: 1280x720, larger (1920x1080), + /// smaller (800x450) – each frame shown at the client size, the filter drawing into the new + /// size as the CPU filter does; minimized (0x0): nothing shown and no resize; restored: shown + /// again. On an adopted device, as the title's is (its CreateRenderTargetView hook is in the + /// path). + #[test] + fn swap_chain_follows_the_window() { + use crate::hle::d3d12x::real; + unsafe { + let Some(dev) = device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + real::adopt(dev.as_raw(), real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + // inside a present, as `present_now` runs it: these submissions are not the title's frames + super::super::IN_PRESENT.with(|c| c.set(true)); + // the title's 3840x2160 image, in COMMON as PresentX hands it over + let (iw, ih) = (3840u32, 2160u32); + let pixels = pattern(iw as usize, ih as usize); + let (image, _up) = upload(&dev, &list, &pixels, iw, ih, D3D12_RESOURCE_STATE_COMMON); + run(&dev, &queue, &list); + let desc = image.GetDesc(); + let window = TestWindow::new(); + let mut p = super::super::presenter_for(&dev, queue.as_raw() as usize).expect("presenter"); + for (k, (w, h)) in [(1280u32, 720u32), (1920, 1080), (800, 450), (0, 0), (1280, 720)].into_iter().enumerate() { + window.resize(w, h); + let before = (p.w, p.h); + let shown = super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc); + if w == 0 { + assert!(!shown, "minimized: nothing is shown"); + assert_eq!((p.w, p.h), before, "minimized: the swap chain keeps its size"); + continue; + } + assert!(shown, "{w}x{h}: the frame is shown"); + let sc = p.sc.clone().unwrap(); + let d = sc.GetDesc1().unwrap(); + assert_eq!((p.w, p.h, d.Width, d.Height), (w, h, w, h), "the swap chain follows the {w}x{h} client area"); + assert_eq!(p.route, Some((Route::Filter, (iw, ih)))); + if k > 2 { + continue; // a size checked already + } + // the filter into the new back buffer, read back + crate::gpu::fence::wait(&p.fence, p.value, &dev, None, 30_000).unwrap(); + let bb: ID3D12Resource = sc.GetBuffer(sc.GetCurrentBackBufferIndex()).unwrap(); + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + p.scaler.as_ref().unwrap().record(&dev, &list, &image, &bb, Area { x: 0, y: 0, w, h }); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = super::super::readback_copy(&list, &bb, &bb.GetDesc()).unwrap(); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT)]); + run(&dev, &queue, &list); + drop(bb); + let want = reference(&pixels, iw as usize, ih as usize, w as usize, h as usize); + check(&texels(&rb, &fp, w, h), &want, w as usize, &format!("{iw}x{ih} → {w}x{h} window")); + } + // a resize DXGI refuses (a back buffer still referenced): the frame is shown anyway, + // drawn at the swap chain's size; another size is asked for at once + let held: ID3D12Resource = p.sc.as_ref().unwrap().GetBuffer(0).unwrap(); + window.resize(1920, 1080); + assert!(super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc), "a refused resize still shows the frame"); + assert_eq!((p.w, p.h), (1280, 720), "refused: the swap chain keeps its size"); + drop(held); + window.resize(800, 450); + assert!(super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc)); + assert_eq!((p.w, p.h), (800, 450), "the next size is asked for at once"); + // the last frame done before the presenter goes (the runtime waits too, `present_now`): + // its allocator, the filter's pipeline and descriptor heaps and the swap chain released + // under the GPU hung the device – the one every GPU test of the process shares + crate::gpu::fence::wait(&p.fence, p.value, &dev, None, 30_000).unwrap(); + drop(p); + super::super::IN_PRESENT.with(|c| c.set(false)); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/window_mode.rs b/crates/xcl/src/hle/d3d12x/window_mode.rs new file mode 100644 index 000000000..46d3e5600 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/window_mode.rs @@ -0,0 +1,272 @@ +//! The XCL window in borderless fullscreen and back (Alt+Enter, F11; `fullscreen` in xcl.toml +//! starts in it), and the image kept at its own aspect ratio inside the client area. +//! +//! Borderless, not exclusive: the window becomes a `WS_POPUP` covering the whole monitor it is +//! on (not its work area – the taskbar goes under it), and toggling back restores the style and +//! placement it had. DXGI's own Alt+Enter stays off (`DXGI_MWA_NO_ALT_ENTER`): no display mode +//! changes. +//! +//! When the client area's shape differs from the image's, the area filter draws into the +//! largest centred rectangle of the image's aspect (`letterbox`), the rest of the back buffer +//! black (`present/downscale.rs`). + +use std::sync::Mutex; + +use windows::Win32::Foundation::{HWND, RECT}; +use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST}; +use windows::Win32::UI::WindowsAndMessaging::*; + +const VK_RETURN: usize = 0x0D; +const VK_F11: usize = 0x7A; +/// WM_(SYS)KEYDOWN lParam: Alt is down (context code) / the key was already down (auto-repeat) +const KF_ALT: isize = 1 << 29; +const KF_REPEAT: isize = 1 << 30; + +/// What a key message does to the window mode. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Key { + /// Alt+Enter or F11 pressed: fullscreen on / off + Toggle, + /// part of the toggle (auto-repeat, the Alt+Enter character that would beep): eaten + Swallow, +} + +/// The window-mode meaning of a window message (None: not ours, it goes on as before). +pub fn key(msg: u32, wp: usize, lp: isize) -> Option { + let press = if lp & KF_REPEAT != 0 { Key::Swallow } else { Key::Toggle }; + match (msg, wp) { + (WM_SYSKEYDOWN, VK_RETURN) if lp & KF_ALT != 0 => Some(press), + (WM_KEYDOWN | WM_SYSKEYDOWN, VK_F11) => Some(press), + (WM_SYSCHAR, 0x0D) if lp & KF_ALT != 0 => Some(Key::Swallow), + _ => None, + } +} + +/// A rectangle of the back buffer, in pixels. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Area { + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, +} + +/// The largest rectangle of `image`'s aspect ratio centred in `client` (the bars around it are +/// black). A side within a pixel of the client's is the client's: no 1-pixel bar from rounding. +pub fn letterbox(image: (u32, u32), client: (u32, u32)) -> Area { + let (iw, ih, cw, ch) = (image.0 as u64, image.1 as u64, client.0 as u64, client.1 as u64); + let full = Area { x: 0, y: 0, w: client.0, h: client.1 }; + if iw == 0 || ih == 0 || cw == 0 || ch == 0 { + return full; + } + let (w, h) = if cw * ih > ch * iw { + // the client is wider: bars left and right + (((ch * iw + ih / 2) / ih).clamp(1, cw), ch) + } else { + (cw, ((cw * ih + iw / 2) / iw).clamp(1, ch)) + }; + let (w, h) = (if cw - w <= 1 { cw } else { w }, if ch - h <= 1 { ch } else { h }); + Area { x: ((cw - w) / 2) as u32, y: ((ch - h) / 2) as u32, w: w as u32, h: h as u32 } +} + +/// The window style in fullscreen: no caption, frame or borders, the rest (visible, …) kept. +pub fn fullscreen_style(style: u32) -> u32 { + (style & !WS_OVERLAPPEDWINDOW.0) | WS_POPUP.0 +} + +/// The fullscreen window's position and size (x, y, w, h): the monitor's whole rectangle. +pub fn fullscreen_rect(monitor: RECT) -> (i32, i32, i32, i32) { + (monitor.left, monitor.top, monitor.right - monitor.left, monitor.bottom - monitor.top) +} + +/// The window in fullscreen: its handle, and the style and placement to restore. +struct Saved { + hwnd: isize, + style: isize, + placement: WINDOWPLACEMENT, +} + +static SAVED: Mutex> = Mutex::new(None); + +/// `hwnd` is in borderless fullscreen. +pub fn is_fullscreen(hwnd: HWND) -> bool { + SAVED.lock().unwrap().as_ref().is_some_and(|s| s.hwnd == hwnd.0 as isize) +} + +/// Borderless fullscreen on the monitor `hwnd` is on, or back to the window it was. +/// +/// # Safety +/// `hwnd` is a top-level window of this process, called on the thread that owns it. +pub unsafe fn toggle(hwnd: HWND) { + let mut saved = SAVED.lock().unwrap(); + if let Some(s) = saved.take_if(|s| s.hwnd == hwnd.0 as isize) { + let mut placement = s.placement; + if !IsWindowVisible(hwnd).as_bool() { + placement.showCmd = SW_HIDE.0 as u32; // the toggle does not show a hidden window + } + SetWindowLongPtrW(hwnd, GWL_STYLE, s.style); + let _ = SetWindowPlacement(hwnd, &placement); + let _ = SetWindowPos(hwnd, None, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + crate::xlog_info!("XCL window: back from fullscreen"); + return; + } + let mut placement = WINDOWPLACEMENT { length: std::mem::size_of::() as u32, ..Default::default() }; + let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + if GetWindowPlacement(hwnd, &mut placement).is_err() || !GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut mi).as_bool() { + crate::xlog_warn!("XCL window: no placement or monitor – fullscreen not entered"); + return; + } + let style = GetWindowLongPtrW(hwnd, GWL_STYLE); + SetWindowLongPtrW(hwnd, GWL_STYLE, fullscreen_style(style as u32) as isize); + let (x, y, w, h) = fullscreen_rect(mi.rcMonitor); + let _ = SetWindowPos(hwnd, Some(HWND_TOP), x, y, w, h, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + *saved = Some(Saved { hwnd: hwnd.0 as isize, style, placement }); + crate::xlog_info!("XCL window: borderless fullscreen {w}x{h} at {x},{y} (Alt+Enter / F11 to leave)"); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hle::d3d12x::present::downscale::tests::{draw, pattern, reference}; + use crate::hle::d3d12x::present::downscale::Scaler; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + use windows::Win32::Graphics::Dxgi::*; + + fn area(x: u32, y: u32, w: u32, h: u32) -> Area { + Area { x, y, w, h } + } + + #[test] + fn letterbox_keeps_the_image_aspect_centred() { + let uhd = (3840, 2160); + // 16:10: bars top and bottom; 21:9 and 32:9: left and right; 4:3: top and bottom + assert_eq!(letterbox(uhd, (1920, 1200)), area(0, 60, 1920, 1080)); + assert_eq!(letterbox(uhd, (2560, 1600)), area(0, 80, 2560, 1440)); + assert_eq!(letterbox(uhd, (2560, 1080)), area(320, 0, 1920, 1080)); + assert_eq!(letterbox(uhd, (5120, 1440)), area(1280, 0, 2560, 1440)); + assert_eq!(letterbox(uhd, (1024, 768)), area(0, 96, 1024, 576)); + // the same ratio: no bars (2560x1440 fullscreen with a 4K image) + for client in [(1280, 720), (2560, 1440), (3840, 2160)] { + assert_eq!(letterbox(uhd, client), area(0, 0, client.0, client.1), "{client:?}"); + } + // odd sizes: within a pixel of the ratio fills; otherwise rounded and centred + assert_eq!(letterbox(uhd, (1366, 768)), area(0, 0, 1366, 768)); + assert_eq!(letterbox(uhd, (1281, 721)), area(0, 0, 1281, 721)); + assert_eq!(letterbox(uhd, (1000, 1001)), area(0, 219, 1000, 563)); + assert_eq!(letterbox((1920, 1080), (3001, 1000)), area(611, 0, 1778, 1000)); + // nothing to keep: the client as it is + assert_eq!(letterbox((0, 0), (800, 600)), area(0, 0, 800, 600)); + assert_eq!(letterbox(uhd, (0, 0)), area(0, 0, 0, 0)); + assert_eq!(letterbox(uhd, (1, 5000)), area(0, 2499, 1, 1)); + } + + #[test] + fn fullscreen_covers_the_monitor_without_a_frame() { + assert_eq!(fullscreen_rect(RECT { left: 0, top: 0, right: 2560, bottom: 1440 }), (0, 0, 2560, 1440)); + // a monitor left of / above the primary one + assert_eq!(fullscreen_rect(RECT { left: -1920, top: -1080, right: 0, bottom: 0 }), (-1920, -1080, 1920, 1080)); + let s = fullscreen_style((WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN).0); + assert_eq!(s, (WS_POPUP | WS_VISIBLE | WS_CLIPCHILDREN).0); + } + + #[test] + fn alt_enter_and_f11_toggle_plain_enter_does_not() { + assert_eq!(key(WM_SYSKEYDOWN, VK_RETURN, KF_ALT | 1), Some(Key::Toggle)); + assert_eq!(key(WM_KEYDOWN, VK_F11, 1), Some(Key::Toggle)); + assert_eq!(key(WM_SYSKEYDOWN, VK_F11, KF_ALT | 1), Some(Key::Toggle)); + // held down: one toggle, the repeats are eaten + assert_eq!(key(WM_SYSKEYDOWN, VK_RETURN, KF_ALT | KF_REPEAT | 1), Some(Key::Swallow)); + assert_eq!(key(WM_KEYDOWN, VK_F11, KF_REPEAT | 1), Some(Key::Swallow)); + // the character of Alt+Enter (DefWindowProc would beep) + assert_eq!(key(WM_SYSCHAR, 0x0D, KF_ALT | 1), Some(Key::Swallow)); + // plain Enter, other keys, key-ups: not ours + assert_eq!(key(WM_KEYDOWN, VK_RETURN, 1), None); + assert_eq!(key(WM_CHAR, 0x0D, 1), None); + assert_eq!(key(WM_SYSKEYDOWN, 0x73, KF_ALT | 1), None); // Alt+F4 + assert_eq!(key(WM_KEYUP, VK_F11, 1), None); + assert_eq!(key(WM_SYSKEYUP, VK_RETURN, KF_ALT | 1), None); + } + + /// A real (hidden) window: fullscreen covers its monitor without a frame, and the toggle + /// back restores its style and rectangle. + #[test] + fn toggle_enters_and_restores_a_window() { + unsafe { + let style = WS_OVERLAPPEDWINDOW; + let Ok(hwnd) = CreateWindowExW(WINDOW_EX_STYLE(0), windows::core::w!("STATIC"), windows::core::w!("xcl window_mode test"), style, 100, 100, 640, 480, None, None, None, None) else { + crate::gpu::recomp::runner::skip_test("no desktop to create a window on"); + return; + }; + let rect = |h| { + let mut r = RECT::default(); + GetWindowRect(h, &mut r).unwrap(); + r + }; + let before = rect(hwnd); + let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + assert!(GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut mi).as_bool()); + + toggle(hwnd); + assert!(is_fullscreen(hwnd)); + let s = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; + assert!(s & WS_POPUP.0 != 0 && s & (WS_CAPTION.0 | WS_THICKFRAME.0) == 0, "style {s:#x}"); + assert_eq!(rect(hwnd), mi.rcMonitor); + assert!(!IsWindowVisible(hwnd).as_bool(), "the toggle shows no hidden window"); + + toggle(hwnd); + assert!(!is_fullscreen(hwnd)); + assert_eq!(GetWindowLongPtrW(hwnd, GWL_STYLE) as u32 & style.0, style.0); + assert_eq!(rect(hwnd), before); + assert!(!IsWindowVisible(hwnd).as_bool()); + let _ = DestroyWindow(hwnd); + } + } + + /// The area filter into the centred rectangle of a client of another shape: the bars are + /// opaque black (cleared – a new target is all zeros, alpha too), the image area is the area + /// filter of the whole image into that rectangle. + #[test] + fn letterboxed_draw_has_black_bars_and_the_filtered_image() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.is_err() || D3D12CreateDevice(&warp.unwrap(), D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let scaler = Scaler::new(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let (sw, sh) = (384u32, 216u32); + let src = pattern(sw as usize, sh as usize); + // a taller client (bars top and bottom) and a wider one (left and right, odd offset) + for (cw, ch, want) in [(256u32, 200u32, area(0, 28, 256, 144)), (320, 120, area(53, 0, 213, 120))] { + let a = letterbox((sw, sh), (cw, ch)); + assert_eq!(a, want); + let got = draw(&dev, &scaler, &src, sw, sh, cw, ch, a); + let filtered = reference(&src, sw as usize, sh as usize, a.w as usize, a.h as usize); + for y in 0..ch { + for x in 0..cw { + let px = &got[((y * cw + x) * 4) as usize..][..4]; + let inside = (a.x..a.x + a.w).contains(&x) && (a.y..a.y + a.h).contains(&y); + if !inside { + assert_eq!(px, [0, 0, 0, 255], "{cw}x{ch}: bar pixel ({x}, {y})"); + continue; + } + let w = filtered[((y - a.y) * a.w + (x - a.x)) as usize]; + for c in 0..3 { + assert!((px[c] as f64 - w[c]).abs() <= 1.5, "{cw}x{ch}: pixel ({x}, {y}) is {px:?}, the area filter gives {w:?}"); + } + } + } + } + } + } +} diff --git a/crates/xcl/src/hle/kbm.rs b/crates/xcl/src/hle/kbm.rs index 6d18b1cfb..fa224db1f 100644 --- a/crates/xcl/src/hle/kbm.rs +++ b/crates/xcl/src/hle/kbm.rs @@ -15,6 +15,8 @@ //! | Space, Enter / Escape, Backspace | A / B | //! | arrows / Tab / P | D-pad / View / Menu | //! +//! Alt+Enter is not A: it toggles borderless fullscreen (`d3d12x::window_mode`), as F11 does. +//! //! The mouse is read with Raw Input on the XCL window (movement in mouse counts, not the //! cursor); its speed becomes a stick deflection – the stick turns the camera at a rate, //! so a mouse moving at a given speed turns it at a matching one (`mouse_sensitivity`). @@ -24,7 +26,7 @@ use std::sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering}; use std::sync::Mutex; use std::time::Instant; -use super::gameinput::{GamepadState, LEFT_SHOULDER, LEFT_STICK, RIGHT_SHOULDER, RIGHT_STICK, X, Y}; +use super::gameinput::{GamepadState, A, LEFT_SHOULDER, LEFT_STICK, RIGHT_SHOULDER, RIGHT_STICK, X, Y}; // --------------------------------------------------------------------------------------- // the mapping (pure, tested) @@ -120,6 +122,15 @@ impl Wheel { } } +/// Enter pressed with Alt is the fullscreen toggle, not the gamepad's A: Enter's A +/// (`gameinput::keyboard`) is taken out of `buttons` while Alt is held with it, and until Enter +/// is released (Alt let go first). Space still presses A. Returns the buttons and whether Enter +/// stays taken out (`held`, for the next call). +pub fn without_alt_enter(buttons: u32, enter: bool, alt: bool, space: bool, held: bool) -> (u32, bool) { + let held = enter && (alt || held); + (if held && !space { buttons & !A } else { buttons }, held) +} + // --------------------------------------------------------------------------------------- // input from the PC // --------------------------------------------------------------------------------------- @@ -212,6 +223,8 @@ static CAPTURED: AtomicBool = AtomicBool::new(false); /// the user is dragging or resizing the window (WM_ENTERSIZEMOVE … WM_EXITSIZEMOVE): /// the cursor must stay free, or the 1-pixel clip teleports it back mid-drag static SIZING: AtomicBool = AtomicBool::new(false); +/// Enter went down with Alt (the fullscreen toggle) and is still held: it is not A +static ALT_ENTER: AtomicBool = AtomicBool::new(false); /// mouse counts not yet taken by `apply` static DX: AtomicI32 = AtomicI32::new(0); static DY: AtomicI32 = AtomicI32::new(0); @@ -410,7 +423,10 @@ pub fn apply(s: &mut GamepadState) { s.left_x = lx; s.left_y = ly; } - // (Space / Enter, Escape / Backspace, arrows, Tab, P: `gameinput::keyboard`) + // (Space / Enter, Escape / Backspace, arrows, Tab, P: `gameinput::keyboard`), but not Alt+Enter + let (buttons, held) = without_alt_enter(s.buttons, key(0x0D), key(0x12), key(0x20), ALT_ENTER.load(Ordering::Relaxed)); + s.buttons = buttons; + ALT_ENTER.store(held, Ordering::Relaxed); const VK_KEYS: [(i32, u32); 3] = [ (0xA0, LEFT_STICK), // Left Shift (0xA2, RIGHT_STICK), // Left Ctrl @@ -461,6 +477,22 @@ mod tests { assert_eq!(stick_from_keys(true, true, true, true), (0.0, 0.0)); } + #[test] + fn alt_enter_is_not_a() { + let pad = A | X; + // plain Enter (or a real pad's A): A + assert_eq!(without_alt_enter(pad, true, false, false, false), (pad, false)); + // Alt+Enter: no A, and none either once Alt is let go while Enter is still down + assert_eq!(without_alt_enter(pad, true, true, false, false), (X, true)); + assert_eq!(without_alt_enter(pad, true, false, false, true), (X, true)); + // Enter released: A again on the next press + assert_eq!(without_alt_enter(0, false, false, false, true), (0, false)); + assert_eq!(without_alt_enter(pad, true, false, false, false), (pad, false)); + // Alt alone takes nothing; Space with Alt+Enter still presses A + assert_eq!(without_alt_enter(pad, false, true, false, false), (pad, false)); + assert_eq!(without_alt_enter(pad, true, true, true, false), (pad, true)); + } + #[test] fn mouse_speed_becomes_a_deflection() { // resting