diff --git a/CHANGELOG.md b/CHANGELOG.md index 30b9a30..d7edc28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ remains unsupported. ### Added - Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, and the engine that ran the guest executes nothing further. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review. +- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted. - Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215. - Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending. - Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review. diff --git a/Cargo.lock b/Cargo.lock index e9de1b0..613d3f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,6 +204,7 @@ dependencies = [ "sha2", "xenora-metal", "xenora-shader", + "xenora-texture", ] [[package]] diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml index c945ce6..f74714e 100644 --- a/crates/loader/Cargo.toml +++ b/crates/loader/Cargo.toml @@ -16,6 +16,7 @@ gpu-tests = [] [dependencies] libc = "0.2" sha2 = "0.10" +xenora-texture = { path = "../texture" } [dev-dependencies] xenora-metal = { path = "../metal" } diff --git a/crates/loader/src/graphics.rs b/crates/loader/src/graphics.rs index 8f626ed..5f4ea58 100644 --- a/crates/loader/src/graphics.rs +++ b/crates/loader/src/graphics.rs @@ -122,6 +122,9 @@ pub enum GraphicsError { /// An indexed draw reads past its index buffer or fetches a vertex, /// after applying the base vertex, outside its vertex buffer. IndexOutOfRange, + /// A descriptor heap, view, sampler, root signature or binding outside + /// the supported texture-binding subset. Nothing is drawn. + Unsupported(&'static str), } impl std::fmt::Display for GraphicsError { @@ -149,6 +152,7 @@ impl std::fmt::Display for GraphicsError { write!(f, "unsupported index buffer format {format}") } Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"), + Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"), } } } @@ -180,6 +184,9 @@ pub struct GraphicsResource { pub state: ResourceStates, pub guest_backing_addr: Option, pub data: Vec, + /// The texel format of a `Texture2D` that a shader resource view may + /// read; `None` for buffers and textures without a supported format. + pub texture_format: Option, } /// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`. @@ -208,6 +215,377 @@ impl IndexFormat { } } +/// Descriptors one shader-visible heap may hold. +pub const MAX_DESCRIPTORS_PER_HEAP: u32 = 64; +/// Largest width and height of a texture that a shader resource view reads. +pub const MAX_TEXTURE_DIMENSION: u32 = 64; +/// `GetDescriptorHandleIncrementSize` for both supported heap types. Guests +/// must query it rather than assume a value, as on D3D12. +pub const DESCRIPTOR_HANDLE_INCREMENT: u32 = 32; +/// `D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND`. +pub const DESCRIPTOR_RANGE_OFFSET_APPEND: u32 = 0xffff_ffff; +/// DXGI format code of `R8G8B8A8_UNORM`. +pub const DXGI_FORMAT_R8G8B8A8_UNORM: u32 = 28; +/// DXGI format code of `BC1_UNORM`. +pub const DXGI_FORMAT_BC1_UNORM: u32 = 71; +/// `D3D12_FILTER_MIN_MAG_MIP_POINT`. +pub const D3D12_FILTER_MIN_MAG_MIP_POINT: u32 = 0; +/// `D3D12_TEXTURE_ADDRESS_MODE_CLAMP`. +pub const D3D12_TEXTURE_ADDRESS_MODE_CLAMP: u32 = 3; + +/// Largest image the software reference draws for a textured draw. +pub const MAX_SOFTWARE_TEXTURED_PIXELS: usize = 4096; +/// The read-only `D3D12_RESOURCE_STATES`: vertex and constant buffer, index +/// buffer, depth read, both shader resources, indirect argument and copy source. +const READ_STATES: u32 = 0x1 | 0x2 | 0x20 | 0x40 | 0x80 | 0x200 | 0x800; + +/// Bit that separates GPU descriptor handles from CPU ones. +const GPU_DESCRIPTOR_SPACE: u64 = 1 << 63; + +/// `D3D12_DESCRIPTOR_HEAP_TYPE`; only the two shader-visible types exist here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorHeapType { + CbvSrvUav, + Sampler, +} + +impl DescriptorHeapType { + /// The heap type for a `D3D12_DESCRIPTOR_HEAP_TYPE` value: `CBV_SRV_UAV` + /// (0) or `SAMPLER` (1). `RTV` (2) and `DSV` (3) are not supported. + pub const fn from_d3d12(value: u32) -> Option { + match value { + 0 => Some(Self::CbvSrvUav), + 1 => Some(Self::Sampler), + _ => None, + } + } +} + +/// `D3D12_CPU_DESCRIPTOR_HANDLE`: the destination of descriptor creation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CpuDescriptorHandle(pub u64); + +/// `D3D12_GPU_DESCRIPTOR_HANDLE`: the base of a bound descriptor table. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GpuDescriptorHandle(pub u64); + +/// `handle + index × increment`, or `None` when the sum leaves the heap's +/// 32-bit offset field and would carry into its heap ID. +const fn offset_handle(handle: u64, index: u32) -> Option { + let offset = (handle as u32 as u64) + index as u64 * DESCRIPTOR_HANDLE_INCREMENT as u64; + if offset > u32::MAX as u64 { + None + } else { + Some(handle & !(u32::MAX as u64) | offset) + } +} + +impl CpuDescriptorHandle { + /// The handle `index` increments past this one, if it stays in its heap's range. + pub const fn offset(self, index: u32) -> Option { + match offset_handle(self.0, index) { + Some(value) => Some(Self(value)), + None => None, + } + } +} + +impl GpuDescriptorHandle { + /// The handle `index` increments past this one, if it stays in its heap's range. + pub const fn offset(self, index: u32) -> Option { + match offset_handle(self.0, index) { + Some(value) => Some(Self(value)), + None => None, + } + } +} + +/// Texel format of a texture a shader resource view reads. Rows are linear +/// and tightly packed: four bytes per texel, or eight bytes per 4×4 block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextureFormat { + Rgba8Unorm, + Bc1Unorm, +} + +impl TextureFormat { + /// The format for a DXGI format code, `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71). + pub const fn from_dxgi(format: u32) -> Option { + match format { + DXGI_FORMAT_R8G8B8A8_UNORM => Some(Self::Rgba8Unorm), + DXGI_FORMAT_BC1_UNORM => Some(Self::Bc1Unorm), + _ => None, + } + } + + /// Bytes of one level of `width` × `height` texels. + pub const fn level_size(self, width: u32, height: u32) -> usize { + match self { + Self::Rgba8Unorm => width as usize * height as usize * 4, + Self::Bc1Unorm => width.div_ceil(4) as usize * height.div_ceil(4) as usize * 8, + } + } +} + +/// `D3D12_SRV_DIMENSION`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SrvDimension { + Buffer, + Texture1D, + Texture2D, + Texture2DArray, + Texture3D, + TextureCube, +} + +/// `D3D12_SHADER_RESOURCE_VIEW_DESC` for a single-level 2D texture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ShaderResourceViewDesc { + /// DXGI format code; it must equal the resource's format. + pub format: u32, + pub view_dimension: SrvDimension, + pub most_detailed_mip: u32, + pub mip_levels: u32, +} + +/// `D3D12_SAMPLER_DESC` without the fields that point sampling ignores. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SamplerDesc { + pub filter: u32, + pub address_u: u32, + pub address_v: u32, + pub address_w: u32, + pub mip_lod_bias: f32, + pub min_lod: f32, + pub max_lod: f32, +} + +impl SamplerDesc { + /// Point filtering with clamp addressing, the one supported state. + pub const fn point_clamp() -> Self { + Self { + filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + address_u: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + address_v: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + address_w: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + mip_lod_bias: 0.0, + min_lod: 0.0, + max_lod: f32::MAX, + } + } + + fn validate(&self) -> Result<(), GraphicsError> { + if self.filter != D3D12_FILTER_MIN_MAG_MIP_POINT { + return Err(GraphicsError::Unsupported( + "sampler filter other than point", + )); + } + if [self.address_u, self.address_v, self.address_w] + .iter() + .any(|&mode| mode != D3D12_TEXTURE_ADDRESS_MODE_CLAMP) + { + return Err(GraphicsError::Unsupported( + "sampler address mode other than clamp", + )); + } + if self.mip_lod_bias != 0.0 + || self.min_lod != 0.0 + || self.max_lod.is_nan() + || self.max_lod < 0.0 + { + return Err(GraphicsError::Unsupported("sampler LOD bias or range")); + } + Ok(()) + } +} + +/// `D3D12_DESCRIPTOR_RANGE_TYPE`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorRangeType { + Srv, + Uav, + Cbv, + Sampler, +} + +/// `D3D12_DESCRIPTOR_RANGE`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DescriptorRange { + pub range_type: DescriptorRangeType, + pub num_descriptors: u32, + pub base_shader_register: u32, + pub register_space: u32, + pub offset_in_descriptors_from_table_start: u32, +} + +/// `D3D12_SHADER_VISIBILITY`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShaderVisibility { + All, + Vertex, + Hull, + Domain, + Geometry, + Pixel, +} + +/// `D3D12_ROOT_PARAMETER`, by parameter type. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RootParameter { + DescriptorTable { + ranges: Vec, + visibility: ShaderVisibility, + }, + Constants32Bit { + visibility: ShaderVisibility, + }, + Cbv { + visibility: ShaderVisibility, + }, + Srv { + visibility: ShaderVisibility, + }, + Uav { + visibility: ShaderVisibility, + }, +} + +/// `D3D12_ROOT_SIGNATURE_DESC`, unserialized. Static samplers are counted only: +/// any is unsupported. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RootSignatureDesc { + pub parameters: Vec, + pub static_sampler_count: u32, +} + +/// The supported root signature: one pixel-stage table holding `t0` and +/// one holding `s0`, at these root parameter indices. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct RootSignature { + srv_parameter: u32, + sampler_parameter: u32, +} + +impl RootSignature { + fn from_desc(desc: &RootSignatureDesc) -> Result { + if desc.static_sampler_count != 0 { + return Err(GraphicsError::Unsupported("static samplers")); + } + if desc.parameters.len() != 2 { + return Err(GraphicsError::Unsupported( + "root signature other than one SRV table and one sampler table", + )); + } + let mut srv = None; + let mut sampler = None; + for (index, parameter) in (0u32..).zip(&desc.parameters) { + let RootParameter::DescriptorTable { ranges, visibility } = parameter else { + return Err(GraphicsError::Unsupported( + "root constants or root descriptors", + )); + }; + if *visibility != ShaderVisibility::Pixel { + return Err(GraphicsError::Unsupported("shader stage other than pixel")); + } + let [range] = ranges.as_slice() else { + return Err(GraphicsError::Unsupported( + "descriptor table with other than one range", + )); + }; + if range.num_descriptors != 1 + || range.base_shader_register != 0 + || range.register_space != 0 + || !matches!( + range.offset_in_descriptors_from_table_start, + 0 | DESCRIPTOR_RANGE_OFFSET_APPEND + ) + { + return Err(GraphicsError::Unsupported( + "descriptor range other than one descriptor at register 0, space 0", + )); + } + let slot = match range.range_type { + DescriptorRangeType::Srv => &mut srv, + DescriptorRangeType::Sampler => &mut sampler, + DescriptorRangeType::Uav => return Err(GraphicsError::Unsupported("UAV range")), + DescriptorRangeType::Cbv => return Err(GraphicsError::Unsupported("CBV range")), + }; + if slot.replace(index).is_some() { + return Err(GraphicsError::Unsupported( + "more than one table of one range type", + )); + } + } + match (srv, sampler) { + (Some(srv_parameter), Some(sampler_parameter)) => Ok(Self { + srv_parameter, + sampler_parameter, + }), + _ => Err(GraphicsError::Unsupported( + "root signature without both an SRV and a sampler table", + )), + } + } +} + +/// One filled descriptor. +#[derive(Clone, Copy, Debug)] +enum Descriptor { + Srv { + resource: GraphicsHandle, + format: TextureFormat, + }, + Sampler(SamplerDesc), +} + +/// Per-execution root signature, heap and table bindings. +#[derive(Default)] +struct TableBindings { + root_signature: Option<(GraphicsHandle, RootSignature)>, + srv_heap: Option, + sampler_heap: Option, + tables: [Option; 2], +} + +/// A shader-visible descriptor heap. +struct DescriptorHeap { + handle: GraphicsHandle, + heap_type: DescriptorHeapType, + slots: Vec>, +} + +/// The texture a textured draw samples, as bound through its SRV table. +#[derive(Clone, Copy, Debug)] +pub struct TextureView<'a> { + pub format: TextureFormat, + pub width: u32, + pub height: u32, + /// The single level: tightly packed rows of texels or BC1 blocks. + pub bytes: &'a [u8], +} + +/// One triangle that samples a bound texture in the pixel stage. +/// +/// Each vertex supplies a float4 position and a float4 texture coordinate, +/// whose `xy` are the normalized `uv` the pixel stage samples at. +#[derive(Clone, Copy, Debug)] +pub struct TexturedDraw<'a> { + pub positions: [[f32; 4]; 3], + pub texcoords: [[f32; 4]; 3], + pub viewport: (usize, usize), + pub clear_color: [u8; 4], + pub texture: TextureView<'a>, + pub sampler: SamplerDesc, +} + +/// Backend renderer for textured draws. +pub type TexturedBackendRenderer<'a> = + dyn Fn(&TexturedDraw<'_>) -> Result, GraphicsError> + 'a; + +/// Shared thread-safe textured backend renderer instance. +pub type SharedTexturedBackendRenderer = + Arc) -> Result, GraphicsError> + Send + Sync>; + /// Primitive Draw Command recorded in a Command List. #[derive(Clone, Debug)] pub enum GraphicsCommand { @@ -247,6 +625,19 @@ pub enum GraphicsCommand { base_vertex_location: i32, start_instance_location: u32, }, + /// `SetDescriptorHeaps`: at most one heap of each type. + SetDescriptorHeaps { + heaps: Vec, + }, + /// `SetGraphicsRootSignature`; it clears every bound table. + SetGraphicsRootSignature { + root_signature: GraphicsHandle, + }, + /// `SetGraphicsRootDescriptorTable`. + SetGraphicsRootDescriptorTable { + root_parameter_index: u32, + base: GpuDescriptorHandle, + }, } /// Command List in recording or closed state. @@ -298,9 +689,14 @@ pub struct GraphicsContext { allocators: HashMap, command_lists: HashMap, resources: HashMap, + /// Descriptor heaps by handle ID, which descriptor handles encode. + descriptor_heaps: HashMap, + root_signatures: HashMap, pub last_presentation: Arc>, /// Optional active backend renderer (e.g. Native Metal). backend: Option, + /// Optional backend renderer for textured draws. + textured_backend: Option, backend_id: GraphicsBackendId, } @@ -319,8 +715,11 @@ impl GraphicsContext { allocators: HashMap::new(), command_lists: HashMap::new(), resources: HashMap::new(), + descriptor_heaps: HashMap::new(), + root_signatures: HashMap::new(), last_presentation: Arc::new(Mutex::new(FramePresentation::default())), backend: None, + textured_backend: None, backend_id: GraphicsBackendId::SoftwareReference, } } @@ -337,10 +736,20 @@ impl GraphicsContext { self.backend_id = GraphicsBackendId::MetalNative; } + /// Install a native Metal adapter for draws that sample a bound texture. + pub fn set_metal_textured_backend(&mut self, renderer: F) + where + F: Fn(&TexturedDraw<'_>) -> Result, GraphicsError> + Send + Sync + 'static, + { + self.textured_backend = Some(Arc::new(renderer)); + self.backend_id = GraphicsBackendId::MetalNative; + } + /// Explicitly configure context to require native Metal without an attached backend. /// Useful for verifying that missing/unsupported Metal devices correctly fail execution. pub fn set_require_metal_without_backend(&mut self) { self.backend = None; + self.textured_backend = None; self.backend_id = GraphicsBackendId::MetalNative; } @@ -447,6 +856,8 @@ impl GraphicsContext { return Err(GraphicsError::InvalidDeviceHandle); } let handle = self.allocate_handle(); + let texture_format = (desc.dimension == ResourceDimension::Texture2D && desc.format_rgba8) + .then_some(TextureFormat::Rgba8Unorm); let size = match desc.dimension { ResourceDimension::Buffer => desc.width as usize, ResourceDimension::Texture2D => (desc.width as usize) * (desc.height as usize) * 4, @@ -460,6 +871,7 @@ impl GraphicsContext { state: initial_state, guest_backing_addr: guest_addr, data: vec![0u8; size], + texture_format, }, ); Ok(handle) @@ -559,7 +971,10 @@ impl GraphicsContext { .resources .get(&resource) .ok_or(GraphicsError::InvalidResourceHandle)?; - if offset + stride > res.data.len() && res.guest_backing_addr.is_none() { + let end = offset + .checked_add(stride) + .ok_or(GraphicsError::InvalidDescriptor)?; + if end > res.data.len() && res.guest_backing_addr.is_none() { return Err(GraphicsError::InvalidDescriptor); } cmd_list.commands.push(GraphicsCommand::SetVertexBuffer { @@ -661,6 +1076,319 @@ impl GraphicsContext { Ok(()) } + /// Create a committed single-level 2D texture (`CreateCommittedResource` + /// with a texture format). `format` is a DXGI code: `R8G8B8A8_UNORM` (28) + /// or `BC1_UNORM` (71). BC1 sizes must be multiples of four. + pub fn create_committed_texture2d( + &mut self, + device: GraphicsHandle, + width: u32, + height: u32, + format: u32, + initial_state: ResourceStates, + guest_addr: Option, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let format = + TextureFormat::from_dxgi(format).ok_or(GraphicsError::Unsupported("texture format"))?; + if !(1..=MAX_TEXTURE_DIMENSION).contains(&width) + || !(1..=MAX_TEXTURE_DIMENSION).contains(&height) + { + return Err(GraphicsError::Unsupported("texture size")); + } + if format == TextureFormat::Bc1Unorm + && (!width.is_multiple_of(4) || !height.is_multiple_of(4)) + { + return Err(GraphicsError::Unsupported( + "BC1 size not a multiple of four", + )); + } + let handle = self.allocate_handle(); + self.resources.insert( + handle, + GraphicsResource { + handle, + desc: ResourceDesc { + dimension: ResourceDimension::Texture2D, + width: u64::from(width), + height, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: format == TextureFormat::Rgba8Unorm, + }, + state: initial_state, + guest_backing_addr: guest_addr, + data: vec![0; format.level_size(width, height)], + texture_format: Some(format), + }, + ); + Ok(handle) + } + + /// Create a descriptor heap (`CreateDescriptorHeap`). `heap_type` is a + /// `D3D12_DESCRIPTOR_HEAP_TYPE`; only shader-visible `CBV_SRV_UAV` and + /// `SAMPLER` heaps of 1 to [`MAX_DESCRIPTORS_PER_HEAP`] descriptors exist. + pub fn create_descriptor_heap( + &mut self, + device: GraphicsHandle, + heap_type: u32, + num_descriptors: u32, + shader_visible: bool, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let heap_type = DescriptorHeapType::from_d3d12(heap_type) + .ok_or(GraphicsError::Unsupported("descriptor heap type"))?; + if !shader_visible { + return Err(GraphicsError::Unsupported( + "non-shader-visible descriptor heap", + )); + } + if !(1..=MAX_DESCRIPTORS_PER_HEAP).contains(&num_descriptors) { + return Err(GraphicsError::Unsupported("descriptor heap capacity")); + } + let handle = self.allocate_handle(); + if handle.id >= 1 << 31 { + return Err(GraphicsError::Unsupported( + "descriptor heap ID space exhausted", + )); + } + self.descriptor_heaps.insert( + handle.id, + DescriptorHeap { + handle, + heap_type, + slots: vec![None; num_descriptors as usize], + }, + ); + Ok(handle) + } + + fn descriptor_heap(&self, heap: GraphicsHandle) -> Result<&DescriptorHeap, GraphicsError> { + self.descriptor_heaps + .get(&heap.id) + .filter(|found| found.handle == heap) + .ok_or(GraphicsError::InvalidDescriptor) + } + + /// `GetCPUDescriptorHandleForHeapStart`. + pub fn cpu_descriptor_handle_for_heap_start( + &self, + heap: GraphicsHandle, + ) -> Result { + self.descriptor_heap(heap)?; + Ok(CpuDescriptorHandle(u64::from(heap.id) << 32)) + } + + /// `GetGPUDescriptorHandleForHeapStart`. + pub fn gpu_descriptor_handle_for_heap_start( + &self, + heap: GraphicsHandle, + ) -> Result { + self.descriptor_heap(heap)?; + Ok(GpuDescriptorHandle( + GPU_DESCRIPTOR_SPACE | u64::from(heap.id) << 32, + )) + } + + /// `GetDescriptorHandleIncrementSize` for a `D3D12_DESCRIPTOR_HEAP_TYPE`. + pub fn descriptor_handle_increment_size(&self, heap_type: u32) -> Result { + DescriptorHeapType::from_d3d12(heap_type) + .map(|_| DESCRIPTOR_HANDLE_INCREMENT) + .ok_or(GraphicsError::Unsupported("descriptor heap type")) + } + + /// The heap ID and slot index a handle in the given space names, if it is + /// increment-aligned. The heap itself is not checked. + fn decode_descriptor_handle(value: u64, gpu: bool) -> Option<(u32, usize)> { + if (value & GPU_DESCRIPTOR_SPACE != 0) != gpu { + return None; + } + let value = value & !GPU_DESCRIPTOR_SPACE; + let offset = value as u32; + if !offset.is_multiple_of(DESCRIPTOR_HANDLE_INCREMENT) { + return None; + } + Some(( + (value >> 32) as u32, + (offset / DESCRIPTOR_HANDLE_INCREMENT) as usize, + )) + } + + fn write_descriptor( + &mut self, + dest: CpuDescriptorHandle, + heap_type: DescriptorHeapType, + descriptor: Descriptor, + ) -> Result<(), GraphicsError> { + let (heap_id, index) = Self::decode_descriptor_handle(dest.0, false) + .ok_or(GraphicsError::InvalidDescriptor)?; + let heap = self + .descriptor_heaps + .get_mut(&heap_id) + .ok_or(GraphicsError::InvalidDescriptor)?; + if heap.heap_type != heap_type { + return Err(GraphicsError::InvalidDescriptor); + } + let slot = heap + .slots + .get_mut(index) + .ok_or(GraphicsError::InvalidDescriptor)?; + *slot = Some(descriptor); + Ok(()) + } + + /// `CreateShaderResourceView` of a single-level 2D texture into a + /// `CBV_SRV_UAV` heap slot. The view format must equal the resource's. + pub fn create_shader_resource_view( + &mut self, + resource: GraphicsHandle, + desc: &ShaderResourceViewDesc, + dest: CpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + let res = self + .resources + .get(&resource) + .ok_or(GraphicsError::InvalidResourceHandle)?; + if res.desc.dimension != ResourceDimension::Texture2D + || res.desc.depth_or_array_size != 1 + || res.desc.mip_levels != 1 + { + return Err(GraphicsError::Unsupported( + "SRV of a resource other than a single-level, single-slice 2D texture", + )); + } + if desc.view_dimension != SrvDimension::Texture2D { + return Err(GraphicsError::Unsupported( + "SRV dimension other than Texture2D", + )); + } + if desc.most_detailed_mip != 0 || desc.mip_levels != 1 { + return Err(GraphicsError::Unsupported( + "SRV mip range other than level 0", + )); + } + let format = TextureFormat::from_dxgi(desc.format) + .ok_or(GraphicsError::Unsupported("SRV format"))?; + if res.texture_format != Some(format) { + return Err(GraphicsError::Unsupported( + "SRV format differs from the resource", + )); + } + let max = u64::from(MAX_TEXTURE_DIMENSION); + if !(1..=max).contains(&res.desc.width) || !(1..=max).contains(&u64::from(res.desc.height)) + { + return Err(GraphicsError::Unsupported("texture size")); + } + self.write_descriptor( + dest, + DescriptorHeapType::CbvSrvUav, + Descriptor::Srv { resource, format }, + ) + } + + /// `CreateSampler` into a `SAMPLER` heap slot. + pub fn create_sampler( + &mut self, + desc: &SamplerDesc, + dest: CpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + desc.validate()?; + self.write_descriptor( + dest, + DescriptorHeapType::Sampler, + Descriptor::Sampler(*desc), + ) + } + + /// `CreateRootSignature` from an unserialized description. Only one + /// pixel-stage table for `t0` and one for `s0` are supported. + pub fn create_root_signature( + &mut self, + device: GraphicsHandle, + desc: &RootSignatureDesc, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let root_signature = RootSignature::from_desc(desc)?; + let handle = self.allocate_handle(); + self.root_signatures.insert(handle, root_signature); + Ok(handle) + } + + fn recording_list( + &mut self, + list: GraphicsHandle, + ) -> Result<&mut GraphicsCommandList, GraphicsError> { + let cmd_list = self + .command_lists + .get_mut(&list) + .ok_or(GraphicsError::InvalidCommandListHandle)?; + if !cmd_list.is_recording { + return Err(GraphicsError::CommandListNotRecording); + } + Ok(cmd_list) + } + + /// Record `SetDescriptorHeaps`: at most one heap of each type. + pub fn cmd_set_descriptor_heaps( + &mut self, + list: GraphicsHandle, + heaps: &[GraphicsHandle], + ) -> Result<(), GraphicsError> { + let mut types = Vec::with_capacity(heaps.len()); + for &heap in heaps { + let heap_type = self.descriptor_heap(heap)?.heap_type; + if types.contains(&heap_type) { + return Err(GraphicsError::InvalidDescriptor); + } + types.push(heap_type); + } + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetDescriptorHeaps { + heaps: heaps.to_vec(), + }); + Ok(()) + } + + /// Record `SetGraphicsRootSignature`. + pub fn cmd_set_graphics_root_signature( + &mut self, + list: GraphicsHandle, + root_signature: GraphicsHandle, + ) -> Result<(), GraphicsError> { + if !self.root_signatures.contains_key(&root_signature) { + return Err(GraphicsError::InvalidDescriptor); + } + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetGraphicsRootSignature { root_signature }); + Ok(()) + } + + /// Record `SetGraphicsRootDescriptorTable`. When the list executes, the + /// command checks the base against the bound root signature and the bound + /// heap of the table's type. A draw then reads the descriptor it names. + pub fn cmd_set_graphics_root_descriptor_table( + &mut self, + list: GraphicsHandle, + root_parameter_index: u32, + base: GpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetGraphicsRootDescriptorTable { + root_parameter_index, + base, + }); + Ok(()) + } + /// Close command list. pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> { let cmd_list = self @@ -738,6 +1466,11 @@ impl GraphicsContext { backend_renderer: Option<&BackendRenderer<'_>>, backend_id: GraphicsBackendId, ) -> Result { + let textured_backend = self.textured_backend.clone(); + let textured_renderer: Option<&TexturedBackendRenderer<'_>> = match &textured_backend { + Some(arc) => Some(arc.as_ref()), + None => None, + }; let cmd_queue = self .queues .get_mut(&queue) @@ -766,6 +1499,7 @@ impl GraphicsContext { let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None; let mut rendered_output: Option> = None; let mut draw_count = 0usize; + let mut bindings = TableBindings::default(); for cmd in &cmd_list.commands { match cmd { @@ -807,6 +1541,59 @@ impl GraphicsContext { offset, format, } => index_buffer = Some((*resource, *offset, *format)), + GraphicsCommand::SetDescriptorHeaps { heaps } => { + let (mut srv_heap, mut sampler_heap) = (None, None); + for &heap in heaps { + match self.descriptor_heap(heap)?.heap_type { + DescriptorHeapType::CbvSrvUav => srv_heap = Some(heap.id), + DescriptorHeapType::Sampler => sampler_heap = Some(heap.id), + } + } + // Changing the heaps invalidates tables bound in the old + // ones; setting the same heaps again keeps them. + if (srv_heap, sampler_heap) != (bindings.srv_heap, bindings.sampler_heap) { + bindings.tables = [None; 2]; + } + bindings.srv_heap = srv_heap; + bindings.sampler_heap = sampler_heap; + } + GraphicsCommand::SetGraphicsRootSignature { root_signature } => { + let layout = *self + .root_signatures + .get(root_signature) + .ok_or(GraphicsError::InvalidDescriptor)?; + // A different root signature invalidates every root + // argument; setting the bound one again keeps them. + if bindings.root_signature.map(|(handle, _)| handle) != Some(*root_signature) { + bindings.tables = [None; 2]; + } + bindings.root_signature = Some((*root_signature, layout)); + } + GraphicsCommand::SetGraphicsRootDescriptorTable { + root_parameter_index, + base, + } => { + let (_, layout) = bindings + .root_signature + .ok_or(GraphicsError::InvalidDescriptor)?; + let bound_heap = if *root_parameter_index == layout.srv_parameter { + bindings.srv_heap + } else if *root_parameter_index == layout.sampler_parameter { + bindings.sampler_heap + } else { + return Err(GraphicsError::InvalidDescriptor); + }; + // The base must name a slot of the bound heap of the + // table's type; its contents are read at the draw. + let (heap_id, index) = Self::decode_descriptor_handle(base.0, true) + .ok_or(GraphicsError::InvalidDescriptor)?; + if bound_heap != Some(heap_id) + || index >= self.descriptor_heaps[&heap_id].slots.len() + { + return Err(GraphicsError::InvalidDescriptor); + } + bindings.tables[*root_parameter_index as usize] = Some(*base); + } GraphicsCommand::DrawIndexedInstanced { index_count_per_instance, instance_count, @@ -823,6 +1610,9 @@ impl GraphicsContext { if *index_count_per_instance == 0 || *instance_count == 0 { continue; } + if bindings.root_signature.is_some() { + return Err(GraphicsError::Unsupported("textured indexed draws")); + } let vertices = self.fetch_indexed_triangle( memory, index_buffer, @@ -848,8 +1638,41 @@ impl GraphicsContext { } GraphicsCommand::DrawInstanced { vertex_count_per_instance, - .. + instance_count, + start_vertex_location, + start_instance_location, } => { + if let Some((_, root_signature)) = bindings.root_signature { + if *vertex_count_per_instance == 0 || *instance_count == 0 { + continue; + } + if *vertex_count_per_instance != 3 + || *instance_count != 1 + || *start_instance_location != 0 + { + return Err(GraphicsError::Unsupported( + "textured draw other than one instance of three vertices", + )); + } + let pixels = self.textured_draw( + memory, + &bindings, + root_signature, + (vertex_resource, vertex_offset, vertex_stride), + *start_vertex_location, + (viewport, clear_color), + (textured_renderer, backend_id), + )?; + draw_count += 1; + if let Some(th) = target_handle + && let Some(target_res) = self.resources.get_mut(&th) + && target_res.data.len() >= pixels.len() + { + target_res.data[..pixels.len()].copy_from_slice(&pixels); + } + rendered_output = Some(pixels); + continue; + } if *vertex_count_per_instance < 3 { continue; } @@ -976,6 +1799,184 @@ impl GraphicsContext { Ok(vertices) } + /// Resolve the SRV and sampler tables, fetch one textured triangle and + /// draw it on the textured backend, or on the software reference when no + /// native backend is required. Every check runs before any drawing. + #[allow(clippy::too_many_arguments)] + fn textured_draw( + &self, + memory: &GuestMemory, + bindings: &TableBindings, + root_signature: RootSignature, + (vertex_resource, vertex_offset, vertex_stride): (Option, usize, usize), + start_vertex: u32, + (viewport, clear_color): ((usize, usize), [u8; 4]), + (renderer, backend_id): (Option<&TexturedBackendRenderer<'_>>, GraphicsBackendId), + ) -> Result, GraphicsError> { + let srv = self.resolve_table(bindings, root_signature.srv_parameter, bindings.srv_heap)?; + let sampler = self.resolve_table( + bindings, + root_signature.sampler_parameter, + bindings.sampler_heap, + )?; + let (Descriptor::Srv { resource, format }, Descriptor::Sampler(sampler)) = (srv, sampler) + else { + return Err(GraphicsError::InvalidDescriptor); + }; + let texture = self + .resources + .get(&resource) + .ok_or(GraphicsError::InvalidResourceHandle)?; + // COMMON promotes to a shader-resource read. Any other state must + // include PIXEL_SHADER_RESOURCE and combine it only with read states. + let state = texture.state.0; + if state != ResourceStates::COMMON.0 + && (state & ResourceStates::PIXEL_SHADER_RESOURCE.0 == 0 || state & !READ_STATES != 0) + { + return Err(GraphicsError::ResourceLifetimeViolation); + } + let width = texture.desc.width as u32; + let height = texture.desc.height; + let mut bytes = vec![0; format.level_size(width, height)]; + Self::read_resource(texture, memory, 0, &mut bytes)?; + + let vertex_res = vertex_resource + .and_then(|handle| self.resources.get(&handle)) + .ok_or(GraphicsError::InvalidResourceHandle)?; + if vertex_stride < 32 { + return Err(GraphicsError::InvalidDescriptor); + } + let mut positions = [[0.0f32; 4]; 3]; + let mut texcoords = [[0.0f32; 4]; 3]; + for (k, (position, texcoord)) in positions.iter_mut().zip(&mut texcoords).enumerate() { + let at = (start_vertex as usize + k) + .checked_mul(vertex_stride) + .and_then(|bytes| bytes.checked_add(vertex_offset)) + .ok_or(GraphicsError::IndexOutOfRange)?; + let mut raw = [0u8; 32]; + Self::read_resource(vertex_res, memory, at, &mut raw)?; + for (value, bytes) in position + .iter_mut() + .chain(texcoord.iter_mut()) + .zip(raw.as_chunks::<4>().0) + { + *value = f32::from_le_bytes(*bytes); + } + } + + let draw = TexturedDraw { + positions, + texcoords, + viewport, + clear_color, + texture: TextureView { + format, + width, + height, + bytes: &bytes, + }, + sampler, + }; + if let Some(renderer) = renderer { + renderer(&draw) + } else if backend_id == GraphicsBackendId::MetalNative { + Err(GraphicsError::NativeMetalRequired) + } else { + Self::execute_software_reference_textured_draw(&draw) + } + } + + /// The descriptor that the table at `parameter` names in the bound heap. + fn resolve_table( + &self, + bindings: &TableBindings, + parameter: u32, + bound_heap: Option, + ) -> Result { + let base = bindings.tables[parameter as usize].ok_or(GraphicsError::InvalidDescriptor)?; + let (heap_id, index) = + Self::decode_descriptor_handle(base.0, true).ok_or(GraphicsError::InvalidDescriptor)?; + if bound_heap != Some(heap_id) { + return Err(GraphicsError::InvalidDescriptor); + } + self.descriptor_heaps + .get(&heap_id) + .and_then(|heap| heap.slots.get(index).copied().flatten()) + .ok_or(GraphicsError::InvalidDescriptor) + } + + /// Software reference for a textured triangle: the coverage rule of + /// [`Self::execute_software_reference_draw`], affine interpolation of the + /// texture coordinate at each pixel center, and point sampling with + /// clamp addressing (`texel = min(floor(clamp(u, 0, 1) * width), width - 1)`). + /// BC1 levels are decoded with `xenora_texture::decode_bc1`. Positions + /// must have `w == 1`. + pub fn execute_software_reference_textured_draw( + draw: &TexturedDraw<'_>, + ) -> Result, GraphicsError> { + if draw.positions.iter().any(|position| position[3] != 1.0) { + return Err(GraphicsError::Unsupported( + "software textured draw with w other than 1", + )); + } + if draw + .positions + .iter() + .chain(&draw.texcoords) + .flatten() + .any(|value| !value.is_finite()) + { + return Err(GraphicsError::InvalidDescriptor); + } + let max = MAX_TEXTURE_DIMENSION; + if !(1..=max).contains(&draw.texture.width) || !(1..=max).contains(&draw.texture.height) { + return Err(GraphicsError::Unsupported("texture size")); + } + let texels = decode_texture(&draw.texture)?; + let (tex_w, tex_h) = (draw.texture.width as usize, draw.texture.height as usize); + let (w, h) = draw.viewport; + let count = w + .checked_mul(h) + .filter(|&count| (1..=MAX_SOFTWARE_TEXTURED_PIXELS).contains(&count)) + .ok_or(GraphicsError::InvalidViewport)?; + let mut pixels = draw.clear_color.repeat(count); + let window = |p: [f32; 4]| [(p[0] + 1.0) * 0.5 * w as f32, (1.0 - p[1]) * 0.5 * h as f32]; + let [p0, p1, p2] = draw.positions.map(window); + let edge = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| -> f32 { + (c[0] - a[0]) * (b[1] - a[1]) - (c[1] - a[1]) * (b[0] - a[0]) + }; + let area = edge(p0, p1, p2); + if area.abs() < 1e-5 { + return Ok(pixels); + } + let nearest = |coord: f32, size: usize| { + ((f64::from(coord.clamp(0.0, 1.0)) * size as f64).floor() as usize).min(size - 1) + }; + for y in 0..h { + for x in 0..w { + let pt = [x as f32 + 0.5, y as f32 + 0.5]; + let b = [edge(p1, p2, pt), edge(p2, p0, pt), edge(p0, p1, pt)]; + let inside = if area > 0.0 { + b.iter().all(|&e| e >= 0.0) + } else { + b.iter().all(|&e| e <= 0.0) + }; + if !inside { + continue; + } + let [u, v] = [0, 1].map(|axis| { + (0..3) + .map(|k| b[k] / area * draw.texcoords[k][axis]) + .sum::() + }); + let texel = (nearest(v, tex_h) * tex_w + nearest(u, tex_w)) * 4; + let idx = (y * w + x) * 4; + pixels[idx..idx + 4].copy_from_slice(&texels[texel..texel + 4]); + } + } + Ok(pixels) + } + /// Read `out.len()` bytes at `offset` of a resource, from its guest backing /// when it has one. The range must lie inside the resource's size. fn read_resource( @@ -1057,3 +2058,30 @@ impl GraphicsContext { Ok(pixels) } } + +/// Row-major RGBA8 texels of a bound texture level. +fn decode_texture(texture: &TextureView<'_>) -> Result, GraphicsError> { + let (width, height) = (texture.width as usize, texture.height as usize); + if texture.bytes.len() != texture.format.level_size(texture.width, texture.height) { + return Err(GraphicsError::InvalidDescriptor); + } + match texture.format { + TextureFormat::Rgba8Unorm => Ok(texture.bytes.to_vec()), + TextureFormat::Bc1Unorm => { + let blocks_wide = width.div_ceil(4); + let mut texels = vec![0; width * height * 4]; + for (block_index, block) in texture.bytes.as_chunks::<8>().0.iter().enumerate() { + let decoded = xenora_texture::decode_bc1(*block); + let (bx, by) = (block_index % blocks_wide * 4, block_index / blocks_wide * 4); + for (i, texel) in decoded.iter().enumerate() { + let (x, y) = (bx + i % 4, by + i / 4); + if x < width && y < height { + let at = (y * width + x) * 4; + texels[at..at + 4].copy_from_slice(texel); + } + } + } + Ok(texels) + } + } +} diff --git a/crates/loader/tests/graphics_textures.rs b/crates/loader/tests/graphics_textures.rs new file mode 100644 index 0000000..3edec4c --- /dev/null +++ b/crates/loader/tests/graphics_textures.rs @@ -0,0 +1,1228 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Guest draws that sample a texture bound through D3D12-style descriptor +//! heaps, a root signature and descriptor tables (#303). +//! +//! Every fixture is synthetic. The expected images are written out by hand +//! from the texel data and the draw geometry, so they depend on neither the +//! software reference nor the native Metal path. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use xenora_loader::graphics::{ + CommandListType, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_R8G8B8A8_UNORM, DescriptorRange, DescriptorRangeType, ExecutionOutcome, + GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle, ResourceDesc, + ResourceDimension, ResourceStates, RootParameter, RootSignatureDesc, SamplerDesc, + ShaderResourceViewDesc, ShaderVisibility, SrvDimension, TextureFormat, +}; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; + +const CBV_SRV_UAV: u32 = 0; +const SAMPLER: u32 = 1; +const VB_ADDR: u64 = 0x10_0000; +const TEX_ADDR: u64 = 0x20_0000; +const STRIDE: usize = 32; + +/// Texel `(x, y)` of the 4×4 texture A is `[64x + 16, 64y + 16, 200, 255]`. +fn texture_a() -> Vec { + (0..16u8) + .flat_map(|i| [(i % 4) * 64 + 16, (i / 4) * 64 + 16, 200, 255]) + .collect() +} + +/// Texel `(x, y)` of the 4×4 texture B is `[7, 11x + 3, 13y + 5, 255]`. +fn texture_b() -> Vec { + (0..16u8) + .flat_map(|i| [7, (i % 4) * 11 + 3, (i / 4) * 13 + 5, 255]) + .collect() +} + +/// An 8×8 BC1 texture of four row-major blocks. Each block selects only its +/// two endpoints (selector 0 or 1), whose RGB565 words expand exactly to 0 +/// or 255 per channel. Interpolated palette entries are left out: Apple's +/// hardware decoder rounds them differently from the spec formula. +/// Each block uses selector 1 where `x == 0 || y == 3` within the block. +const BC1_BLOCKS: [[u8; 8]; 4] = [ + // Endpoint 0 red (0xF800), endpoint 1 blue (0x001F). + [0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], + // Green (0x07E0), black (0x0000). + [0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], + // White (0xFFFF), magenta (0xF81F). + [0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], + // Yellow (0xFFE0), cyan (0x07FF). + [0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], +]; + +/// The BC1 texture decoded by hand, row-major RGBA8. +fn bc1_expected() -> Vec { + let endpoints = [ + [[255, 0, 0, 255], [0, 0, 255, 255]], + [[0, 255, 0, 255], [0, 0, 0, 255]], + [[255, 255, 255, 255], [255, 0, 255, 255]], + [[255, 255, 0, 255], [0, 255, 255, 255]], + ]; + let mut texels = Vec::new(); + for y in 0..8 { + for x in 0..8 { + let block = (y / 4) * 2 + x / 4; + let selector = usize::from(x % 4 == 0 || y % 4 == 3); + texels.extend(endpoints[block][selector]); + } + } + texels +} + +/// A fullscreen triangle: position float4, then texture coordinate float4. +/// Over an N×N viewport the pixel centre `(x + 0.5, y + 0.5)` gets +/// `uv = ((x + 0.5) / N, (y + 0.5) / N)`, so pixel `(x, y)` of an N×N +/// texture samples texel `(x, y)` and the image equals the texture. +const VERTICES: [[f32; 8]; 3] = [ + [-1.0, -1.0, 0.5, 1.0, 0.0, 1.0, 0.0, 1.0], + [3.0, -1.0, 0.5, 1.0, 2.0, 1.0, 0.0, 1.0], + [-1.0, 3.0, 0.5, 1.0, 0.0, -1.0, 0.0, 1.0], +]; + +/// The same triangle with `uv' = 2·uv − 0.6`: pixel centres sample +/// u (and v) = −0.35, 0.15, 0.65, 1.15, off texel centres and outside +/// [0, 1] on both sides. Point sampling with clamping reads texels +/// 0, 0, 2, 3 along each axis; wrapping or linear filtering would not. +const CLAMP_VERTICES: [[f32; 8]; 3] = [ + [-1.0, -1.0, 0.5, 1.0, -0.6, 1.4, 0.0, 1.0], + [3.0, -1.0, 0.5, 1.0, 3.4, 1.4, 0.0, 1.0], + [-1.0, 3.0, 0.5, 1.0, -0.6, -2.6, 0.0, 1.0], +]; +const CLAMPED_TEXEL: [usize; 4] = [0, 0, 2, 3]; + +fn pixel_table(range_type: DescriptorRangeType) -> RootParameter { + RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility: ShaderVisibility::Pixel, + } +} + +fn root_signature_desc() -> RootSignatureDesc { + RootSignatureDesc { + parameters: vec![ + pixel_table(DescriptorRangeType::Srv), + pixel_table(DescriptorRangeType::Sampler), + ], + static_sampler_count: 0, + } +} + +fn srv_desc(format: u32) -> ShaderResourceViewDesc { + ShaderResourceViewDesc { + format, + view_dimension: SrvDimension::Texture2D, + most_detailed_mip: 0, + mip_levels: 1, + } +} + +struct Rig { + ctx: GraphicsContext, + memory: GuestMemory, + device: GraphicsHandle, + queue: GraphicsHandle, + alloc: GraphicsHandle, + list: GraphicsHandle, + vb: GraphicsHandle, + srv_heap: GraphicsHandle, + sampler_heap: GraphicsHandle, + root_signature: GraphicsHandle, + /// Sampler table at root parameter 0, SRV table at 1. + swapped_root_signature: GraphicsHandle, +} + +/// SRV heap slots: 0 texture A (4×4), 1 texture B (4×4), 2 the 8×8 BC1 +/// texture, 3 empty. +/// Sampler heap slots: 0 and 2 point/clamp, 1 empty. Every supported +/// sampler has the same state, so slots differ only in being filled. +fn rig() -> Rig { + let mut ctx = GraphicsContext::new(); + let device = ctx.create_device().unwrap(); + let queue = ctx + .create_command_queue(device, CommandListType::Direct) + .unwrap(); + let alloc = ctx + .create_command_allocator(device, CommandListType::Direct) + .unwrap(); + let list = ctx + .create_command_list(device, alloc, CommandListType::Direct) + .unwrap(); + // Records 0–2 are VERTICES and 3–5 CLAMP_VERTICES. + let vertex_bytes: Vec = VERTICES + .as_flattened() + .iter() + .chain(CLAMP_VERTICES.as_flattened()) + .flat_map(|value| value.to_le_bytes()) + .collect(); + let vb = ctx + .create_committed_resource( + device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: vertex_bytes.len() as u64, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::VERTEX_AND_CONSTANT_BUFFER, + Some(VB_ADDR), + ) + .unwrap(); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(VB_ADDR, 0x1000, MemoryPermissions::READ_ONLY, &vertex_bytes) + .unwrap(); + + let textures = [ + (DXGI_FORMAT_R8G8B8A8_UNORM, texture_a()), + (DXGI_FORMAT_R8G8B8A8_UNORM, texture_b()), + (DXGI_FORMAT_BC1_UNORM, BC1_BLOCKS.as_flattened().to_vec()), + ]; + let srv_heap = ctx + .create_descriptor_heap(device, CBV_SRV_UAV, 4, true) + .unwrap(); + let srv_start = ctx.cpu_descriptor_handle_for_heap_start(srv_heap).unwrap(); + for (slot, (format, bytes)) in (0u32..).zip(&textures) { + let addr = TEX_ADDR + u64::from(slot) * 0x1000; + memory + .map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes) + .unwrap(); + let size = if *format == DXGI_FORMAT_BC1_UNORM { + 8 + } else { + 4 + }; + let texture = ctx + .create_committed_texture2d( + device, + size, + size, + *format, + ResourceStates::COMMON, + Some(addr), + ) + .unwrap(); + ctx.create_shader_resource_view( + texture, + &srv_desc(*format), + srv_start.offset(slot).unwrap(), + ) + .unwrap(); + } + let sampler_heap = ctx + .create_descriptor_heap(device, SAMPLER, 3, true) + .unwrap(); + let sampler_start = ctx + .cpu_descriptor_handle_for_heap_start(sampler_heap) + .unwrap(); + for slot in [0, 2] { + ctx.create_sampler( + &SamplerDesc::point_clamp(), + sampler_start.offset(slot).unwrap(), + ) + .unwrap(); + } + let root_signature = ctx + .create_root_signature(device, &root_signature_desc()) + .unwrap(); + let swapped_root_signature = ctx + .create_root_signature( + device, + &RootSignatureDesc { + parameters: vec![ + pixel_table(DescriptorRangeType::Sampler), + pixel_table(DescriptorRangeType::Srv), + ], + static_sampler_count: 0, + }, + ) + .unwrap(); + Rig { + ctx, + memory, + device, + queue, + alloc, + list, + vb, + srv_heap, + sampler_heap, + root_signature, + swapped_root_signature, + } +} + +/// What one textured draw binds; `None` leaves that table unset. +#[derive(Clone, Copy)] +struct Binding { + srv_slot: Option, + sampler_slot: Option, + heaps_bound: (bool, bool), + stride: usize, + viewport: u32, + first_vertex: u32, + swapped: bool, + /// Vertex count, instance count, start instance. + draw: (u32, u32, u32), +} + +const SLOT_0: Binding = Binding { + srv_slot: Some(0), + sampler_slot: Some(0), + heaps_bound: (true, true), + stride: STRIDE, + viewport: 4, + first_vertex: 0, + swapped: false, + draw: (3, 1, 0), +}; + +/// Slot 2 holds the 8×8 BC1 texture and is drawn into an 8×8 viewport. +fn srv(slot: u32) -> Binding { + Binding { + srv_slot: Some(slot), + viewport: if slot == 2 { 8 } else { 4 }, + ..SLOT_0 + } +} + +/// Record and run: the binding's viewport, heaps, root signature, the two +/// tables (SRV at root parameter 0 and sampler at 1, or swapped) and one draw. +fn run(rig: &mut Rig, binding: Binding) -> Result { + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc)?; + let size = binding.viewport as usize; + ctx.cmd_set_viewport(rig.list, size, size)?; + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, binding.stride)?; + let mut heaps = Vec::new(); + if binding.heaps_bound.0 { + heaps.push(rig.srv_heap); + } + if binding.heaps_bound.1 { + heaps.push(rig.sampler_heap); + } + ctx.cmd_set_descriptor_heaps(rig.list, &heaps)?; + let (root_signature, srv_parameter, sampler_parameter) = if binding.swapped { + (rig.swapped_root_signature, 1, 0) + } else { + (rig.root_signature, 0, 1) + }; + ctx.cmd_set_graphics_root_signature(rig.list, root_signature)?; + if let Some(slot) = binding.srv_slot { + let base = ctx.gpu_descriptor_handle_for_heap_start(rig.srv_heap)?; + let base = base.offset(slot).unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, srv_parameter, base)?; + } + if let Some(slot) = binding.sampler_slot { + let base = ctx.gpu_descriptor_handle_for_heap_start(rig.sampler_heap)?; + let base = base.offset(slot).unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, sampler_parameter, base)?; + } + let (vertices, instances, start_instance) = binding.draw; + ctx.cmd_draw_instanced( + rig.list, + vertices, + instances, + binding.first_vertex, + start_instance, + )?; + ctx.close_command_list(rig.list)?; + ctx.execute_command_list(rig.queue, rig.list, &rig.memory) +} + +#[test] +fn software_textured_draw_reproduces_rgba8_texels() { + let mut rig = rig(); + let outcome = run(&mut rig, SLOT_0).expect("textured draw"); + assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference); + assert_eq!(outcome.draw_count, 1); + assert_eq!((outcome.width, outcome.height), (4, 4)); + assert_eq!(outcome.pixels, texture_a()); +} + +/// The draw reads the descriptor the table names: slot 1 gives texture B, +/// which differs from texture A in every texel. +#[test] +fn descriptor_table_offset_selects_the_texture() { + let mut rig = rig(); + let outcome = run(&mut rig, srv(1)).expect("textured draw"); + assert_eq!(outcome.pixels, texture_b()); + for (a, b) in texture_a().chunks(4).zip(texture_b().chunks(4)) { + assert_ne!(a, b); + } +} + +#[test] +fn software_textured_draw_decodes_bc1() { + let mut rig = rig(); + let outcome = run(&mut rig, srv(2)).expect("BC1 textured draw"); + assert_eq!((outcome.width, outcome.height), (8, 8)); + assert_eq!(outcome.pixels, bc1_expected()); + // The shared BC1 decoder agrees with the hand-decoded blocks. + let expected = bc1_expected(); + for (index, block) in BC1_BLOCKS.into_iter().enumerate() { + let (bx, by) = (index % 2 * 4, index / 2 * 4); + for (i, texel) in xenora_texture::decode_bc1(block).iter().enumerate() { + let at = ((by + i / 4) * 8 + bx + i % 4) * 4; + assert_eq!(texel, &expected[at..at + 4], "block {index} texel {i}"); + } + } +} + +#[test] +fn unsupported_objects_fail_at_creation() { + let mut rig = rig(); + let ctx = &mut rig.ctx; + let device = rig.device; + let unsupported = |result: Result<(), GraphicsError>, case: &str| { + assert!( + matches!(result, Err(GraphicsError::Unsupported(_))), + "{case}: {result:?}" + ); + }; + + // Descriptor heaps: RTV and DSV types, CPU-only heaps, capacity. + for (heap_type, count, visible, case) in [ + (2, 4, true, "RTV heap"), + (3, 4, true, "DSV heap"), + (CBV_SRV_UAV, 4, false, "non-shader-visible heap"), + (CBV_SRV_UAV, 0, true, "empty heap"), + (SAMPLER, 65, true, "heap over capacity"), + ] { + unsupported( + ctx.create_descriptor_heap(device, heap_type, count, visible) + .map(drop), + case, + ); + } + + // Textures: other formats and BC1 sizes that are not whole blocks. + unsupported( + ctx.create_committed_texture2d(device, 4, 4, 2, ResourceStates::COMMON, None) + .map(drop), + "R32G32B32A32_FLOAT texture", + ); + unsupported( + ctx.create_committed_texture2d( + device, + 6, + 6, + DXGI_FORMAT_BC1_UNORM, + ResourceStates::COMMON, + None, + ) + .map(drop), + "6x6 BC1 texture", + ); + unsupported( + ctx.create_committed_texture2d( + device, + 65, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + ResourceStates::COMMON, + None, + ) + .map(drop), + "texture over the size limit", + ); + + // Shader resource views. + let texture = ctx + .create_committed_texture2d( + device, + 4, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + ResourceStates::COMMON, + None, + ) + .unwrap(); + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let base = srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM); + for (desc, case) in [ + ( + srv_desc(DXGI_FORMAT_BC1_UNORM), + "format differs from resource", + ), + (srv_desc(10), "R16G16B16A16_FLOAT view"), + ( + ShaderResourceViewDesc { + view_dimension: SrvDimension::Texture3D, + ..base + }, + "Texture3D view", + ), + ( + ShaderResourceViewDesc { + mip_levels: 2, + ..base + }, + "two-level view", + ), + ] { + unsupported(ctx.create_shader_resource_view(texture, &desc, dest), case); + } + + // Samplers. + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.sampler_heap) + .unwrap(); + let point = SamplerDesc::point_clamp(); + for (desc, case) in [ + ( + SamplerDesc { + filter: 0x15, + ..point + }, + "linear filter", + ), + ( + SamplerDesc { + address_v: 1, + ..point + }, + "wrap addressing", + ), + ( + SamplerDesc { + mip_lod_bias: 0.5, + ..point + }, + "LOD bias", + ), + ] { + unsupported(ctx.create_sampler(&desc, dest), case); + } + assert_eq!(point.address_u, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + + // Root signatures. + let table = |range_type, visibility| RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility, + }; + let srv_table = || pixel_table(DescriptorRangeType::Srv); + let sampler_table = || pixel_table(DescriptorRangeType::Sampler); + let two_ranges = RootParameter::DescriptorTable { + ranges: vec![ + DescriptorRange { + range_type: DescriptorRangeType::Srv, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }; + 2 + ], + visibility: ShaderVisibility::Pixel, + }; + let wide_range = RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type: DescriptorRangeType::Srv, + num_descriptors: 2, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility: ShaderVisibility::Pixel, + }; + for (parameters, static_sampler_count, case) in [ + ( + vec![srv_table(), sampler_table(), srv_table()], + 0, + "three tables", + ), + (vec![srv_table(), srv_table()], 0, "two SRV tables"), + ( + vec![ + table(DescriptorRangeType::Uav, ShaderVisibility::Pixel), + sampler_table(), + ], + 0, + "UAV range", + ), + ( + vec![ + table(DescriptorRangeType::Cbv, ShaderVisibility::Pixel), + sampler_table(), + ], + 0, + "CBV range", + ), + ( + vec![ + table(DescriptorRangeType::Srv, ShaderVisibility::Vertex), + sampler_table(), + ], + 0, + "vertex-stage table", + ), + ( + vec![ + srv_table(), + table(DescriptorRangeType::Sampler, ShaderVisibility::All), + ], + 0, + "all-stage table", + ), + ( + vec![ + RootParameter::Constants32Bit { + visibility: ShaderVisibility::Pixel, + }, + sampler_table(), + ], + 0, + "root constants", + ), + ( + vec![two_ranges, sampler_table()], + 0, + "two ranges in a table", + ), + (vec![wide_range, sampler_table()], 0, "two-descriptor range"), + (vec![srv_table(), sampler_table()], 1, "static sampler"), + (vec![srv_table()], 0, "SRV table only"), + ] { + let desc = RootSignatureDesc { + parameters, + static_sampler_count, + }; + unsupported(ctx.create_root_signature(device, &desc).map(drop), case); + } + // The supported shape also works with its tables in the other order. + let swapped = RootSignatureDesc { + parameters: vec![sampler_table(), srv_table()], + static_sampler_count: 0, + }; + ctx.create_root_signature(device, &swapped).unwrap(); +} + +/// Bindings that resolve to nothing, or to the wrong kind of descriptor, +/// fail at execution before the backend is called. +#[test] +fn bad_bindings_fail_and_never_draw() { + let mut rig = rig(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + rig.ctx.set_metal_textured_backend(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + Ok(vec![0; 64]) + }); + for (binding, case) in [ + ( + Binding { + srv_slot: None, + ..SLOT_0 + }, + "SRV table unset", + ), + ( + Binding { + sampler_slot: None, + ..SLOT_0 + }, + "sampler table unset", + ), + (srv(3), "empty SRV slot"), + (srv(4), "SRV slot past the heap"), + ( + Binding { + sampler_slot: Some(1), + ..SLOT_0 + }, + "empty sampler slot", + ), + ( + Binding { + heaps_bound: (true, false), + ..SLOT_0 + }, + "sampler heap not bound", + ), + ( + Binding { + heaps_bound: (false, true), + ..SLOT_0 + }, + "SRV heap not bound", + ), + ( + Binding { + stride: 16, + ..SLOT_0 + }, + "vertex stride without a texture coordinate", + ), + ] { + let result = run(&mut rig, binding); + assert_eq!(result, Err(GraphicsError::InvalidDescriptor), "{case}"); + } + + // A table whose base lies in the other heap, or in the CPU handle space. + let ctx = &mut rig.ctx; + let sampler_base = ctx + .gpu_descriptor_handle_for_heap_start(rig.sampler_heap) + .unwrap(); + let srv_base = ctx + .gpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let cpu_base = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let misaligned = xenora_loader::graphics::GpuDescriptorHandle(srv_base.0 + 4); + for (srv_table, case) in [ + (sampler_base, "SRV table in the sampler heap"), + ( + xenora_loader::graphics::GpuDescriptorHandle(cpu_base.0), + "CPU handle as table base", + ), + (misaligned, "misaligned table base"), + ] { + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_viewport(rig.list, 4, 4).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE) + .unwrap(); + ctx.cmd_set_descriptor_heaps(rig.list, &[rig.srv_heap, rig.sampler_heap]) + .unwrap(); + ctx.cmd_set_graphics_root_signature(rig.list, rig.root_signature) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 0, srv_table) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 1, sampler_base) + .unwrap(); + ctx.cmd_draw_instanced(rig.list, 3, 1, 0, 0).unwrap(); + ctx.close_command_list(rig.list).unwrap(); + let result = ctx.execute_command_list(rig.queue, rig.list, &rig.memory); + assert_eq!(result, Err(GraphicsError::InvalidDescriptor), "{case}"); + } + + // A textured indexed draw is outside the subset. + let ib = ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: 6, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::COMMON, + None, + ) + .unwrap(); + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE) + .unwrap(); + ctx.cmd_set_index_buffer(rig.list, ib, 0, 57).unwrap(); + ctx.cmd_set_graphics_root_signature(rig.list, rig.root_signature) + .unwrap(); + ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0) + .unwrap(); + ctx.close_command_list(rig.list).unwrap(); + assert!(matches!( + ctx.execute_command_list(rig.queue, rig.list, &rig.memory), + Err(GraphicsError::Unsupported(_)) + )); + + // Two heaps of one type in one SetDescriptorHeaps call. + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + assert_eq!( + ctx.cmd_set_descriptor_heaps(rig.list, &[rig.srv_heap, rig.srv_heap]), + Err(GraphicsError::InvalidDescriptor) + ); + + assert_eq!(calls.load(Ordering::SeqCst), 0, "the backend never drew"); + // The same rig draws once its binding is valid. + run(&mut rig, SLOT_0).expect("valid binding draws"); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +/// Off-centre and out-of-range coordinates: point sampling with clamping +/// gives pixel `(x, y)` texel `(CLAMPED_TEXEL[x], CLAMPED_TEXEL[y])`. The +/// draw starts at vertex record 3. +#[test] +fn point_clamp_sampling_off_centre_and_outside_unit_range() { + let mut rig = rig(); + let outcome = run( + &mut rig, + Binding { + first_vertex: 3, + ..SLOT_0 + }, + ) + .expect("textured draw"); + let a = texture_a(); + let expected: Vec = (0..16) + .flat_map(|i| { + let at = (CLAMPED_TEXEL[i / 4] * 4 + CLAMPED_TEXEL[i % 4]) * 4; + a[at..at + 4].to_vec() + }) + .collect(); + assert_eq!(outcome.pixels, expected); + assert_ne!(outcome.pixels, a); +} + +/// The root signature's parameter order decides which table is which, and +/// a nonzero sampler slot resolves. +#[test] +fn swapped_root_parameters_and_second_sampler_slot() { + let mut rig = rig(); + let outcome = run( + &mut rig, + Binding { + swapped: true, + sampler_slot: Some(2), + ..srv(1) + }, + ) + .expect("textured draw"); + assert_eq!(outcome.pixels, texture_b()); + // Binding the SRV table at the sampler's parameter fails. + let mut wrong = self::rig(); + let ctx = &mut wrong.ctx; + ctx.reset_command_list(wrong.list, wrong.alloc).unwrap(); + ctx.cmd_set_descriptor_heaps(wrong.list, &[wrong.srv_heap, wrong.sampler_heap]) + .unwrap(); + ctx.cmd_set_graphics_root_signature(wrong.list, wrong.swapped_root_signature) + .unwrap(); + let base = ctx + .gpu_descriptor_handle_for_heap_start(wrong.srv_heap) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(wrong.list, 0, base) + .unwrap(); + ctx.close_command_list(wrong.list).unwrap(); + assert_eq!( + ctx.execute_command_list(wrong.queue, wrong.list, &wrong.memory), + Err(GraphicsError::InvalidDescriptor) + ); +} + +#[derive(Clone)] +enum Step { + Heaps(Vec), + Root(GraphicsHandle), + Tables, + Draw, +} + +fn record(rig: &mut Rig, steps: &[Step]) -> Result { + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc)?; + ctx.cmd_set_viewport(rig.list, 4, 4)?; + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE)?; + for step in steps { + match step { + Step::Heaps(heaps) => ctx.cmd_set_descriptor_heaps(rig.list, heaps)?, + Step::Root(root) => ctx.cmd_set_graphics_root_signature(rig.list, *root)?, + Step::Tables => { + let srv = ctx.gpu_descriptor_handle_for_heap_start(rig.srv_heap)?; + let sampler = ctx.gpu_descriptor_handle_for_heap_start(rig.sampler_heap)?; + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 0, srv)?; + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 1, sampler)?; + } + Step::Draw => ctx.cmd_draw_instanced(rig.list, 3, 1, 0, 0)?, + } + } + ctx.close_command_list(rig.list)?; + ctx.execute_command_list(rig.queue, rig.list, &rig.memory) +} + +/// Changing heaps or the root signature invalidates bound tables; setting +/// the same heaps or the same root signature again keeps them. +#[test] +fn heap_and_root_signature_changes_invalidate_tables() { + let mut rig = rig(); + let other_srv_heap = rig + .ctx + .create_descriptor_heap(rig.device, CBV_SRV_UAV, 4, true) + .unwrap(); + let same_layout = rig + .ctx + .create_root_signature(rig.device, &root_signature_desc()) + .unwrap(); + let heaps = Step::Heaps(vec![rig.srv_heap, rig.sampler_heap]); + let other = Step::Heaps(vec![other_srv_heap, rig.sampler_heap]); + let root = Step::Root(rig.root_signature); + let bound = [heaps.clone(), root.clone(), Step::Tables]; + for (extra, expected, case) in [ + (vec![], Ok(()), "plain"), + (vec![heaps.clone()], Ok(()), "same heaps again"), + (vec![root.clone()], Ok(()), "same root signature again"), + ( + vec![other, heaps.clone()], + Err(GraphicsError::InvalidDescriptor), + "heaps changed and restored", + ), + ( + vec![Step::Root(same_layout)], + Err(GraphicsError::InvalidDescriptor), + "another root signature with the same layout", + ), + ] { + let mut steps = bound.to_vec(); + steps.extend(extra); + steps.push(Step::Draw); + let result = record(&mut rig, &steps); + match expected { + Ok(()) => assert_eq!(result.expect(case).pixels, texture_a(), "{case}"), + Err(error) => assert_eq!(result, Err(error), "{case}"), + } + } +} + +/// Zero vertices or instances draw nothing; any other shape than one +/// instance of three vertices is unsupported. Neither reaches the backend. +#[test] +fn textured_draw_shapes() { + let mut rig = rig(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + rig.ctx.set_metal_textured_backend(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + Ok(vec![0; 64]) + }); + for draw in [(3, 0, 0), (0, 1, 0)] { + let outcome = run(&mut rig, Binding { draw, ..SLOT_0 }).unwrap(); + assert_eq!(outcome.draw_count, 0, "{draw:?}"); + } + for draw in [(6, 1, 0), (3, 2, 0), (3, 1, 1)] { + let result = run(&mut rig, Binding { draw, ..SLOT_0 }); + assert!( + matches!(result, Err(GraphicsError::Unsupported(_))), + "{draw:?}: {result:?}" + ); + } + assert_eq!(calls.load(Ordering::SeqCst), 0); +} + +/// Vertex and texture reads stay inside their resources even when the +/// guest backing maps more bytes. +#[test] +fn reads_stay_inside_resources() { + let mut rig = rig(); + rig.vb = rig + .ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: 2 * STRIDE as u64, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::VERTEX_AND_CONSTANT_BUFFER, + Some(VB_ADDR), + ) + .unwrap(); + assert_eq!(run(&mut rig, SLOT_0), Err(GraphicsError::IndexOutOfRange)); +} + +/// Array textures cannot be viewed, and a texture in a state that excludes +/// pixel-shader reads cannot be sampled. +#[test] +fn texture_shape_and_state_are_checked() { + let mut rig = rig(); + let ctx = &mut rig.ctx; + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap() + .offset(3) + .unwrap(); + let array = ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Texture2D, + width: 4, + height: 4, + depth_or_array_size: 2, + mip_levels: 1, + format_rgba8: true, + }, + ResourceStates::COMMON, + None, + ) + .unwrap(); + assert!(matches!( + ctx.create_shader_resource_view(array, &srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM), dest), + Err(GraphicsError::Unsupported(_)) + )); + for (state, ok) in [ + (ResourceStates::COPY_DEST, false), + ( + ResourceStates(ResourceStates::COPY_DEST.0 | ResourceStates::PIXEL_SHADER_RESOURCE.0), + false, + ), + ( + ResourceStates( + ResourceStates::NON_PIXEL_SHADER_RESOURCE.0 + | ResourceStates::PIXEL_SHADER_RESOURCE.0, + ), + true, + ), + (ResourceStates::RENDER_TARGET, false), + (ResourceStates::PIXEL_SHADER_RESOURCE, true), + ] { + let ctx = &mut rig.ctx; + let texture = ctx + .create_committed_texture2d( + rig.device, + 4, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + state, + Some(TEX_ADDR), + ) + .unwrap(); + ctx.create_shader_resource_view(texture, &srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM), dest) + .unwrap(); + let result = run(&mut rig, srv(3)); + if ok { + assert_eq!(result.unwrap().pixels, texture_a(), "{state:?}"); + } else { + assert_eq!( + result, + Err(GraphicsError::ResourceLifetimeViolation), + "{state:?}" + ); + } + } +} + +/// The public software reference rejects viewports it cannot allocate. +#[test] +fn software_reference_rejects_oversized_viewports() { + let texels = texture_a(); + for viewport in [(usize::MAX, 2), (65, 64), (0, 4)] { + let draw = xenora_loader::graphics::TexturedDraw { + positions: VERTICES.map(|v| [v[0], v[1], v[2], v[3]]), + texcoords: VERTICES.map(|v| [v[4], v[5], v[6], v[7]]), + viewport, + clear_color: [0, 0, 0, 255], + texture: xenora_loader::graphics::TextureView { + format: TextureFormat::Rgba8Unorm, + width: 4, + height: 4, + bytes: &texels, + }, + sampler: SamplerDesc::point_clamp(), + }; + assert_eq!( + GraphicsContext::execute_software_reference_textured_draw(&draw), + Err(GraphicsError::InvalidViewport), + "{viewport:?}" + ); + } +} + +/// Handle arithmetic cannot carry into the heap ID. +#[test] +fn descriptor_handle_offsets_stay_in_their_heap() { + let rig = rig(); + let start = rig + .ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + assert_eq!(start.offset(1 << 27), None); + let last = start.offset((1 << 27) - 1).unwrap(); + assert_eq!(last.0 >> 32, start.0 >> 32); + let gpu = rig + .ctx + .gpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + assert_eq!(gpu.offset(1 << 27), None); +} + +#[test] +fn textured_draw_requires_native_backend_when_configured() { + let mut rig = rig(); + rig.ctx.set_require_metal_without_backend(); + assert_eq!( + run(&mut rig, SLOT_0), + Err(GraphicsError::NativeMetalRequired) + ); +} + +/// The backend receives the bound texture's level, the sampler and the +/// guest's per-vertex positions and texture coordinates. +#[test] +fn backend_receives_the_bound_texture_and_vertices() { + let mut rig = rig(); + let seen = Arc::new(std::sync::Mutex::new(None)); + let sink = seen.clone(); + rig.ctx.set_metal_textured_backend(move |draw| { + *sink.lock().unwrap() = Some(( + draw.texture.format, + (draw.texture.width, draw.texture.height), + draw.texture.bytes.to_vec(), + draw.positions, + draw.texcoords, + draw.sampler, + )); + GraphicsContext::execute_software_reference_textured_draw(draw) + }); + let outcome = run(&mut rig, srv(2)).unwrap(); + assert_eq!(outcome.backend, GraphicsBackendId::MetalNative); + let (format, extent, bytes, positions, texcoords, sampler) = + seen.lock().unwrap().take().unwrap(); + assert_eq!(format, TextureFormat::Bc1Unorm); + assert_eq!(extent, (8, 8)); + assert_eq!(bytes, BC1_BLOCKS.as_flattened()); + assert_eq!(positions, VERTICES.map(|v| [v[0], v[1], v[2], v[3]])); + assert_eq!(texcoords, VERTICES.map(|v| [v[4], v[5], v[6], v[7]])); + assert_eq!(sampler, SamplerDesc::point_clamp()); +} + +/// The translated RDNA2 `image_sample_lz` pixel stage samples the bound +/// texture on Metal. Native, software and hand-derived images agree. +#[test] +#[cfg_attr( + not(feature = "gpu-tests"), + ignore = "needs native Metal device; run scripts/test-gpu.sh" +)] +fn native_metal_textured_draw_matches_references() { + use xenora_metal::NativeCompute; + use xenora_metal::sampler::MetalSampler; + use xenora_metal::texture_pipeline::{MetalRgba8Texture, Rgba8MipLevel, Rgba8TextureDesc}; + use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; + use xenora_texture::{Bc1Upload, Bc1UploadDesc}; + + let msl = compile_graphics( + Architecture::Gfx1030, + include_bytes!("../../../fixtures/rdna2/x9-varying-vs.bin"), + &image_sample_lz_ps(), + ) + .expect("compile translated image_sample_lz shader") + .msl; + let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device")); + let entries = [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT]; + let backend = gpu.clone(); + let metal_error = |e: xenora_metal::MetalError| GraphicsError::BackendError(format!("{e:?}")); + let mut rig = rig(); + rig.ctx.set_metal_textured_backend(move |draw| { + assert_eq!(draw.sampler, SamplerDesc::point_clamp()); + let sampler = MetalSampler::new( + backend.device(), + xenora_texture::SamplerDesc::nearest_clamp(), + ) + .map_err(metal_error)?; + let (width, height) = (draw.texture.width as usize, draw.texture.height as usize); + let extent = [draw.viewport.0, draw.viewport.1]; + match draw.texture.format { + TextureFormat::Rgba8Unorm => { + let desc = Rgba8TextureDesc::new(width, height, 1).map_err(metal_error)?; + let level = Rgba8MipLevel::new_packed(0, width, height, draw.texture.bytes); + let texture = MetalRgba8Texture::upload(backend.device(), desc, &[level]) + .map_err(metal_error)?; + backend.render_rgba8_sampled( + &msl, + entries, + &draw.positions, + &draw.texcoords, + extent, + draw.clear_color, + Some((&texture, &sampler)), + ) + } + TextureFormat::Bc1Unorm => { + let row_pitch = width.div_ceil(4) * 8; + let desc = Bc1UploadDesc { + width, + height, + mips: 1, + layers: 1, + format: 1, + usage: 1, + row_pitch, + slice_pitch: row_pitch * height.div_ceil(4), + }; + let upload = Bc1Upload::new(draw.texture.bytes, desc) + .map_err(|e| GraphicsError::BackendError(format!("{e:?}")))?; + backend.render_rgba8_sampled_bc1( + &msl, + entries, + &draw.positions, + &draw.texcoords, + extent, + draw.clear_color, + &upload, + &sampler, + ) + } + } + .map_err(metal_error) + }); + + let mut software = self::rig(); + for (slot, expected, name) in [ + (0, texture_a(), "RGBA8 texture A"), + (1, texture_b(), "RGBA8 texture B"), + (2, bc1_expected(), "BC1 texture"), + ] { + let native = run(&mut rig, srv(slot)).expect("native textured draw"); + assert_eq!(native.backend, GraphicsBackendId::MetalNative); + assert_eq!(native.pixels, expected, "{name}: native vs hand-derived"); + let reference = run(&mut software, srv(slot)).expect("software textured draw"); + assert_eq!( + native.pixels, reference.pixels, + "{name}: native vs software" + ); + } + // Off-centre and out-of-range coordinates clamp on Metal as in software. + let clamped = Binding { + first_vertex: 3, + ..SLOT_0 + }; + let native = run(&mut rig, clamped).expect("native clamped draw"); + let reference = run(&mut software, clamped).expect("software clamped draw"); + assert_eq!( + native.pixels, reference.pixels, + "clamped: native vs software" + ); + assert_ne!(native.pixels, texture_a()); + println!( + "device={} guest-bound textures: RGBA8 slots 0 and 1 (16 of 16 pixels) and BC1 slot 2 (64 of 64) match", + gpu.device_name() + ); +} + +/// Translated gfx1030 pixel stage: interpolate parameter 0's `xy`, then +/// `image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:2D` and +/// export the sample. Same bytes as the Metal crate's translated-render test. +fn image_sample_lz_ps() -> Vec { + [ + &[0x00, 0x00, 0x08, 0xc8][..], + &[0x01, 0x00, 0x09, 0xc8], + &[0x00, 0x01, 0x0c, 0xc8], + &[0x01, 0x01, 0x0d, 0xc8], + &[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], + &[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], + &[0x00, 0x00, 0x81, 0xbf], + ] + .concat() +} diff --git a/crates/metal/src/render.rs b/crates/metal/src/render.rs index f407187..91f39ec 100644 --- a/crates/metal/src/render.rs +++ b/crates/metal/src/render.rs @@ -101,7 +101,43 @@ impl NativeCompute { colors, [width, height], clear, - sampled, + sampled.map(|(texture, sampler)| (texture.raw(), sampler)), + ) + .map(|(pixels, _)| pixels) + } + + /// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound + /// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the + /// sampler to fragment sampler slot 0. + /// + /// # Errors + /// + /// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level. + #[allow(clippy::too_many_arguments)] + pub fn render_rgba8_sampled_bc1( + &self, + source: &str, + entries: [&str; 2], + vertices: &[[f32; 4]; 3], + colors: &[[f32; 4]; 3], + extent: [usize; 2], + clear: [u8; 4], + texture: &Bc1Upload<'_>, + sampler: &crate::sampler::MetalSampler, + ) -> Result, MetalError> { + let level = texture + .subresource(0, 0) + .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; + self.validate_bc_extent(level.width, level.height, "BC1")?; + let bc1 = self.new_bc1_texture(&level)?; + self.render_rgba8_internal( + source, + entries, + vertices, + colors, + extent, + clear, + Some((&bc1, sampler)), ) .map(|(pixels, _)| pixels) } @@ -116,7 +152,7 @@ impl NativeCompute { [width, height]: [usize; 2], clear: [u8; 4], sampled: Option<( - &crate::texture_pipeline::MetalRgba8Texture, + &ProtocolObject, &crate::sampler::MetalSampler, )>, ) -> Result<(Vec, Option), MetalError> { @@ -228,7 +264,7 @@ impl NativeCompute { encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0); encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1); if let Some((tex, samp)) = sampled { - encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0); + encoder.setFragmentTexture_atIndex(Some(tex), 0); encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0); } encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3); diff --git a/crates/metal/tests/native/translated_bc1.rs b/crates/metal/tests/native/translated_bc1.rs new file mode 100644 index 0000000..387e4d4 --- /dev/null +++ b/crates/metal/tests/native/translated_bc1.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; +use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1}; + +use super::{context, native}; + +/// The translated `image_sample_lz` pixel stage samples a native BC1 +/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's +/// four blocks selects only its two endpoints, which expand exactly to 0 or +/// 255, so the image is known without a decoder: selector 1 (the second +/// endpoint) where `x == 0 || y == 3` within a block, else selector 0. +#[test] +fn translated_image_sample_lz_reads_bound_bc1_texture() { + let blocks: [[u8; 8]; 4] = [ + [0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue + [0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black + [0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta + [0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan + ]; + let endpoints: [[[u8; 4]; 2]; 4] = [ + [[255, 0, 0, 255], [0, 0, 255, 255]], + [[0, 255, 0, 255], [0, 0, 0, 255]], + [[255, 255, 255, 255], [255, 0, 255, 255]], + [[255, 255, 0, 255], [0, 255, 255, 255]], + ]; + let mut expected = Vec::new(); + for y in 0..8 { + for x in 0..8 { + let selector = usize::from(x % 4 == 0 || y % 4 == 3); + expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]); + } + } + for (index, block) in blocks.into_iter().enumerate() { + let (bx, by) = (index % 2 * 4, index / 2 * 4); + for (i, texel) in decode_bc1(block).iter().enumerate() { + let at = ((by + i / 4) * 8 + bx + i % 4) * 4; + assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}"); + } + } + + let ps: Vec = [ + &[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x + &[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x + &[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y + &[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y + &[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz + &[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0 + &[0x00, 0x00, 0x81, 0xbf], // s_endpgm + ] + .concat(); + let compiled = compile_graphics( + Architecture::Gfx1030, + include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"), + &ps, + ) + .expect("compile translated image_sample_lz shader"); + let gpu = context(); + let upload = Bc1Upload::new( + blocks.as_flattened(), + Bc1UploadDesc { + width: 8, + height: 8, + mips: 1, + layers: 1, + format: 1, + usage: 1, + row_pitch: 16, + slice_pitch: 32, + }, + ) + .expect("valid BC1 upload"); + let sampler = native(xenora_metal::sampler::MetalSampler::new( + gpu.device(), + SamplerDesc::nearest_clamp(), + )); + // Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8). + let positions = [ + [-1.0, -1.0, 0.5, 1.0], + [3.0, -1.0, 0.5, 1.0], + [-1.0, 3.0, 0.5, 1.0], + ]; + let uvs = [ + [0.0, 1.0, 0.0, 1.0], + [2.0, 1.0, 0.0, 1.0], + [0.0, -1.0, 0.0, 1.0], + ]; + let pixels = native(gpu.render_rgba8_sampled_bc1( + &compiled.msl, + [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT], + &positions, + &uvs, + [8, 8], + [19, 43, 93, 251], + &upload, + &sampler, + )); + assert_eq!(pixels, expected); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 933cb97..0cdce52 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -26,6 +26,8 @@ mod texture_bc_alpha; mod texture_bc_channel; #[path = "native/texture_sampling.rs"] mod texture_sampling; +#[path = "native/translated_bc1.rs"] +mod translated_bc1; #[path = "native/translated_render.rs"] mod translated_render; diff --git a/docs/interfaces.md b/docs/interfaces.md index ecef73a..5586c5e 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -511,3 +511,47 @@ compare function. Colour and the stored depth are both read back. These passes are checked on the GPU with Metal validation against expectations derived independently from the public semantics; synthetic fixtures only. + +### Guest texture binding (descriptor tables) + +`GraphicsContext` lets a guest command list sample one texture in the pixel +stage through a D3D12-shaped binding. A draw samples only if a root signature +is bound. Draws without one keep the flat-colour path. The supported subset +is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the +object is created, or with an error at execution. A rejected draw never +reaches the backend. Draws recorded before it in the same list have already +run. + +| Object | Supported | +| --- | --- | +| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. | +| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. | +| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. | +| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. | +| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. | +| `cmd_set_descriptor_heaps` | At most one heap of each type. | +| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. | + +Descriptor handles follow D3D12 pointer arithmetic: the heap start plus +`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the +value). `offset` returns `None` rather than carry into the next heap. CPU and +GPU handles are separate spaces. A textured draw is a `DrawInstanced` of +one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or +instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes +`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position +at byte 0 and a float4 texture coordinate at byte 16, with a stride of at +least 32. Textured indexed draws are unsupported. + +The native backend receives a `TexturedDraw` with the bound level and must +bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of +the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1` +binds a BC1 level natively for that purpose. The software reference has no +clipping or depth test. A pixel is covered when its centre lies inside or on +an edge of the triangle. The texture coordinate is interpolated affinely, so +`w = 1` is required, and point sampled with +`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the +spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two +interpolated palette entries differently (171/84 against 170/85, measured +on an M5 Pro), so the tests use endpoint colours only. Pipeline +state objects do not exist yet, so the backend, not the guest, chooses the +pixel shader. These entry points are not yet wired to guest imports. diff --git a/scripts/test-gpu.sh b/scripts/test-gpu.sh index 9627db8..d7be36b 100755 --- a/scripts/test-gpu.sh +++ b/scripts/test-gpu.sh @@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \ --nocapture --test-threads=1 +# Guest draws sample textures bound through descriptor tables (#303). +cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures --no-run +timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures -- \ + --nocapture --test-threads=1 + # The native app interface runs the trusted fixture's guest draw on Metal. cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \