#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Condvar, Mutex}; use std::thread::ThreadId; use eonacat_xsbox_gpu::formats::texture::{ self, Dimension, Error, Layout, Swizzle, Texture, TextureDesc, layout_swizzle, }; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::hle::{HleModule}; use crate::hle_export; const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; const S_FALSE: HRESULT = 1; #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct ResourceDesc { pub dimension: u32, pub alignment: u64, pub width: u64, pub height: u32, pub depth_or_array: u16, pub mips: u16, pub format: u32, pub samples: u32, pub quality: u32, pub layout: u32, pub flags: u32, } const _: () = assert!(size_of::() == 0x38); const SWIZZLED: u32 = 0x100; const TEXTURE_1D: u32 = 2; const TEXTURE_2D: u32 = 3; const TEXTURE_3D: u32 = 4; const NO_MODE: u32 = 0xffff_ffff; fn dimension(kind: u32) -> Option { match kind { TEXTURE_1D => Some(Dimension::Tex1d), TEXTURE_2D => Some(Dimension::Tex2d), TEXTURE_3D => Some(Dimension::Tex3d), _ => None, } } pub extern "system" fn XGSuggestSwizzleMode( desc: *const ResourceDesc, flags: u32, out: *mut u32, ) -> HRESULT { let (Some(desc), Some(out)) = (unsafe { (desc.as_ref(), out.as_mut()) }) else { return E_INVALIDARG; }; let Some(dim) = dimension(desc.dimension) else { return E_INVALIDARG; }; let layout = match desc.layout { l @ (texture::LAYOUT_64KB_UNDEFINED | texture::LAYOUT_64KB_STANDARD) => l, _ => 0, }; if flags != 0 { tracing::debug!(flags, "swizzle mode suggestion flags not looked at"); } match layout_swizzle(dim, layout, desc.flags) { Some(mode) => { *out = SWIZZLED | mode.0; tracing::debug!( width = desc.width, height = desc.height, depth_or_array = desc.depth_or_array, mips = desc.mips, format = desc.format, dimension = desc.dimension, flags = format_args!("{:#x}", desc.flags), asked = format_args!("{flags:#x}"), layout = format_args!("{:#x}", *out), "suggested swizzle mode" ); S_OK } None => { tracing::warn!(?desc, "no 64 KiB tiled mode for this description"); E_NOTIMPL } } } #[repr(C)] pub struct Computer { vtable: &'static Vtable, refs: AtomicU32, desc: ResourceDesc, mips: u32, texture: Texture, tiled: bool, } type This = *mut Computer; fn computer<'a>(this: This) -> &'a Computer { unsafe { &*this } } pub extern "system" fn XGCreateTextureComputer( desc: *const ResourceDesc, out: *mut This, ) -> HRESULT { let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else { return E_INVALIDARG; }; let tiled = desc.layout == texture::LAYOUT_64KB_UNDEFINED; create(desc, tiled, out) } fn create(desc: ResourceDesc, tiled: bool, out: *mut This) -> HRESULT { let _lock = Exclusive::hold(); initialize(); let Some(texture) = texture(&desc) else { tracing::warn!(?desc, "no texture layout"); return E_INVALIDARG; }; tracing::debug!( width = desc.width, height = desc.height, format = desc.format, layout = format_args!("{:#x}", desc.layout), size = texture.size, "texture computer" ); let mips = texture.planes[0].layout.mips.len() as u32; let computer = Box::new(Computer { vtable: &VTABLE, refs: AtomicU32::new(1), desc, mips, texture, tiled, }); unsafe { out.write(Box::into_raw(computer)) }; S_OK } fn texture(desc: &ResourceDesc) -> Option { let dimension = dimension(desc.dimension)?; let swizzle = layout_swizzle(dimension, desc.layout, desc.flags)?; if !mode_allowed(desc, dimension, swizzle) { return None; } let mut texture = Texture::new(&TextureDesc { dimension, width: u32::try_from(desc.width).ok()?, height: desc.height, depth_or_array: u32::from(desc.depth_or_array), mips: u32::from(desc.mips), format: desc.format, samples: desc.samples.max(1), swizzle, }) .ok()?; for plane in &mut texture.planes { plane.layout.configure_xor(crate::hle::console::current().pipes()); } (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) } const MIPS: usize = 15; fn mode_allowed(desc: &ResourceDesc, dimension: Dimension, swizzle: Swizzle) -> bool { let depth = desc.flags & texture::ALLOW_DEPTH_STENCIL != 0 && dimension == Dimension::Tex2d; let wide = eonacat_xsbox_gpu::formats::texture::format(desc.format).is_some_and(|f| f.bytes > 8 || f.block != 1); let z = swizzle == Swizzle::SW_64KB_Z_X; swizzle != Swizzle::SW_4KB_R_X && (!depth || z) && !(z && wide) } #[repr(C)] #[derive(Debug, Default, Clone, Copy)] pub struct MipOut { pub size: u64, pub offset: u64, pub slice_size: u64, pub pitch_texels: u32, pub pitch_bytes: u32, pub alignment: u32, pub padded: [u32; 3], pub elements: [u32; 2], pub texels: [u32; 2], pub depth_or_array: u32, pub samples: u32, pub swizzle: u32, pub bank_rotation: [u64; 2], pub slice_depth: u32, pub in_tail: u32, pub tail_position: u32, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct PlaneOut { pub usage: u32, pub size: u64, pub slice_size: u64, pub offset: u64, pub alignment: u64, pub element_bytes: u32, pub standard_mips: u32, pub tail_mips: u32, pub mips: [MipOut; MIPS], } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct LayoutOut { pub size: u64, pub alignment: u64, pub mips: u32, pub planes: u32, pub plane: [PlaneOut; 4], pub dimension: u32, } const _: () = assert!(size_of::() == 0x70); const _: () = assert!(size_of::() == 0x6c8); const _: () = assert!(size_of::() == 0x1b40); fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut { let m = &l.mips[i]; let bpe = u64::from(l.desc.element_bytes); let block = l.desc.block; let three_d = desc.dimension == TEXTURE_3D; let array = u32::from(desc.depth_or_array).max(1); let mut out = MipOut { pitch_texels: m.pitch * block, pitch_bytes: m.pitch * l.desc.element_bytes, padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }], elements: [m.width, m.height], texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)], depth_or_array: if three_d { m.depth } else { array }, samples: l.desc.samples, slice_depth: l.block[2], swizzle: l.desc.swizzle.0, ..MipOut::default() }; let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe; let depth = u64::from(if three_d { m.depth_pitch } else { 1 }); match m.tail { None => { out.offset = m.offset; out.slice_size = slice * u64::from(l.desc.samples); out.size = out.slice_size * depth; out.alignment = l.alignment as u32; } Some(t) => { out.in_tail = 1; out.alignment = 256; if l.thick { out.slice_size = l.alignment / u64::from(l.block[2]); out.tail_position = t.x | t.y << 11; } else { out.offset = u64::from(t.offset); out.slice_size = slice; } out.size = out.slice_size * depth; } } out } extern "system" fn add_ref(this: This) -> u32 { computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1 } extern "system" fn release(this: This) -> u32 { let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; if left == 0 { drop(unsafe { Box::from_raw(this) }); } left } extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { if out.is_null() { return E_INVALIDARG; } let c = computer(this); let out = unsafe { out.write_bytes(0, 1); &mut *out }; out.size = c.texture.size; out.alignment = c.texture.alignment; out.mips = c.mips; out.planes = c.texture.planes.len() as u32; out.dimension = c.desc.dimension; let depth = c.desc.flags & texture::ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1); for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) { let l = &p.layout; plane.usage = match (p.stencil, depth) { (true, _) => 8, (false, true) => 7, (false, false) => 1, }; plane.size = l.size; plane.slice_size = l.slice_size; plane.offset = p.offset; plane.alignment = l.alignment; plane.element_bytes = l.desc.element_bytes; plane.standard_mips = l.first_tail_mip; plane.tail_mips = c.mips - l.first_tail_mip; for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() { *mip = mip_out(&c.desc, l, i); } } S_OK } struct CopyArgs<'a> { layout: &'a Layout, mip: u32, slice: u32, tiled: usize, linear: usize, } fn copy_args( c: &Computer, plane: u32, subresource: u32, row: u32, depth: u32, ) -> Option> { let p = c.texture.planes.get(plane as usize)?; let l = &p.layout; let (mip, slice) = (subresource % c.mips, subresource / c.mips); let m = l.mips.get(mip as usize)?; let bytes = m.width as usize * l.desc.element_bytes as usize; let depths = l.subresource_depth(mip) as usize; let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; Some(CopyArgs { layout: l, mip, slice, tiled: (p.offset + l.size) as usize, linear, }) } fn result(r: Result<(), Error>) -> HRESULT { match r { Ok(()) => S_OK, Err(Error::Unsupported) => E_NOTIMPL, Err(_) => E_INVALIDARG, } } extern "system" fn copy_into( this: This, tiled: *mut u8, plane: u32, subresource: u32, linear: *const u8, row: u32, depth: u32, ) -> HRESULT { let c = computer(this); let Some(a) = copy_args(c, plane, subresource, row, depth) else { return E_INVALIDARG; }; if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } let offset = c.texture.planes[plane as usize].offset as usize; let (tiled, linear) = unsafe { ( std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), std::slice::from_raw_parts(linear, a.linear), ) }; let r = a .layout .tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); if r.is_err() { tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed"); } result(r) } #[allow(clippy::too_many_arguments)] extern "system" fn copy_from( this: This, linear: *mut u8, plane: u32, subresource: u32, _sample: u32, tiled: *const u8, row: u32, depth: u32, ) -> HRESULT { let c = computer(this); let Some(a) = copy_args(c, plane, subresource, row, depth) else { return E_INVALIDARG; }; if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } let offset = c.texture.planes[plane as usize].offset as usize; let (tiled, linear) = unsafe { ( std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), std::slice::from_raw_parts_mut(linear, a.linear), ) }; let r = a .layout .detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); if r.is_err() { tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed"); } result(r) } #[repr(C)] pub struct PackedMips { pub standard: u8, pub packed: u8, pub tiles: u32, pub start: u32, } #[repr(C)] pub struct SubresourceTiling { pub width: u32, pub height: u16, pub depth: u16, pub start: u32, } const TILE: u64 = 64 << 10; extern "system" fn tiling( this: This, tiles: *mut u32, packed: *mut PackedMips, shape: *mut [u32; 3], count: *mut u32, first: u32, out: *mut SubresourceTiling, ) -> HRESULT { let c = computer(this); let l = &c.texture.planes[0].layout; if l.alignment != TILE { return E_FAIL; } if l.thick { return E_NOTIMPL; } let standard = l.first_tail_mip; let tail = standard < c.mips; let tail_tiles = match standard { 0 => l.slice_size / TILE, s if s < c.mips => l.mips[s as usize - 1].offset / TILE, _ => 0, }; let block = l.desc.block; unsafe { if let Some(t) = tiles.as_mut() { *t = (l.size / TILE) as u32; } if let Some(p) = packed.as_mut() { *p = PackedMips { standard: standard as u8, packed: (c.mips - standard) as u8, tiles: tail_tiles as u32, start: 0, }; } if let Some(s) = shape.as_mut() { *s = [l.block[0] * block, l.block[1] * block, l.block[2]]; } if let Some(n) = count.as_mut() { let slices = if tail { l.slices.min(2) } else { l.slices }; let wanted = (standard * slices).saturating_sub(first).min(*n); for i in 0..wanted { let (slice, mip) = ((first + i) / standard, (first + i) % standard); let m = &l.mips[mip as usize]; let entry = if tail && slice > 0 { SubresourceTiling { width: 0, height: 0, depth: 0, start: 0, } } else { SubresourceTiling { width: m.pitch / l.block[0], height: (m.rows / l.block[1]) as u16, depth: 1, start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, } }; out.add(i as usize).write(entry); } *n = wanted; } } S_OK } extern "system" fn element_offset( this: This, plane: u32, mip: u32, x: u64, y: u32, z: u32, _sample: u32, bit: *mut u32, ) -> u64 { if !bit.is_null() { unsafe { bit.write(0) }; } let Some(p) = computer(this).texture.planes.get(plane as usize) else { return 0; }; let x = u32::try_from(x).unwrap_or(u32::MAX); match p.layout.offset(mip, x, y, z) { Ok(at) => p.offset + at, Err(e) => { tracing::warn!(?e, mip, x, y, z, "texel outside its texture"); 0 } } } #[allow(clippy::too_many_arguments)] extern "system" fn texel_coordinate( this: This, offset: u64, plane: *mut u32, mip: *mut u32, x: *mut u64, y: *mut u32, z: *mut u32, sample: *mut u32, ) -> HRESULT { let planes = &computer(this).texture.planes; let Some((index, p)) = planes .iter() .enumerate() .find(|(_, p)| (p.offset..p.offset + p.layout.size).contains(&offset)) else { return E_INVALIDARG; }; if !p.layout.addressable() { return E_NOTIMPL; } let Some((m, ex, ey, ez)) = p.layout.coordinate(offset - p.offset) else { return E_INVALIDARG; }; unsafe { for (out, value) in [(plane, index as u32), (mip, m), (y, ey), (z, ez), (sample, 0)] { if !out.is_null() { out.write(value); } } if !x.is_null() { x.write(u64::from(ex)); } } S_OK } extern "system" fn view_descriptor(this: This, plane: u32, out: *mut [u32; 8]) -> HRESULT { if !out.is_null() { unsafe { out.write([0; 8]) }; } static SAID: std::sync::Once = std::sync::Once::new(); SAID.call_once(|| { tracing::warn!( desc = ?computer(this).desc, plane, "XG: a texture view descriptor was asked for; refused (views are made through the device here)" ); }); E_INVALIDARG } #[repr(C)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct SwizzlePatternInfo { pub equation: u32, pub block: [u32; 3], } extern "system" fn swizzle_pattern(this: This, plane: u32, out: *mut SwizzlePatternInfo) -> HRESULT { const NO_EQUATION: u32 = u32::MAX; let Some(p) = computer(this).texture.planes.get(plane as usize) else { return E_INVALIDARG; }; if out.is_null() { return E_INVALIDARG; } let l = &p.layout; let swizzle = l.desc.swizzle; let info = SwizzlePatternInfo { equation: if swizzle == Swizzle::LINEAR { NO_EQUATION } else { swizzle.0 }, block: [l.block[0], l.block[1], if l.thick { l.block[2] } else { 1 }], }; unsafe { out.write(info) }; S_OK } extern "system" fn size_bytes(this: This) -> u64 { computer(this).texture.size } extern "system" fn alignment_bytes(this: This) -> u64 { computer(this).texture.alignment } extern "system" fn mip_offset(this: This, plane: u32, mip: u32) -> u64 { let Some(p) = computer(this).texture.planes.get(plane as usize) else { return 0; }; match p.layout.offset(mip, 0, 0, 0) { Ok(at) => p.offset + at, Err(e) => { tracing::warn!(?e, plane, mip, "mip outside its texture"); 0 } } } extern "system" fn is_tiled(this: This) -> bool { computer(this).tiled } static INITIALIZED: AtomicBool = AtomicBool::new(false); fn initialize() -> bool { !INITIALIZED.swap(true, Ordering::AcqRel) } pub extern "system" fn XGInitializeLibrary() -> HRESULT { if initialize() { S_OK } else { S_FALSE } } pub extern "system" fn XGTerminateLibrary() -> HRESULT { if INITIALIZED.swap(false, Ordering::AcqRel) { S_OK } else { S_FALSE } } const SCARLETT: u32 = 4; static HARDWARE_VERSION: AtomicU32 = AtomicU32::new(SCARLETT); pub extern "system" fn XGSetHardwareVersion(version: u32) { initialize(); HARDWARE_VERSION.store(version, Ordering::Relaxed); if version < SCARLETT { tracing::error!(version, "XG: Xbox One layouts are not modelled; Series layouts are computed"); } } struct Exclusive { owner: Mutex<(Option, u32)>, free: Condvar, } static LOCKING: AtomicBool = AtomicBool::new(false); static EXCLUSIVE: Exclusive = Exclusive { owner: Mutex::new((None, 0)), free: Condvar::new(), }; impl Exclusive { fn enter(&self) { let me = std::thread::current().id(); let mut owner = self.owner.lock().unwrap_or_else(|e| e.into_inner()); loop { match owner.0 { None => { *owner = (Some(me), 1); return; } Some(o) if o == me => { owner.1 += 1; return; } Some(_) => owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner()), } } } fn leave(&self) { let me = std::thread::current().id(); let mut owner = self.owner.lock().unwrap_or_else(|e| e.into_inner()); if owner.0 == Some(me) { owner.1 -= 1; if owner.1 == 0 { owner.0 = None; self.free.notify_one(); } } } fn hold() -> Option { LOCKING.load(Ordering::Acquire).then(|| { EXCLUSIVE.enter(); ExclusiveGuard }) } } struct ExclusiveGuard; impl Drop for ExclusiveGuard { fn drop(&mut self) { EXCLUSIVE.leave(); } } pub extern "system" fn XGEnableExclusiveLocking(enabled: i32) { LOCKING.store(enabled != 0, Ordering::Release); } pub extern "system" fn XGEnterExclusiveLock() -> i32 { if !LOCKING.load(Ordering::Acquire) { return 0; } EXCLUSIVE.enter(); 1 } pub extern "system" fn XGLeaveExclusiveLock() { if LOCKING.load(Ordering::Acquire) { EXCLUSIVE.leave(); } } const BIND_RENDER_TARGET: u32 = 0x20; const BIND_DEPTH_STENCIL: u32 = 0x40; const BIND_UNORDERED_ACCESS: u32 = 0x80; const MISC_TILED: u32 = 0x0800_0000; const ALLOW_UNORDERED_ACCESS: u32 = 4; #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Texture1dDesc { pub width: u32, pub mips: u32, pub array: u32, pub format: u32, pub usage: u32, pub bind: u32, pub cpu_access: u32, pub misc: u32, pub swizzle: u32, pub pitch: u32, } extern "system" fn beyond(_: This) -> HRESULT { tracing::warn!( slot = format_args!("{SLOT:#x}"), "texture computer method not implemented" ); E_NOTIMPL } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Texture2dDesc { pub width: u32, pub height: u32, pub mips: u32, pub array: u32, pub format: u32, pub samples: u32, pub quality: u32, pub usage: u32, pub bind: u32, pub cpu_access: u32, pub misc: u32, pub swizzle: u32, pub pitch: u32, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Texture3dDesc { pub width: u32, pub height: u32, pub depth: u32, pub mips: u32, pub format: u32, pub usage: u32, pub bind: u32, pub cpu_access: u32, pub misc: u32, pub swizzle: u32, pub pitch: u32, } struct Classic { dimension: u32, width: u32, height: u32, depth_or_array: u32, mips: u32, format: u32, samples: u32, quality: u32, bind: u32, misc: u32, swizzle: u32, pitch: u32, } impl From<&Texture1dDesc> for Classic { fn from(d: &Texture1dDesc) -> Classic { Classic { dimension: TEXTURE_1D, width: d.width, height: 1, depth_or_array: d.array, mips: d.mips, format: d.format, samples: 1, quality: 0, bind: d.bind, misc: d.misc, swizzle: d.swizzle, pitch: d.pitch, } } } impl From<&Texture2dDesc> for Classic { fn from(d: &Texture2dDesc) -> Classic { Classic { dimension: TEXTURE_2D, width: d.width, height: d.height, depth_or_array: d.array, mips: d.mips, format: d.format, samples: d.samples, quality: d.quality, bind: d.bind, misc: d.misc, swizzle: d.swizzle, pitch: d.pitch, } } } impl From<&Texture3dDesc> for Classic { fn from(d: &Texture3dDesc) -> Classic { Classic { dimension: TEXTURE_3D, width: d.width, height: d.height, depth_or_array: d.depth, mips: d.mips, format: d.format, samples: 1, quality: 0, bind: d.bind, misc: d.misc, swizzle: d.swizzle, pitch: d.pitch, } } } impl Classic { fn resource(&self) -> Option<(ResourceDesc, bool)> { if self.swizzle == NO_MODE || self.swizzle > 0xff { return None; } let mut flags = 0; if self.bind & BIND_RENDER_TARGET != 0 { flags |= texture::ALLOW_RENDER_TARGET; } if self.bind & BIND_DEPTH_STENCIL != 0 { flags |= texture::ALLOW_DEPTH_STENCIL; } if self.bind & BIND_UNORDERED_ACCESS != 0 { flags |= ALLOW_UNORDERED_ACCESS; } Some(( ResourceDesc { dimension: self.dimension, alignment: 0, width: u64::from(self.width), height: self.height, depth_or_array: u16::try_from(self.depth_or_array.max(1)).ok()?, mips: u16::try_from(self.mips).ok()?, format: self.format, samples: self.samples.max(1), quality: self.quality, layout: SWIZZLED | self.swizzle, flags, }, self.misc & MISC_TILED != 0, )) } } fn create_classic(desc: Option, out: *mut This) -> HRESULT { let (Some(desc), false) = (desc, out.is_null()) else { return E_INVALIDARG; }; let Some((resource, tiled)) = desc.resource() else { tracing::warn!(swizzle = desc.swizzle, "XG description without a usable swizzle mode"); return E_INVALIDARG; }; let hr = create(resource, tiled, out); if hr != S_OK || desc.pitch == 0 { return hr; } let made = unsafe { out.read() }; let l = &computer(made).texture.planes[0].layout; let own = l.mips[0].pitch * l.desc.block; if desc.pitch != own { tracing::warn!(asked = desc.pitch, own, "XG: a row pitch of the caller's is not laid out here"); release(made); unsafe { out.write(std::ptr::null_mut()) }; return E_NOTIMPL; } S_OK } pub extern "system" fn XGCreateTexture1DComputer(desc: *const Texture1dDesc, out: *mut This) -> HRESULT { create_classic(unsafe { desc.as_ref() }.map(Classic::from), out) } pub extern "system" fn XGCreateTexture2DComputer(desc: *const Texture2dDesc, out: *mut This) -> HRESULT { create_classic(unsafe { desc.as_ref() }.map(Classic::from), out) } pub extern "system" fn XGCreateTexture3DComputer(desc: *const Texture3dDesc, out: *mut This) -> HRESULT { create_classic(unsafe { desc.as_ref() }.map(Classic::from), out) } fn compute_layout(desc: Option, out: *mut LayoutOut) -> HRESULT { if out.is_null() { return E_INVALIDARG; } let mut c = std::ptr::null_mut(); let hr = create_classic(desc, &mut c); if hr != S_OK { return hr; } let hr = layout(c, out); release(c); hr } pub extern "system" fn XGComputeTexture1DLayout(desc: *const Texture1dDesc, out: *mut LayoutOut) -> HRESULT { compute_layout(unsafe { desc.as_ref() }.map(Classic::from), out) } pub extern "system" fn XGComputeTexture2DLayout(desc: *const Texture2dDesc, out: *mut LayoutOut) -> HRESULT { compute_layout(unsafe { desc.as_ref() }.map(Classic::from), out) } pub extern "system" fn XGComputeTexture3DLayout(desc: *const Texture3dDesc, out: *mut LayoutOut) -> HRESULT { compute_layout(unsafe { desc.as_ref() }.map(Classic::from), out) } #[allow(clippy::too_many_arguments)] pub extern "system" fn XGComputeOptimalSwizzleMode( kind: u32, _format: u32, _width: u32, _height: u32, _depth_or_array: u32, _samples: u32, bind: u32, misc: u32, ) -> u32 { let Some(dim) = dimension(kind) else { return NO_MODE; }; let mut flags = 0; if bind & BIND_RENDER_TARGET != 0 { flags |= texture::ALLOW_RENDER_TARGET; } if bind & BIND_DEPTH_STENCIL != 0 { flags |= texture::ALLOW_DEPTH_STENCIL; } let layout = if misc & MISC_TILED != 0 { texture::LAYOUT_64KB_UNDEFINED } else { 0 }; layout_swizzle(dim, layout, flags).map_or(NO_MODE, |s| s.0) } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct BufferDesc { pub byte_width: u32, pub usage: u32, pub bind: u32, pub cpu_access: u32, pub misc: u32, pub stride: u32, } pub extern "system" fn XGComputeBufferLayout(desc: *const BufferDesc, out: *mut LayoutOut) -> HRESULT { const KIB_64: u64 = 64 << 10; const BUFFER: u32 = 1; let Some(desc) = (unsafe { desc.as_ref() }) else { return E_INVALIDARG; }; if out.is_null() || desc.byte_width == 0 { return E_INVALIDARG; } let size = u64::from(desc.byte_width).next_multiple_of(KIB_64); let mut layout: LayoutOut = unsafe { std::mem::zeroed() }; (layout.size, layout.alignment, layout.mips, layout.planes, layout.dimension) = (size, KIB_64, 1, 1, BUFFER); let plane = &mut layout.plane[0]; (plane.usage, plane.size, plane.slice_size, plane.alignment, plane.element_bytes, plane.standard_mips) = (1, size, size, KIB_64, 1, 1); plane.mips[0] = MipOut { size, slice_size: size, pitch_texels: desc.byte_width, pitch_bytes: desc.byte_width, alignment: KIB_64 as u32, padded: [desc.byte_width, 1, 1], elements: [desc.byte_width, 1], texels: [desc.byte_width, 1], depth_or_array: 1, samples: 1, swizzle: Swizzle::LINEAR.0, ..MipOut::default() }; unsafe { out.write(layout) }; S_OK } fn is_depth_format(format: u32) -> bool { matches!(format, 19 | 20 | 39 | 40 | 44 | 45 | 53 | 55) } #[allow(clippy::too_many_arguments)] pub extern "system" fn XGComputeOptimalDepthStencilSwizzleMode( _format: u32, _width: u32, _height: u32, _depth_or_array: u32, _samples: u32, _compressed: i32, tiled: i32, _texture_compatible: i32, out: *mut u32, ) { if out.is_null() { return; } let misc = if tiled != 0 { MISC_TILED } else { 0 }; let mode = XGComputeOptimalSwizzleMode(TEXTURE_2D, 0, 0, 0, 0, 0, BIND_DEPTH_STENCIL, misc); unsafe { out.write(mode) }; } pub extern "system" fn XGValidateDepthStencilSwizzleMode(format: u32, samples: u32, mode: u32) -> HRESULT { let ok = is_depth_format(format) && matches!(samples, 1 | 2 | 4 | 8) && mode == Swizzle::SW_64KB_Z_X.0; if ok { S_OK } else { E_INVALIDARG } } pub extern "system" fn XGValidateDescriptor(dwords: u32, descriptor: *const u32, _flags: u32) -> HRESULT { if descriptor.is_null() || !matches!(dwords, 4 | 8) { return E_INVALIDARG; } S_OK } pub extern "system" fn XGComputeTileShape( kind: u32, format: u32, bytes_per_element: u32, samples: u32, texels: *mut [u32; 3], elements: *mut [u32; 3], ) -> HRESULT { let Some(dim) = dimension(kind) else { return E_INVALIDARG; }; let samples_ok = match dim { Dimension::Tex2d => matches!(samples, 1 | 2 | 4 | 8), _ => samples == 1, }; if !samples_ok { return E_INVALIDARG; } let (element_bytes, block) = if format == 0 { if !matches!(bytes_per_element, 1 | 2 | 4 | 8 | 16) { return E_INVALIDARG; } (bytes_per_element, 1) } else { match texture::format(format) { Some(f) if !f.stencil => (f.bytes, f.block), _ => return E_INVALIDARG, } }; let shape = if dim == Dimension::Tex1d { [(TILE as u32) / element_bytes, 1, 1] } else { let layout = Layout::new(&texture::Desc { dimension: dim, width: 1024 * block, height: 1024 * block, depth: if dim == Dimension::Tex3d { 256 } else { 1 }, mips: 1, element_bytes, block, samples, swizzle: Swizzle::SW_64KB_S, }); match layout { Ok(l) => l.block, Err(e) => { tracing::warn!(?e, kind, format, samples, "no tile shape"); return E_INVALIDARG; } } }; unsafe { if let Some(e) = elements.as_mut() { *e = shape; } if let Some(t) = texels.as_mut() { *t = if format == 0 { [0; 3] } else { [shape[0] * block, shape[1] * block, shape[2]] }; } } S_OK } #[repr(C)] struct Vtable([*const (); 22]); unsafe impl Sync for Vtable {} static VTABLE: Vtable = Vtable([ add_ref as *const (), release as *const (), layout as *const (), size_bytes as *const (), alignment_bytes as *const (), mip_offset as *const (), element_offset as *const (), texel_coordinate as *const (), copy_into as *const (), copy_from as *const (), tiling as *const (), view_descriptor as *const (), is_tiled as *const (), swizzle_pattern as *const (), beyond::<0x70> as *const (), beyond::<0x78> as *const (), beyond::<0x80> as *const (), beyond::<0x88> as *const (), beyond::<0x90> as *const (), beyond::<0x98> as *const (), beyond::<0xa0> as *const (), beyond::<0xa8> as *const (), ]); pub(crate) fn module() -> HleModule { HleModule { name: "xg", dlls: &["xg_xs.dll"], exports: vec![ hle_export!(XGCreateTextureComputer), hle_export!(XGSuggestSwizzleMode), hle_export!(XGCreateTexture1DComputer), hle_export!(XGCreateTexture2DComputer), hle_export!(XGCreateTexture3DComputer), hle_export!(XGComputeTexture1DLayout), hle_export!(XGComputeTexture2DLayout), hle_export!(XGComputeTexture3DLayout), hle_export!(XGComputeOptimalSwizzleMode), hle_export!(XGComputeBufferLayout), hle_export!(XGComputeOptimalDepthStencilSwizzleMode), hle_export!(XGValidateDepthStencilSwizzleMode), hle_export!(XGValidateDescriptor), hle_export!(XGComputeTileShape), hle_export!(XGInitializeLibrary), hle_export!(XGTerminateLibrary), hle_export!(XGSetHardwareVersion), hle_export!(XGEnableExclusiveLocking), hle_export!(XGEnterExclusiveLock), hle_export!(XGLeaveExclusiveLock), ], } }