Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ 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.
- **Window:** the game's image keeps its aspect ratio in a window of another shape (black bars; an
image that fits 1:1 is copied texel for texel). `scaling` in the game's `xcl.toml`: `"fit"`,
`"integer"` (whole multiples only), `"stretch"` (the old behaviour); `XCL_SCALING` overrides it.

## Building and usage

Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ 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,
/// How the game's image fills the window: "fit" (aspect ratio kept, black bars – a 16:9
/// image in a 21:9 window), "integer" (whole multiples only, 1:1 pixels) or "stretch".
/// `XCL_SCALING` overrides.
pub scaling: String,
/// 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
Expand Down Expand Up @@ -184,6 +188,7 @@ impl Default for Config {
window_width: 1280,
window_height: 720,
window_pos: "auto".into(),
scaling: "fit".into(),
xbox_live_tokens: false,
keyboard_mouse: true,
mouse_sensitivity: 1.0,
Expand Down
214 changes: 183 additions & 31 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ use windows::Win32::UI::WindowsAndMessaging::*;
use crate::gpu::fence::{self, FenceError};
use crate::stubs::StubInfo;

mod downscale;
use downscale::Route;

static RTVS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
static LISTS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
static CANDIDATE: Mutex<Option<(usize, usize)>> = Mutex::new(None); // (queue, resource) – resource AddRef'd
Expand Down Expand Up @@ -530,6 +533,14 @@ struct Presenter {
fence: ID3D12Fence,
copy_source: Option<ID3D12Resource>,
dumps: Vec<FrameDump>,
/// the area filter for a window smaller than the image (`downscale`); failed: copy only
scaler: Option<downscale::Scaler>,
scaler_failed: bool,
/// the route last logged, with the image size
route: Option<(Route, (u32, u32), (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,
Expand Down Expand Up @@ -566,31 +577,53 @@ unsafe fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after:
unsafe fn new_presenter(queue: usize) -> Option<Presenter> {
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<Presenter> {
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()?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
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::<IDXGIFactory2>(DXGI_CREATE_FACTORY_FLAGS(0)) else { return false };
let qraw = p.queue as *mut c_void;
Expand Down Expand Up @@ -668,36 +701,82 @@ 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 scaling = scaling();
let mut route = downscale::route(image, client, scaling);
if matches!(route, Route::Filter | Route::Place) && !scaler_ready(p, fmt) {
route = Route::Copy;
}
let mut rect = downscale::place(image, client, scaling);
if p.route != Some((route, image, client)) {
let how = match route {
Route::Filter => "area filter into a swap chain of the client size",
Route::Place => "copied 1:1 into a swap chain of the client size",
Route::Copy if client == image => "copy",
Route::Copy => "copy, the window stretches it",
Route::Skip => "nothing shown, the swap chain keeps its size",
};
let at = if matches!(route, Route::Filter | Route::Place) && (rect.2, rect.3) != client {
format!(" at {}x{}+{}+{} ({scaling:?}, black bars around it)", rect.2, rect.3, rect.0, rect.1)
} else {
String::new()
};
crate::xlog_info!("present: {}x{} image in a {}x{} client area – {how}{at}", image.0, image.1, client.0, client.1);
p.route = Some((route, image, client));
}
if route == Route::Skip {
return false;
}
let (sw, sh) = if route == Route::Copy { image } else { client };
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 = Route::Filter;
rect = downscale::place(image, (p.w, p.h), scaling);
}
let Some(sc) = p.sc.clone() else { return };
let Ok(bb) = sc.GetBuffer::<ID3D12Resource>(sc.GetCurrentBackBufferIndex()) else { return };
let full = (rect.0, rect.1, rect.2, rect.3) == (0, 0, p.w, p.h);
let Some(sc) = p.sc.clone() else { return false };
let Ok(bb) = sc.GetBuffer::<ID3D12Resource>(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 = draw(&p.dev, &p.list, p.scaler.as_ref(), route, &src, &bb, D3D12_RESOURCE_STATE_PRESENT, rect, full);
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() });
}
}
Expand All @@ -724,14 +803,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::<ID3D12CommandList>() 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::<ID3D12CommandList>() else { return false };
q.ExecuteCommandLists(&[Some(cl)]);
p.copy_source = Some(src);
p.dumps = dumps;
Expand All @@ -741,13 +820,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() {
Expand All @@ -761,15 +840,83 @@ 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
}

/// `scaling` (`XCL_SCALING` overrides): how the image fills the window; "fit" when unknown.
fn scaling() -> downscale::Scaling {
static S: std::sync::OnceLock<downscale::Scaling> = std::sync::OnceLock::new();
*S.get_or_init(|| {
let env = std::env::var("XCL_SCALING").ok();
let v = env.as_deref().unwrap_or(&crate::state::config().scaling);
downscale::Scaling::parse(v).unwrap_or_else(|| {
crate::xlog_warn!("scaling: expected \"fit\", \"integer\" or \"stretch\", got {v:?} – using fit");
downscale::Scaling::Fit
})
})
}

/// Record on `list` how `src` (the title's image) goes into `bb` (a back buffer in state
/// `from`) for `route` at `rect` (`full`: `rect` covers all of `bb`). Returns `bb`'s state after.
#[allow(clippy::too_many_arguments)]
unsafe fn draw(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, scaler: Option<&downscale::Scaler>, route: Route, src: &ID3D12Resource, bb: &ID3D12Resource, from: D3D12_RESOURCE_STATES, rect: (u32, u32, u32, u32), full: bool) -> D3D12_RESOURCE_STATES {
match (route, scaler) {
(Route::Filter, Some(scaler)) => {
list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_RENDER_TARGET)]);
// the title's image is promoted from COMMON to a shader resource, as for the copy
scaler.record_into(dev, list, src, bb, rect, !full);
D3D12_RESOURCE_STATE_RENDER_TARGET
}
(Route::Place, Some(scaler)) => {
// black bars, then the image copied texel for texel between them
list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_RENDER_TARGET)]);
scaler.clear(dev, list, bb);
list.ResourceBarrier(&[transition(bb, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_DEST)]);
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(bb), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
let image = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
list.CopyTextureRegion(&dst, rect.0, rect.1, 0, &image, None);
D3D12_RESOURCE_STATE_COPY_DEST
}
_ => {
list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_COPY_DEST)]);
list.CopyResource(bb, src);
D3D12_RESOURCE_STATE_COPY_DEST
}
}
}

/// 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`,
Expand Down Expand Up @@ -993,6 +1140,11 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI
impl Drop for Presenter {
fn drop(&mut self) {
unsafe {
// the last present's list may still run: it uses the swap chain's buffers, the
// scaler's descriptors and the title's image, all released with the presenter
if !self.disabled {
let _ = fence::wait(&self.fence, self.value, &self.dev, Some(self.event), 2000);
}
let _ = CloseHandle(self.event);
}
}
Expand Down
Loading
Loading