mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 00:51:11 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
817a95b419 | ||
|
|
33c025a785 | ||
|
|
c0cbc2f787 | ||
|
|
e8b0a380e9 | ||
|
|
df3b9674a3 | ||
|
|
db50deb9f7 | ||
|
|
76679a9c05 | ||
|
|
6785cb04e3 | ||
|
|
99c8331576 | ||
|
|
077a215d49 | ||
|
|
3c710b53ba | ||
|
|
4886e9cd80 | ||
|
|
7aa8166cf2 | ||
|
|
c107f3a43f |
No files matched your search
@@ -11,6 +11,8 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
|
||||
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
|
||||
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
|
||||
|
||||
@@ -246,6 +246,15 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
|
||||
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let start = self.cpu.rip;
|
||||
let result = self.execute_instruction();
|
||||
if result.is_err() {
|
||||
self.cpu.rip = start;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
|
||||
@@ -112,7 +112,19 @@ impl DbtEngine {
|
||||
|
||||
// Look up or translate block at cpu.rip
|
||||
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
|
||||
let block_fn_ptr = match self.get_or_compile_block(cpu.rip, memory, block_limit) {
|
||||
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
|
||||
// A decode failure can belong to a later instruction in the block.
|
||||
// Execute the current instruction alone so earlier effects retire
|
||||
// and an earlier data fault takes precedence over speculative fetch.
|
||||
if block_limit > 1
|
||||
&& matches!(
|
||||
block,
|
||||
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
|
||||
)
|
||||
{
|
||||
block = self.get_or_compile_block(cpu.rip, memory, 1);
|
||||
}
|
||||
let block_fn_ptr = match block {
|
||||
Ok(ptr) => ptr,
|
||||
Err(reason) => {
|
||||
return ExecutionResult {
|
||||
@@ -1661,6 +1673,58 @@ mod tests {
|
||||
assert_eq!(unsupported.instructions_executed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_store_survives_the_next_fault_or_budget_boundary() {
|
||||
for native in [false, true] {
|
||||
for (tail, fault) in [
|
||||
(&[0xcc][..], ExitReason::IllegalInstruction(0xcc)),
|
||||
(
|
||||
&[0xb8, 1][..],
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(ENTRY + 5)),
|
||||
),
|
||||
(
|
||||
&[0x48, 0x8b, 0x02, 0xf4][..],
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(0x4000)),
|
||||
),
|
||||
] {
|
||||
for budget in [0, 1, 16] {
|
||||
// mov [rcx], rax; then an illegal, truncated or faulting instruction.
|
||||
let code = [&[0x48, 0x89, 0x01][..], tail].concat();
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
memory
|
||||
.map_region(0x3000, 8, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
cpu.set(Register::Rax, 0x1234);
|
||||
cpu.set(Register::Rcx, 0x3000);
|
||||
cpu.set(Register::Rdx, 0x4000);
|
||||
let mut expected = cpu.clone();
|
||||
if budget > 0 {
|
||||
expected.rip += 3;
|
||||
}
|
||||
let result = if native {
|
||||
engine.run(&mut cpu, &mut memory, budget)
|
||||
} else {
|
||||
crate::cpu::Interpreter::new(cpu, &mut memory, budget).run()
|
||||
};
|
||||
assert_eq!(result.instructions_executed, budget.min(1));
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
if budget <= 1 {
|
||||
ExitReason::StepLimitExceeded
|
||||
} else {
|
||||
fault
|
||||
}
|
||||
);
|
||||
assert_eq!(result.final_state, expected);
|
||||
assert_eq!(
|
||||
memory.read_u64(0x3000).unwrap(),
|
||||
if budget == 0 { 0 } else { 0x1234 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hlt_preserves_first_memory_fault() {
|
||||
let code = [
|
||||
|
||||
@@ -117,6 +117,11 @@ pub enum GraphicsError {
|
||||
DeviceCreationFailure(String),
|
||||
BackendError(String),
|
||||
NativeMetalRequired,
|
||||
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
|
||||
InvalidIndexFormat(u32),
|
||||
/// An indexed draw reads past its index buffer or fetches a vertex,
|
||||
/// after applying the base vertex, outside its vertex buffer.
|
||||
IndexOutOfRange,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for GraphicsError {
|
||||
@@ -140,6 +145,10 @@ impl std::fmt::Display for GraphicsError {
|
||||
f,
|
||||
"native Metal backend required but not provided or failed"
|
||||
),
|
||||
Self::InvalidIndexFormat(format) => {
|
||||
write!(f, "unsupported index buffer format {format}")
|
||||
}
|
||||
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,6 +182,32 @@ pub struct GraphicsResource {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum IndexFormat {
|
||||
R16Uint,
|
||||
R32Uint,
|
||||
}
|
||||
|
||||
impl IndexFormat {
|
||||
/// The format for a DXGI format code: `R16_UINT` (57) or `R32_UINT` (42).
|
||||
pub const fn from_dxgi(format: u32) -> Option<Self> {
|
||||
match format {
|
||||
57 => Some(Self::R16Uint),
|
||||
42 => Some(Self::R32Uint),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes per index.
|
||||
pub const fn size(self) -> usize {
|
||||
match self {
|
||||
Self::R16Uint => 2,
|
||||
Self::R32Uint => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Primitive Draw Command recorded in a Command List.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphicsCommand {
|
||||
@@ -200,6 +235,18 @@ pub enum GraphicsCommand {
|
||||
start_vertex_location: u32,
|
||||
start_instance_location: u32,
|
||||
},
|
||||
SetIndexBuffer {
|
||||
resource: GraphicsHandle,
|
||||
offset: usize,
|
||||
format: IndexFormat,
|
||||
},
|
||||
DrawIndexedInstanced {
|
||||
index_count_per_instance: u32,
|
||||
instance_count: u32,
|
||||
start_index_location: u32,
|
||||
base_vertex_location: i32,
|
||||
start_instance_location: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Command List in recording or closed state.
|
||||
@@ -548,6 +595,72 @@ impl GraphicsContext {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record set index buffer. `format` is a DXGI format code; only
|
||||
/// `R16_UINT` (57) and `R32_UINT` (42) are index formats.
|
||||
pub fn cmd_set_index_buffer(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
resource: GraphicsHandle,
|
||||
offset: usize,
|
||||
format: u32,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
let format =
|
||||
IndexFormat::from_dxgi(format).ok_or(GraphicsError::InvalidIndexFormat(format))?;
|
||||
let res = self
|
||||
.resources
|
||||
.get(&resource)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
if !offset.is_multiple_of(format.size()) || offset > res.data.len() {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
cmd_list.commands.push(GraphicsCommand::SetIndexBuffer {
|
||||
resource,
|
||||
offset,
|
||||
format,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record draw indexed instanced. Each draw renders one triangle once: at
|
||||
/// execution the index count must be 0 or 3, the instance count 0 or 1 and
|
||||
/// the start instance 0, or the draw is rejected; a zero index or instance
|
||||
/// count draws nothing. Index values are ordinary triangle-list indices
|
||||
/// (no primitive restart), range checked after adding the base vertex.
|
||||
pub fn cmd_draw_indexed_instanced(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
index_count_per_instance: u32,
|
||||
instance_count: u32,
|
||||
start_index_location: u32,
|
||||
base_vertex_location: i32,
|
||||
start_instance_location: u32,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
cmd_list
|
||||
.commands
|
||||
.push(GraphicsCommand::DrawIndexedInstanced {
|
||||
index_count_per_instance,
|
||||
instance_count,
|
||||
start_index_location,
|
||||
base_vertex_location,
|
||||
start_instance_location,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close command list.
|
||||
pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
@@ -649,6 +762,8 @@ impl GraphicsContext {
|
||||
let mut target_handle: Option<GraphicsHandle> = None;
|
||||
let mut vertex_resource: Option<GraphicsHandle> = None;
|
||||
let mut vertex_offset = 0usize;
|
||||
let mut vertex_stride = 0usize;
|
||||
let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None;
|
||||
let mut rendered_output: Option<Vec<u8>> = None;
|
||||
let mut draw_count = 0usize;
|
||||
|
||||
@@ -679,10 +794,57 @@ impl GraphicsContext {
|
||||
viewport = (*width, *height);
|
||||
}
|
||||
GraphicsCommand::SetVertexBuffer {
|
||||
resource, offset, ..
|
||||
resource,
|
||||
offset,
|
||||
stride,
|
||||
} => {
|
||||
vertex_resource = Some(*resource);
|
||||
vertex_offset = *offset;
|
||||
vertex_stride = *stride;
|
||||
}
|
||||
GraphicsCommand::SetIndexBuffer {
|
||||
resource,
|
||||
offset,
|
||||
format,
|
||||
} => index_buffer = Some((*resource, *offset, *format)),
|
||||
GraphicsCommand::DrawIndexedInstanced {
|
||||
index_count_per_instance,
|
||||
instance_count,
|
||||
start_index_location,
|
||||
base_vertex_location,
|
||||
start_instance_location,
|
||||
} => {
|
||||
if !matches!(index_count_per_instance, 0 | 3)
|
||||
|| *instance_count > 1
|
||||
|| *start_instance_location != 0
|
||||
{
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
if *index_count_per_instance == 0 || *instance_count == 0 {
|
||||
continue;
|
||||
}
|
||||
let vertices = self.fetch_indexed_triangle(
|
||||
memory,
|
||||
index_buffer,
|
||||
(vertex_resource, vertex_offset, vertex_stride),
|
||||
*start_index_location,
|
||||
*base_vertex_location,
|
||||
)?;
|
||||
draw_count += 1;
|
||||
let pixels = if let Some(renderer) = backend_renderer {
|
||||
renderer(&vertices, viewport, clear_color)?
|
||||
} else if backend_id == GraphicsBackendId::MetalNative {
|
||||
return Err(GraphicsError::NativeMetalRequired);
|
||||
} else {
|
||||
Self::execute_software_reference_draw(&vertices, viewport, clear_color)?
|
||||
};
|
||||
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);
|
||||
}
|
||||
GraphicsCommand::DrawInstanced {
|
||||
vertex_count_per_instance,
|
||||
@@ -761,6 +923,84 @@ impl GraphicsContext {
|
||||
})
|
||||
}
|
||||
|
||||
/// The three float4 positions one indexed triangle fetches: index `k` is
|
||||
/// read at `offset + (start + k) * size` of the index buffer, and vertex
|
||||
/// `index + base_vertex` at `offset + vertex * stride` of the vertex buffer.
|
||||
fn fetch_indexed_triangle(
|
||||
&self,
|
||||
memory: &GuestMemory,
|
||||
index_buffer: Option<(GraphicsHandle, usize, IndexFormat)>,
|
||||
(vertex_resource, vertex_offset, vertex_stride): (Option<GraphicsHandle>, usize, usize),
|
||||
start: u32,
|
||||
base_vertex: i32,
|
||||
) -> Result<[[f32; 4]; 3], GraphicsError> {
|
||||
let resource = |handle: Option<GraphicsHandle>| {
|
||||
handle
|
||||
.and_then(|handle| self.resources.get(&handle))
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)
|
||||
};
|
||||
let (index_handle, index_offset, format) =
|
||||
index_buffer.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
let index_res = resource(Some(index_handle))?;
|
||||
let vertex_res = resource(vertex_resource)?;
|
||||
if vertex_stride < 16 {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
let size = format.size();
|
||||
let mut raw_indices = [0u8; 12];
|
||||
let raw_indices = &mut raw_indices[..3 * size];
|
||||
let first = (start as usize)
|
||||
.checked_mul(size)
|
||||
.and_then(|bytes| bytes.checked_add(index_offset))
|
||||
.ok_or(GraphicsError::IndexOutOfRange)?;
|
||||
Self::read_resource(index_res, memory, first, raw_indices)?;
|
||||
let mut vertices = [[0.0f32; 4]; 3];
|
||||
for (row, index) in vertices.iter_mut().zip(raw_indices.chunks_exact(size)) {
|
||||
let index = if size == 2 {
|
||||
u32::from(u16::from_le_bytes([index[0], index[1]]))
|
||||
} else {
|
||||
u32::from_le_bytes(index.try_into().unwrap())
|
||||
};
|
||||
let vertex = usize::try_from(i64::from(index) + i64::from(base_vertex))
|
||||
.map_err(|_| GraphicsError::IndexOutOfRange)?;
|
||||
let at = vertex
|
||||
.checked_mul(vertex_stride)
|
||||
.and_then(|bytes| bytes.checked_add(vertex_offset))
|
||||
.ok_or(GraphicsError::IndexOutOfRange)?;
|
||||
let mut raw = [0u8; 16];
|
||||
Self::read_resource(vertex_res, memory, at, &mut raw)?;
|
||||
for (value, bytes) in row.iter_mut().zip(raw.as_chunks::<4>().0) {
|
||||
*value = f32::from_le_bytes(*bytes);
|
||||
}
|
||||
}
|
||||
Ok(vertices)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
res: &GraphicsResource,
|
||||
memory: &GuestMemory,
|
||||
offset: usize,
|
||||
out: &mut [u8],
|
||||
) -> Result<(), GraphicsError> {
|
||||
let end = offset
|
||||
.checked_add(out.len())
|
||||
.filter(|&end| end <= res.data.len())
|
||||
.ok_or(GraphicsError::IndexOutOfRange)?;
|
||||
match res.guest_backing_addr {
|
||||
Some(guest_addr) => {
|
||||
let address = guest_addr
|
||||
.checked_add(offset as u64)
|
||||
.filter(|address| address.checked_add(out.len() as u64).is_some())
|
||||
.ok_or(GraphicsError::IndexOutOfRange)?;
|
||||
memory.read_bytes(address, out)?;
|
||||
}
|
||||
None => out.copy_from_slice(&res.data[offset..end]),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Software reference rasterizer for deterministic test verification when GPU tests are off.
|
||||
pub fn execute_software_reference_draw(
|
||||
vertices: &[[f32; 4]; 3],
|
||||
|
||||
@@ -590,3 +590,414 @@ fn test_guest_dbt_graphics_pipeline_metal_render_dual_inputs() {
|
||||
let expected_clear = [10, 20, 30, 255];
|
||||
assert_eq!(pixels2, expected_clear.repeat(12));
|
||||
}
|
||||
|
||||
/// Guest addresses of the indexed-draw fixtures.
|
||||
const INDEXED_VB: u64 = 0x7000_0000;
|
||||
const INDEXED_IB: u64 = 0x7100_0000;
|
||||
/// Vertex stride of the indexed fixtures: a float4 position and 16 unused bytes.
|
||||
const INDEXED_STRIDE: usize = 32;
|
||||
|
||||
/// Triangle (4,3) (16,4) (6,16) of a 16x16 target in clip space; no pixel
|
||||
/// centre lies on one of its edges.
|
||||
const INDEXED_TRIANGLE: [[f32; 4]; 3] = [
|
||||
[-0.5, 0.625, 0.5, 1.0],
|
||||
[1.0, 0.5, 0.5, 1.0],
|
||||
[-0.25, -1.0, 0.5, 1.0],
|
||||
];
|
||||
|
||||
/// Ten vertices: the triangle at vertices 5, 7 and 2, and decoys elsewhere,
|
||||
/// so a wrong fetch passes different positions.
|
||||
fn indexed_vertices() -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
for vertex in 0..10 {
|
||||
let position = match vertex {
|
||||
5 => INDEXED_TRIANGLE[0],
|
||||
7 => INDEXED_TRIANGLE[1],
|
||||
2 => INDEXED_TRIANGLE[2],
|
||||
other => [other as f32 * 0.125 - 0.75, -0.5, 0.5, 1.0],
|
||||
};
|
||||
for value in position {
|
||||
bytes.extend(value.to_le_bytes());
|
||||
}
|
||||
bytes.extend([0xAB; 16]);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
struct IndexedRig {
|
||||
ctx: GraphicsContext,
|
||||
memory: GuestMemory,
|
||||
queue: GraphicsHandle,
|
||||
alloc: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
vb: GraphicsHandle,
|
||||
ib16: GraphicsHandle,
|
||||
ib32: GraphicsHandle,
|
||||
}
|
||||
|
||||
/// A context with guest-backed vertex and index buffers. The 16-bit buffer
|
||||
/// holds 9, 9, 6, 8, 3, 5, 0 and the 32-bit buffer 9, 3, 5, 0, 7 and three
|
||||
/// indices above 16 bits, 0x10003, 0x10005, 0x10000.
|
||||
fn indexed_rig() -> IndexedRig {
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
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();
|
||||
let buffer = |ctx: &mut GraphicsContext, bytes: usize, addr| {
|
||||
let desc = ResourceDesc {
|
||||
dimension: ResourceDimension::Buffer,
|
||||
width: bytes as u64,
|
||||
height: 1,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: false,
|
||||
};
|
||||
ctx.create_committed_resource(device, desc, ResourceStates::COMMON, Some(addr))
|
||||
.unwrap()
|
||||
};
|
||||
let vertices = indexed_vertices();
|
||||
let ib16: Vec<u8> = [9u16, 9, 6, 8, 3, 5, 0]
|
||||
.iter()
|
||||
.flat_map(|index| index.to_le_bytes())
|
||||
.collect();
|
||||
let ib32: Vec<u8> = [9u32, 3, 5, 0, 7, 0x1_0003, 0x1_0005, 0x1_0000]
|
||||
.iter()
|
||||
.flat_map(|index| index.to_le_bytes())
|
||||
.collect();
|
||||
let vb = buffer(&mut ctx, vertices.len(), INDEXED_VB);
|
||||
let ib16_handle = buffer(&mut ctx, ib16.len(), INDEXED_IB);
|
||||
let ib32_handle = buffer(&mut ctx, ib32.len(), INDEXED_IB + 0x1000);
|
||||
let mut memory = GuestMemory::new();
|
||||
for (addr, bytes) in [
|
||||
(INDEXED_VB, &vertices),
|
||||
(INDEXED_IB, &ib16),
|
||||
(INDEXED_IB + 0x1000, &ib32),
|
||||
] {
|
||||
memory
|
||||
.map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes)
|
||||
.unwrap();
|
||||
}
|
||||
IndexedRig {
|
||||
ctx,
|
||||
memory,
|
||||
queue,
|
||||
alloc,
|
||||
list,
|
||||
vb,
|
||||
ib16: ib16_handle,
|
||||
ib32: ib32_handle,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one indexed draw (16x16 viewport, the rig's vertex buffer) and run it.
|
||||
fn run_indexed(
|
||||
rig: &mut IndexedRig,
|
||||
index_buffer: (GraphicsHandle, usize, u32),
|
||||
draw: (u32, u32, u32, i32),
|
||||
) -> Result<xenora_loader::graphics::ExecutionOutcome, GraphicsError> {
|
||||
let ctx = &mut rig.ctx;
|
||||
ctx.reset_command_list(rig.list, rig.alloc)?;
|
||||
ctx.cmd_set_viewport(rig.list, 16, 16)?;
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)?;
|
||||
ctx.cmd_set_index_buffer(rig.list, index_buffer.0, index_buffer.1, index_buffer.2)?;
|
||||
let (count, instances, start, base) = draw;
|
||||
ctx.cmd_draw_indexed_instanced(rig.list, count, instances, start, base, 0)?;
|
||||
ctx.close_command_list(rig.list)?;
|
||||
ctx.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
}
|
||||
|
||||
const R16_UINT: u32 = 57;
|
||||
const R32_UINT: u32 = 42;
|
||||
|
||||
/// Start index, signed base vertex, index size and buffer offset all select
|
||||
/// vertices 5, 7, 2: the backend receives exactly the triangle's positions
|
||||
/// (literal values), never a decoy.
|
||||
#[test]
|
||||
fn test_d3d12_indexed_draw_fetches_start_and_base_vertex() {
|
||||
let mut rig = indexed_rig();
|
||||
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let record = seen.clone();
|
||||
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
|
||||
record.lock().unwrap().push(*vtx);
|
||||
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
|
||||
});
|
||||
let (ib16, ib32) = (rig.ib16, rig.ib32);
|
||||
for (name, buffer, draw) in [
|
||||
// 16-bit indices 3, 5, 0 at index 4, base vertex +2.
|
||||
("u16 positive base", (ib16, 0, R16_UINT), (3, 1, 4, 2)),
|
||||
// 16-bit indices 6, 8, 3 at index 2, base vertex -1.
|
||||
("u16 negative base", (ib16, 0, R16_UINT), (3, 1, 2, -1)),
|
||||
// The same through a buffer offset of one index (2 bytes).
|
||||
("u16 buffer offset", (ib16, 2, R16_UINT), (3, 1, 1, -1)),
|
||||
// 32-bit indices 3, 5, 0 at index 1, base vertex +2.
|
||||
("u32 positive base", (ib32, 0, R32_UINT), (3, 1, 1, 2)),
|
||||
// 32-bit indices above 16 bits, base vertex -65534: all 32 bits count.
|
||||
("u32 wide indices", (ib32, 0, R32_UINT), (3, 1, 5, -65534)),
|
||||
] {
|
||||
seen.lock().unwrap().clear();
|
||||
let outcome = run_indexed(&mut rig, buffer, draw).expect(name);
|
||||
assert_eq!(outcome.draw_count, 1, "{name}");
|
||||
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE], "{name}");
|
||||
assert_eq!(
|
||||
outcome.pixels,
|
||||
GraphicsContext::execute_software_reference_draw(
|
||||
&INDEXED_TRIANGLE,
|
||||
(16, 16),
|
||||
[0, 0, 0, 255]
|
||||
)
|
||||
.unwrap(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
// A vertex buffer offset of two vertices does the base vertex's work.
|
||||
seen.lock().unwrap().clear();
|
||||
let ctx = &mut rig.ctx;
|
||||
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
ctx.cmd_set_viewport(rig.list, 16, 16).unwrap();
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 2 * INDEXED_STRIDE, INDEXED_STRIDE)
|
||||
.unwrap();
|
||||
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
|
||||
.unwrap();
|
||||
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 0, 0)
|
||||
.unwrap();
|
||||
ctx.close_command_list(rig.list).unwrap();
|
||||
let outcome = ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
.expect("vertex buffer offset");
|
||||
assert_eq!(outcome.draw_count, 1);
|
||||
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE]);
|
||||
// Zero indices or zero instances draw nothing and never call the backend.
|
||||
seen.lock().unwrap().clear();
|
||||
for draw in [(0, 1, 0, 0), (3, 0, 0, 0)] {
|
||||
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), draw).unwrap();
|
||||
assert_eq!(outcome.draw_count, 0);
|
||||
}
|
||||
assert!(seen.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Index format, offset, count, range, negative fetch and unknown or missing
|
||||
/// buffers each fail with a typed error, and nothing reaches the backend.
|
||||
#[test]
|
||||
fn test_d3d12_indexed_draw_errors() {
|
||||
let mut rig = indexed_rig();
|
||||
let calls = Arc::new(std::sync::Mutex::new(0usize));
|
||||
let counter = calls.clone();
|
||||
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
|
||||
*counter.lock().unwrap() += 1;
|
||||
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
|
||||
});
|
||||
let (ib16, ib32) = (rig.ib16, rig.ib32);
|
||||
let unknown = GraphicsHandle {
|
||||
id: 999,
|
||||
generation: 1,
|
||||
};
|
||||
for format in [0, 41, 56, 58, 28] {
|
||||
assert_eq!(
|
||||
run_indexed(&mut rig, (ib16, 0, format), (3, 1, 0, 0)).unwrap_err(),
|
||||
GraphicsError::InvalidIndexFormat(format)
|
||||
);
|
||||
}
|
||||
for (name, buffer, draw, error) in [
|
||||
(
|
||||
"misaligned offset",
|
||||
(ib32, 2, R32_UINT),
|
||||
(3, 1, 0, 0),
|
||||
GraphicsError::InvalidDescriptor,
|
||||
),
|
||||
(
|
||||
"offset past buffer",
|
||||
(ib16, 16, R16_UINT),
|
||||
(3, 1, 0, 0),
|
||||
GraphicsError::InvalidDescriptor,
|
||||
),
|
||||
(
|
||||
"unknown buffer",
|
||||
(unknown, 0, R16_UINT),
|
||||
(3, 1, 0, 0),
|
||||
GraphicsError::InvalidResourceHandle,
|
||||
),
|
||||
(
|
||||
"count not one triangle",
|
||||
(ib16, 0, R16_UINT),
|
||||
(6, 1, 0, 0),
|
||||
GraphicsError::InvalidDescriptor,
|
||||
),
|
||||
(
|
||||
"bad count with zero instances",
|
||||
(ib16, 0, R16_UINT),
|
||||
(6, 0, 0, 0),
|
||||
GraphicsError::InvalidDescriptor,
|
||||
),
|
||||
(
|
||||
"two instances",
|
||||
(ib16, 0, R16_UINT),
|
||||
(3, 2, 4, 2),
|
||||
GraphicsError::InvalidDescriptor,
|
||||
),
|
||||
(
|
||||
"indices past buffer",
|
||||
(ib16, 0, R16_UINT),
|
||||
(3, 1, 5, 0),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
),
|
||||
(
|
||||
"start overflow",
|
||||
(ib32, 0, R32_UINT),
|
||||
(3, 1, u32::MAX, 0),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
),
|
||||
(
|
||||
"negative vertex",
|
||||
(ib16, 0, R16_UINT),
|
||||
(3, 1, 4, -1),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
),
|
||||
(
|
||||
"vertex past buffer",
|
||||
(ib16, 0, R16_UINT),
|
||||
(3, 1, 0, 1),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
),
|
||||
(
|
||||
"base overflow",
|
||||
(ib32, 0, R32_UINT),
|
||||
(3, 1, 0, i32::MAX),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
),
|
||||
] {
|
||||
let got = run_indexed(&mut rig, buffer, draw);
|
||||
assert_eq!(got.unwrap_err(), error, "{name}");
|
||||
}
|
||||
|
||||
// A draw without an index buffer is rejected at execution.
|
||||
let ctx = &mut rig.ctx;
|
||||
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
|
||||
.unwrap();
|
||||
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0)
|
||||
.unwrap();
|
||||
ctx.close_command_list(rig.list).unwrap();
|
||||
assert_eq!(
|
||||
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
|
||||
Err(GraphicsError::InvalidResourceHandle)
|
||||
);
|
||||
// A stride smaller than one float4 position is rejected.
|
||||
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, 12).unwrap();
|
||||
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
|
||||
.unwrap();
|
||||
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 0)
|
||||
.unwrap();
|
||||
ctx.close_command_list(rig.list).unwrap();
|
||||
assert_eq!(
|
||||
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
|
||||
Err(GraphicsError::InvalidDescriptor)
|
||||
);
|
||||
// A nonzero start instance is rejected.
|
||||
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
|
||||
.unwrap();
|
||||
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
|
||||
.unwrap();
|
||||
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 1)
|
||||
.unwrap();
|
||||
ctx.close_command_list(rig.list).unwrap();
|
||||
assert_eq!(
|
||||
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
|
||||
Err(GraphicsError::InvalidDescriptor)
|
||||
);
|
||||
// An index buffer whose guest backing would wrap the address space is
|
||||
// rejected, not read at a wrapped address.
|
||||
let device = ctx.create_device().unwrap();
|
||||
// The read's start wraps (start 8 at 2 bytes each), then only its end does.
|
||||
for (guest_addr, start) in [(u64::MAX - 8, 8), (u64::MAX - 2, 0)] {
|
||||
let wrapping = rig
|
||||
.ctx
|
||||
.create_committed_resource(
|
||||
device,
|
||||
ResourceDesc {
|
||||
dimension: ResourceDimension::Buffer,
|
||||
width: 64,
|
||||
height: 1,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: false,
|
||||
},
|
||||
ResourceStates::COMMON,
|
||||
Some(guest_addr),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
run_indexed(&mut rig, (wrapping, 0, R16_UINT), (3, 1, start, 0)).unwrap_err(),
|
||||
GraphicsError::IndexOutOfRange,
|
||||
"guest address {guest_addr:#x} start {start}"
|
||||
);
|
||||
}
|
||||
// No rejected draw reached the backend.
|
||||
assert_eq!(*calls.lock().unwrap(), 0);
|
||||
}
|
||||
|
||||
/// The loader's indexed fetch feeds the native Metal renderer: the GPU image
|
||||
/// of the fetched triangle equals the image of the literal triangle.
|
||||
#[test]
|
||||
#[cfg_attr(
|
||||
not(feature = "gpu-tests"),
|
||||
ignore = "needs native Metal device; run scripts/test-gpu.sh"
|
||||
)]
|
||||
fn test_d3d12_indexed_draw_native_metal() {
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
|
||||
let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
|
||||
let msl = compile_graphics(Architecture::Gfx1030, vs_bytes, ps_bytes)
|
||||
.expect("compile graphics RDNA2 shaders")
|
||||
.msl;
|
||||
let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device"));
|
||||
let render = {
|
||||
let gpu = gpu.clone();
|
||||
let msl = msl.clone();
|
||||
move |vtx: &[[f32; 4]; 3], vp: (usize, usize), cc: [u8; 4]| {
|
||||
gpu.render_rgba8(
|
||||
&msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
vtx,
|
||||
&[[0.0; 4]; 3],
|
||||
[vp.0, vp.1],
|
||||
cc,
|
||||
)
|
||||
.map_err(|e| GraphicsError::BackendError(format!("Metal GPU error: {e:?}")))
|
||||
}
|
||||
};
|
||||
let direct = render(&INDEXED_TRIANGLE, (16, 16), [0, 0, 0, 255]).expect("direct render");
|
||||
let mut rig = indexed_rig();
|
||||
rig.ctx.set_metal_backend(render);
|
||||
let ib16 = rig.ib16;
|
||||
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), (3, 1, 2, -1)).expect("indexed");
|
||||
assert_eq!(outcome.backend, GraphicsBackendId::MetalNative);
|
||||
assert_eq!(outcome.pixels, direct);
|
||||
// The constant shader paints the covered pixels red; the CPU rasteriser
|
||||
// agrees pixel for pixel, and the triangle covers some but not all pixels.
|
||||
let reference = GraphicsContext::execute_software_reference_draw(
|
||||
&INDEXED_TRIANGLE,
|
||||
(16, 16),
|
||||
[0, 0, 0, 255],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(outcome.pixels, reference);
|
||||
let red = outcome
|
||||
.pixels
|
||||
.chunks(4)
|
||||
.filter(|p| *p == [255, 0, 0, 255])
|
||||
.count();
|
||||
assert!((1..256).contains(&red), "{red} red pixels");
|
||||
println!("indexed native Metal draw: {red} of 256 pixels covered");
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
|
||||
#[test]
|
||||
fn native_indirect_transfers_commit_before_target_fetch() {
|
||||
const ENTRY: u64 = 0x2000;
|
||||
const SLOT: u64 = 0x1800;
|
||||
const TARGET: u64 = 0x3000;
|
||||
const STACK: u64 = 0x4000;
|
||||
const SENTINEL: u64 = 0xabcd_1234;
|
||||
|
||||
// R9 or [RIP - 0x806]. Both memory operands point back to SLOT.
|
||||
for (branch, call) in [
|
||||
(&[0x41, 0xff, 0xd1][..], true),
|
||||
(&[0x41, 0xff, 0xe1][..], false),
|
||||
(&[0xff, 0x15, 0xfa, 0xf7, 0xff, 0xff][..], true),
|
||||
(&[0xff, 0x25, 0xfa, 0xf7, 0xff, 0xff][..], false),
|
||||
] {
|
||||
for target_permissions in [
|
||||
Some(MemoryPermissions::READ_EXECUTE),
|
||||
Some(MemoryPermissions::READ_WRITE),
|
||||
None,
|
||||
] {
|
||||
let return_address = ENTRY + branch.len() as u64;
|
||||
let mut code = branch.to_vec();
|
||||
code.push(0xf4);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
SLOT,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&TARGET.to_le_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
STACK,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&SENTINEL.to_le_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
if let Some(permissions) = target_permissions {
|
||||
let target_opcode = if call { 0xc3 } else { 0xf4 };
|
||||
memory
|
||||
.map_region_with_data(TARGET, 1, permissions, &[target_opcode])
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(ENTRY, STACK + 8);
|
||||
cpu.set(Register::R9, TARGET);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let transfer = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(transfer.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(transfer.instructions_executed, 1);
|
||||
assert_eq!(cpu.rip, TARGET);
|
||||
let stack_after_transfer = if call { STACK } else { STACK + 8 };
|
||||
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
|
||||
assert_eq!(
|
||||
memory.read_u64(STACK).unwrap(),
|
||||
if call { return_address } else { SENTINEL }
|
||||
);
|
||||
|
||||
let resumed = engine.run(&mut cpu, &mut memory, 3);
|
||||
match target_permissions {
|
||||
Some(MemoryPermissions::READ_EXECUTE) => {
|
||||
assert_eq!(resumed.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(resumed.instructions_executed, if call { 2 } else { 1 });
|
||||
assert_eq!(cpu.rip, if call { return_address + 1 } else { TARGET + 1 });
|
||||
assert_eq!(cpu.get(Register::Rsp), STACK + 8);
|
||||
}
|
||||
permissions => {
|
||||
let fault = if permissions.is_some() {
|
||||
MemoryError::PermissionViolation {
|
||||
address: TARGET,
|
||||
required: "execute",
|
||||
}
|
||||
} else {
|
||||
MemoryError::UnmappedAddress(TARGET)
|
||||
};
|
||||
assert_eq!(resumed.exit_reason, ExitReason::MemoryFault(fault));
|
||||
assert_eq!(resumed.instructions_executed, 0);
|
||||
assert_eq!(cpu.rip, TARGET);
|
||||
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
|
||||
objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"MTLAllocation",
|
||||
"MTLArgument",
|
||||
"MTLBuffer",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
|
||||
@@ -23,7 +23,10 @@ use xenora_texture::{
|
||||
#[path = "render.rs"]
|
||||
mod render;
|
||||
|
||||
pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState};
|
||||
pub use render::{
|
||||
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer,
|
||||
IndexedDraw, IndexedPass,
|
||||
};
|
||||
|
||||
const MAX_THREADS_PER_GROUP: usize = 64;
|
||||
const MAX_GROUPS: usize = 64;
|
||||
|
||||
@@ -15,7 +15,7 @@ pub mod texture_pipeline;
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use compute::{
|
||||
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer,
|
||||
GuestBufferView, MetalError, NativeCompute, RunProfile,
|
||||
GuestBufferView, IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
|
||||
};
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
|
||||
+308
-2
@@ -7,8 +7,8 @@ use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
use objc2::sel;
|
||||
use objc2_metal::{
|
||||
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction,
|
||||
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction,
|
||||
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
|
||||
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLIndexType,
|
||||
MTLLoadAction, MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
|
||||
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
|
||||
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
|
||||
MTLTextureUsage, MTLViewport,
|
||||
@@ -717,6 +717,312 @@ impl NativeCompute {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_INDEXED_VERTICES: usize = 1024;
|
||||
const MAX_INDICES: usize = 4096;
|
||||
|
||||
/// An index buffer of 16- or 32-bit unsigned indices.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum IndexBuffer<'a> {
|
||||
U16(&'a [u16]),
|
||||
U32(&'a [u32]),
|
||||
}
|
||||
|
||||
impl IndexBuffer<'_> {
|
||||
fn len(self) -> usize {
|
||||
match self {
|
||||
Self::U16(indices) => indices.len(),
|
||||
Self::U32(indices) => indices.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self, position: usize) -> u32 {
|
||||
match self {
|
||||
Self::U16(indices) => u32::from(indices[position]),
|
||||
Self::U32(indices) => indices[position],
|
||||
}
|
||||
}
|
||||
|
||||
fn restart(self) -> u32 {
|
||||
match self {
|
||||
Self::U16(_) => u32::from(u16::MAX),
|
||||
Self::U32(_) => u32::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
fn size(self) -> usize {
|
||||
match self {
|
||||
Self::U16(_) => 2,
|
||||
Self::U32(_) => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// The indices packed into little-endian words, the last one zero-padded.
|
||||
fn words(self) -> Vec<u32> {
|
||||
match self {
|
||||
Self::U16(indices) => indices
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
u32::from(pair[0]) | pair.get(1).map_or(0, |&high| u32::from(high) << 16)
|
||||
})
|
||||
.collect(),
|
||||
Self::U32(indices) => indices.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One indexed triangle-list draw: `index_count` indices from `start_index`,
|
||||
/// each fetching vertex `index + base_vertex`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct IndexedDraw {
|
||||
pub start_index: usize,
|
||||
pub index_count: usize,
|
||||
pub base_vertex: i32,
|
||||
pub fill: DepthFill,
|
||||
}
|
||||
|
||||
/// An offscreen pass of up to 16 indexed draws, in order, into a cleared
|
||||
/// RGBA8Unorm target without depth attachment.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct IndexedPass<'a> {
|
||||
pub extent: [usize; 2],
|
||||
pub clear_color: [u8; 4],
|
||||
/// Up to 1024 clip-space float4 positions.
|
||||
pub vertices: &'a [[f32; 4]],
|
||||
/// Up to 4096 indices shared by every draw.
|
||||
pub indices: IndexBuffer<'a>,
|
||||
pub draws: &'a [IndexedDraw],
|
||||
/// As [`DepthPass::texture`], for [`DepthFill::Bc1Texture`] draws.
|
||||
pub texture: Option<&'a Bc1Upload<'a>>,
|
||||
}
|
||||
|
||||
impl NativeCompute {
|
||||
/// Draw an indexed offscreen pass and read back its colour.
|
||||
///
|
||||
/// Each draw is one native `drawIndexedPrimitives` call on the pass's
|
||||
/// index buffer with the draw's start offset and signed base vertex, so
|
||||
/// Metal itself fetches the vertices. Every fetched vertex is checked
|
||||
/// against the vertex buffer first: out-of-range fetches and raw
|
||||
/// primitive-restart values are rejected, never left to the GPU. Base vertex needs no capability query: the
|
||||
/// Apple family 7 that [`NativeCompute::new`] requires supports it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid extent, too many draws, vertices or
|
||||
/// indices, non-finite positions, an index count that is zero or not a
|
||||
/// multiple of 3, an index range past the buffer, a primitive-restart
|
||||
/// index, a fetched vertex outside the vertex buffer, a textured draw without texture, unavailable BC
|
||||
/// compression (operation `supportsBCTextureCompression`), or Metal setup
|
||||
/// or execution failure.
|
||||
pub fn render_indexed(&self, pass: &IndexedPass<'_>) -> Result<Vec<u8>, MetalError> {
|
||||
let [width, height] = pass.extent;
|
||||
let pixels = width
|
||||
.checked_mul(height)
|
||||
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
|
||||
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
|
||||
validate_indexed_pass(pass)?;
|
||||
let bc1 = pass
|
||||
.texture
|
||||
.map(|upload| {
|
||||
let level = upload.subresource(0, 0).map_err(|error| {
|
||||
MetalError::new("texture subresource", format!("{error:?}"))
|
||||
})?;
|
||||
self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
self.new_bc1_texture(&level)
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(DEPTH_SOURCE, &options)?;
|
||||
let vertex = find_function(&library, "depth_vertex")?;
|
||||
let flat = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_flat")?,
|
||||
MTLPixelFormat::Invalid,
|
||||
)?;
|
||||
let textured = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_textured")?,
|
||||
MTLPixelFormat::Invalid,
|
||||
)?;
|
||||
let color = self.new_target(
|
||||
PIXEL_FORMAT,
|
||||
width,
|
||||
height,
|
||||
MTLStorageMode::Shared,
|
||||
MTLTextureUsage::RenderTarget,
|
||||
)?;
|
||||
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
|
||||
// SAFETY: Slot zero is the only color attachment for this pass.
|
||||
let attachment = unsafe {
|
||||
pass_descriptor
|
||||
.colorAttachments()
|
||||
.objectAtIndexedSubscript(0)
|
||||
};
|
||||
attachment.setTexture(Some(&color));
|
||||
attachment.setLoadAction(MTLLoadAction::Clear);
|
||||
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
|
||||
attachment.setClearColor(MTLClearColor {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
});
|
||||
attachment.setStoreAction(MTLStoreAction::Store);
|
||||
let positions: Vec<u32> = pass
|
||||
.vertices
|
||||
.as_flattened()
|
||||
.iter()
|
||||
.map(|value| value.to_bits())
|
||||
.collect();
|
||||
let positions = self.new_buffer(&positions)?;
|
||||
let indices = self.new_buffer(&pass.indices.words())?;
|
||||
let index_type = match pass.indices {
|
||||
IndexBuffer::U16(_) => MTLIndexType::UInt16,
|
||||
IndexBuffer::U32(_) => MTLIndexType::UInt32,
|
||||
};
|
||||
let command = self.queue.commandBuffer().ok_or_else(|| {
|
||||
MetalError::new("commandBuffer", "render command buffer creation failed")
|
||||
})?;
|
||||
let encoder = command
|
||||
.renderCommandEncoderWithDescriptor(&pass_descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"renderCommandEncoderWithDescriptor",
|
||||
"render encoder creation failed",
|
||||
)
|
||||
})?;
|
||||
encoder.setViewport(MTLViewport {
|
||||
originX: 0.0,
|
||||
originY: 0.0,
|
||||
width: width as f64,
|
||||
height: height as f64,
|
||||
znear: 0.0,
|
||||
zfar: 1.0,
|
||||
});
|
||||
let extent = [width as f32, height as f32];
|
||||
for draw in pass.draws {
|
||||
// SAFETY: Validation proved that every index the draw reads lies
|
||||
// inside the index buffer, that the offset is a multiple of the
|
||||
// index size, and that every `index + base_vertex` names a float4
|
||||
// of the position buffer, the only memory the vertex stage reads.
|
||||
// Fragment constants are copied by Metal and match the declared
|
||||
// types. The texture, when bound, is a live BC1 texture of this
|
||||
// device; both buffers outlive the command.
|
||||
unsafe {
|
||||
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
|
||||
match draw.fill {
|
||||
DepthFill::Flat(rgba) => {
|
||||
encoder.setRenderPipelineState(&flat);
|
||||
let rgba = rgba.map(|value| f32::from(value) / 255.0);
|
||||
encoder.setFragmentBytes_length_atIndex(
|
||||
NonNull::from(&rgba).cast(),
|
||||
size_of_val(&rgba),
|
||||
0,
|
||||
);
|
||||
}
|
||||
DepthFill::Bc1Texture => {
|
||||
encoder.setRenderPipelineState(&textured);
|
||||
encoder.setFragmentTexture_atIndex(bc1.as_deref(), 0);
|
||||
encoder.setFragmentBytes_length_atIndex(
|
||||
NonNull::from(&extent).cast(),
|
||||
size_of_val(&extent),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance(
|
||||
MTLPrimitiveType::Triangle,
|
||||
draw.index_count,
|
||||
index_type,
|
||||
&indices,
|
||||
draw.start_index * pass.indices.size(),
|
||||
1,
|
||||
draw.base_vertex as isize,
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
encoder.endEncoding();
|
||||
complete_command(&command)?;
|
||||
|
||||
let mut output = vec![0; pixels * 4];
|
||||
// SAFETY: GPU writes have completed, and the initialized output
|
||||
// allocation fits the entire shared texture with tightly packed rows.
|
||||
unsafe {
|
||||
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
|
||||
NonNull::from(output.as_mut_slice()).cast(),
|
||||
width * 4,
|
||||
whole(width, height),
|
||||
0,
|
||||
);
|
||||
}
|
||||
Ok(output)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_indexed_pass(pass: &IndexedPass<'_>) -> Result<(), MetalError> {
|
||||
let invalid = |reason: String| Err(MetalError::new("indexed pass", reason));
|
||||
if pass.draws.len() > MAX_DEPTH_DRAWS {
|
||||
return invalid("expected at most 16 draws".to_owned());
|
||||
}
|
||||
if !(1..=MAX_INDEXED_VERTICES).contains(&pass.vertices.len())
|
||||
|| !(1..=MAX_INDICES).contains(&pass.indices.len())
|
||||
{
|
||||
return invalid("expected 1..=1024 vertices and 1..=4096 indices".to_owned());
|
||||
}
|
||||
if pass
|
||||
.vertices
|
||||
.as_flattened()
|
||||
.iter()
|
||||
.any(|value| !value.is_finite())
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"render input",
|
||||
"expected finite vertex data",
|
||||
));
|
||||
}
|
||||
for (number, draw) in pass.draws.iter().enumerate() {
|
||||
if draw.index_count == 0 || !draw.index_count.is_multiple_of(3) {
|
||||
return invalid(format!(
|
||||
"draw {number}: index count must be a nonzero multiple of 3"
|
||||
));
|
||||
}
|
||||
let end = draw
|
||||
.start_index
|
||||
.checked_add(draw.index_count)
|
||||
.filter(|&end| end <= pass.indices.len())
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"indexed pass",
|
||||
format!("draw {number}: index range past the index buffer"),
|
||||
)
|
||||
})?;
|
||||
for position in draw.start_index..end {
|
||||
let index = pass.indices.index(position);
|
||||
// Metal documents 0xFFFF / 0xFFFFFFFF as the primitive-restart value
|
||||
// of indexed draws without defining it for triangle lists, so the
|
||||
// raw value is rejected whatever the base vertex.
|
||||
if index == pass.indices.restart() {
|
||||
return invalid(format!(
|
||||
"draw {number}: index {position} is the primitive-restart value"
|
||||
));
|
||||
}
|
||||
let vertex = i64::from(index) + i64::from(draw.base_vertex);
|
||||
if !(0..pass.vertices.len() as i64).contains(&vertex) {
|
||||
return invalid(format!(
|
||||
"draw {number}: index {position} fetches vertex {vertex} outside the vertex buffer"
|
||||
));
|
||||
}
|
||||
}
|
||||
if draw.fill == DepthFill::Bc1Texture && pass.texture.is_none() {
|
||||
return invalid("textured draw without texture".to_owned());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_depth_pass(pass: &DepthPass<'_>) -> Result<(), MetalError> {
|
||||
if pass.draws.len() > MAX_DEPTH_DRAWS {
|
||||
return Err(MetalError::new("depth pass", "expected at most 16 draws"));
|
||||
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
case clear
|
||||
palette 0 16 32 48 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
end
|
||||
case u16_first
|
||||
fetch 0 1 2
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 0 255
|
||||
color 0000000000000001
|
||||
color 0000000000000011
|
||||
color 0000000000000111
|
||||
color 0000000000011111
|
||||
color 0000000000111111
|
||||
color 0000000001111111
|
||||
color 0000000111111111
|
||||
color 0000001111111111
|
||||
color 0000011111111111
|
||||
color 0001111111111111
|
||||
color 0011111111111111
|
||||
color 0111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
end
|
||||
case u32_first
|
||||
fetch 0 1 2
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 0 255
|
||||
color 0000000000000001
|
||||
color 0000000000000011
|
||||
color 0000000000000111
|
||||
color 0000000000011111
|
||||
color 0000000000111111
|
||||
color 0000000001111111
|
||||
color 0000000111111111
|
||||
color 0000001111111111
|
||||
color 0000011111111111
|
||||
color 0001111111111111
|
||||
color 0011111111111111
|
||||
color 0111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
end
|
||||
case u16_odd_start
|
||||
fetch 3 4 5
|
||||
palette 0 0 0 0 255
|
||||
palette 1 0 255 0 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000111111000000
|
||||
color 0000111111111111
|
||||
color 0000111111111110
|
||||
color 0000011111111100
|
||||
color 0000011111111000
|
||||
color 0000011111110000
|
||||
color 0000011111100000
|
||||
color 0000011111100000
|
||||
color 0000011111000000
|
||||
color 0000011110000000
|
||||
color 0000001100000000
|
||||
color 0000001000000000
|
||||
color 0000000000000000
|
||||
end
|
||||
case u32_start
|
||||
fetch 3 4 5
|
||||
palette 0 0 0 0 255
|
||||
palette 1 0 255 0 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000111111000000
|
||||
color 0000111111111111
|
||||
color 0000111111111110
|
||||
color 0000011111111100
|
||||
color 0000011111111000
|
||||
color 0000011111110000
|
||||
color 0000011111100000
|
||||
color 0000011111100000
|
||||
color 0000011111000000
|
||||
color 0000011110000000
|
||||
color 0000001100000000
|
||||
color 0000001000000000
|
||||
color 0000000000000000
|
||||
end
|
||||
case u16_base_positive
|
||||
fetch 6 7 8
|
||||
palette 0 0 0 0 255
|
||||
palette 1 0 0 255 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 1111111110000000
|
||||
color 1111111100000000
|
||||
color 1111111000000000
|
||||
color 1111110000000000
|
||||
color 1111000000000000
|
||||
color 1110000000000000
|
||||
color 1100000000000000
|
||||
color 1000000000000000
|
||||
end
|
||||
case u16_base_negative
|
||||
fetch 6 7 8
|
||||
palette 0 0 0 0 255
|
||||
palette 1 0 0 255 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 1111111110000000
|
||||
color 1111111100000000
|
||||
color 1111111000000000
|
||||
color 1111110000000000
|
||||
color 1111000000000000
|
||||
color 1110000000000000
|
||||
color 1100000000000000
|
||||
color 1000000000000000
|
||||
end
|
||||
case u32_base_negative
|
||||
fetch 6 7 8
|
||||
palette 0 0 0 0 255
|
||||
palette 1 0 0 255 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 1111111110000000
|
||||
color 1111111100000000
|
||||
color 1111111000000000
|
||||
color 1111110000000000
|
||||
color 1111000000000000
|
||||
color 1110000000000000
|
||||
color 1100000000000000
|
||||
color 1000000000000000
|
||||
end
|
||||
case reversed_winding
|
||||
fetch 2 1 0
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 0 255
|
||||
color 0000000000000001
|
||||
color 0000000000000011
|
||||
color 0000000000000111
|
||||
color 0000000000011111
|
||||
color 0000000000111111
|
||||
color 0000000001111111
|
||||
color 0000000111111111
|
||||
color 0000001111111111
|
||||
color 0000011111111111
|
||||
color 0001111111111111
|
||||
color 0011111111111111
|
||||
color 0111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
color 1111111111111111
|
||||
end
|
||||
case two_triangles_textured
|
||||
fetch 9 10 11 9 11 12
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 255 255
|
||||
palette 2 0 0 0 0
|
||||
palette 3 0 255 0 255
|
||||
palette 4 255 255 255 255
|
||||
palette 5 255 255 0 255
|
||||
palette 6 132 130 132 255
|
||||
palette 7 8 8 8 255
|
||||
palette 8 0 0 0 255
|
||||
color 0011001122223333
|
||||
color 0011001122223333
|
||||
color 1100110033332222
|
||||
color 1100110033332222
|
||||
color 0000111133223344
|
||||
color 0000111133223344
|
||||
color 1111000044332233
|
||||
color 1111000044332233
|
||||
color 5555555566777766
|
||||
color 5555555566777766
|
||||
color 8888888877666677
|
||||
color 8888888877666677
|
||||
color 5555555566777766
|
||||
color 5555555566777766
|
||||
color 8888888877666677
|
||||
color 8888888888888888
|
||||
end
|
||||
case textured_base_vertex
|
||||
fetch 9 10 11
|
||||
palette 0 0 0 0 255
|
||||
palette 1 255 0 0 255
|
||||
palette 2 0 0 255 255
|
||||
palette 3 0 0 0 0
|
||||
palette 4 0 255 0 255
|
||||
palette 5 255 255 255 255
|
||||
palette 6 132 130 132 255
|
||||
palette 7 8 8 8 255
|
||||
color 0122112233334444
|
||||
color 0022112233334444
|
||||
color 0001221144443333
|
||||
color 0000221144443333
|
||||
color 0000022244334455
|
||||
color 0000002244334455
|
||||
color 0000000155443344
|
||||
color 0000000055443344
|
||||
color 0000000006777766
|
||||
color 0000000000777766
|
||||
color 0000000000066677
|
||||
color 0000000000006677
|
||||
color 0000000000000766
|
||||
color 0000000000000066
|
||||
color 0000000000000007
|
||||
color 0000000000000000
|
||||
end
|
||||
case painter_order
|
||||
fetch 0 1 2
|
||||
fetch 3 4 5
|
||||
fetch 6 7 8
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 0 255
|
||||
palette 2 0 255 0 255
|
||||
palette 3 0 0 255 255
|
||||
color 0000000000000001
|
||||
color 0000000000000011
|
||||
color 0000000000000111
|
||||
color 0000222222011111
|
||||
color 0000222222222222
|
||||
color 0000222222222221
|
||||
color 0000022222222211
|
||||
color 0000022222222111
|
||||
color 3333333332221111
|
||||
color 3333333322211111
|
||||
color 3333333222211111
|
||||
color 3333332222111111
|
||||
color 3333122221111111
|
||||
color 3331112211111111
|
||||
color 3311112111111111
|
||||
color 3111111111111111
|
||||
end
|
||||
case u32_mixed
|
||||
fetch 9 10 11 9 11 12
|
||||
fetch 9 10 11
|
||||
fetch 0 1 2
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 255 0 255
|
||||
palette 2 255 255 0 255
|
||||
palette 3 132 130 132 255
|
||||
palette 4 0 0 0 255
|
||||
palette 5 8 8 8 255
|
||||
color 0000000000000001
|
||||
color 0000000000000011
|
||||
color 0000000000000111
|
||||
color 0000000000011111
|
||||
color 0000000000111111
|
||||
color 0000000001111111
|
||||
color 0000000111111111
|
||||
color 0000000011111111
|
||||
color 0000022231111111
|
||||
color 0002222233111111
|
||||
color 0044444455311111
|
||||
color 0444444455331111
|
||||
color 2222222233555111
|
||||
color 2222222233555511
|
||||
color 4444444455333351
|
||||
color 4444444444444444
|
||||
end
|
||||
case flat_two_triangles
|
||||
fetch 9 10 11 9 11 12
|
||||
palette 0 0 255 0 255
|
||||
palette 1 0 0 0 255
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000000000000
|
||||
color 0000000011111111
|
||||
end
|
||||
case textured_first
|
||||
fetch 0 1 2
|
||||
palette 0 255 0 0 255
|
||||
palette 1 0 0 255 255
|
||||
palette 2 0 0 0 0
|
||||
palette 3 0 255 0 255
|
||||
palette 4 0 0 0 255
|
||||
palette 5 255 255 0 255
|
||||
color 0011001122223334
|
||||
color 0011001122223344
|
||||
color 1100110033332444
|
||||
color 1100110033344444
|
||||
color 0000111133444444
|
||||
color 0000111134444444
|
||||
color 1111000444444444
|
||||
color 1111004444444444
|
||||
color 5555544444444444
|
||||
color 5554444444444444
|
||||
color 4444444444444444
|
||||
color 4444444444444444
|
||||
color 4444444444444444
|
||||
color 4444444444444444
|
||||
color 4444444444444444
|
||||
color 4444444444444444
|
||||
end
|
||||
case u32_high_indices
|
||||
fetch 9 10 11
|
||||
palette 0 0 0 0 255
|
||||
palette 1 255 0 0 255
|
||||
color 0111111111111111
|
||||
color 0011111111111111
|
||||
color 0001111111111111
|
||||
color 0000111111111111
|
||||
color 0000011111111111
|
||||
color 0000001111111111
|
||||
color 0000000111111111
|
||||
color 0000000011111111
|
||||
color 0000000001111111
|
||||
color 0000000000111111
|
||||
color 0000000000011111
|
||||
color 0000000000001111
|
||||
color 0000000000000111
|
||||
color 0000000000000011
|
||||
color 0000000000000001
|
||||
color 0000000000000000
|
||||
end
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU check: the reference index fetch and rasteriser agree with the
|
||||
//! independently derived expectations for every indexed case. Runs without a GPU.
|
||||
|
||||
#[path = "support/indexed_cases.rs"]
|
||||
mod indexed_cases;
|
||||
|
||||
use indexed_cases::{BC1_BLOCKS, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices};
|
||||
use xenora_ref::depth::{RefFill, RefTexture};
|
||||
use xenora_ref::indexed::{RefIndexedDraw, RefIndices, fetch, render_indexed};
|
||||
|
||||
fn bc1_texels() -> Vec<[u8; 4]> {
|
||||
let mut texels = vec![[0; 4]; 64];
|
||||
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
|
||||
for (index, texel) in xenora_texture::decode_bc1(*bytes).iter().enumerate() {
|
||||
texels[((block / 2) * 4 + index / 4) * 8 + (block % 2) * 4 + index % 4] = *texel;
|
||||
}
|
||||
}
|
||||
texels
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_independent_expectations() {
|
||||
let texels = bc1_texels();
|
||||
let texture = RefTexture {
|
||||
width: 8,
|
||||
height: 8,
|
||||
texels: &texels,
|
||||
};
|
||||
let wide = wide_indices();
|
||||
let vertices = vertices();
|
||||
let (cases, expected) = (cases(), expected());
|
||||
assert_eq!(cases.len(), 16);
|
||||
assert_eq!(expected.len(), cases.len());
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let indices = if case.wide {
|
||||
RefIndices::U32(&wide)
|
||||
} else {
|
||||
RefIndices::U16(&INDICES)
|
||||
};
|
||||
let draws: Vec<_> = case
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| RefIndexedDraw {
|
||||
start: draw.start,
|
||||
count: draw.count,
|
||||
base_vertex: draw.base_vertex,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => RefFill::Flat(rgba),
|
||||
Fill::Texture => RefFill::Texture,
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let fetched: Vec<_> = draws
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(number, draw)| fetch(number, draw, indices, vertices.len()).expect("fetch"))
|
||||
.collect();
|
||||
assert_eq!(fetched, want.fetch, "{} fetch", case.name);
|
||||
let color = render_indexed(
|
||||
[SIZE, SIZE],
|
||||
case.clear_color,
|
||||
&vertices,
|
||||
indices,
|
||||
&draws,
|
||||
Some(texture),
|
||||
)
|
||||
.expect("reference render");
|
||||
assert_eq!(color, want.color, "{} colour", case.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
use xenora_metal::{DepthFill, IndexBuffer, IndexedDraw, IndexedPass};
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
|
||||
|
||||
use super::indexed_cases::{
|
||||
BC1_BLOCKS, Case, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices,
|
||||
};
|
||||
use super::{context, native};
|
||||
|
||||
fn metal_draws(case: &Case) -> Vec<IndexedDraw> {
|
||||
case.draws
|
||||
.iter()
|
||||
.map(|draw| IndexedDraw {
|
||||
start_index: draw.start,
|
||||
index_count: draw.count,
|
||||
base_vertex: draw.base_vertex,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => DepthFill::Flat(rgba),
|
||||
Fill::Texture => DepthFill::Bc1Texture,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bc1_upload() -> Bc1Upload<'static> {
|
||||
Bc1Upload::new(
|
||||
&BC1_BLOCKS,
|
||||
Bc1UploadDesc {
|
||||
width: 8,
|
||||
height: 8,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: 16,
|
||||
slice_pitch: 32,
|
||||
},
|
||||
)
|
||||
.expect("valid BC1 upload")
|
||||
}
|
||||
|
||||
/// Each case's native colour must equal the independently derived image
|
||||
/// (which the CPU reference also reproduces in `indexed_reference`), per pixel.
|
||||
/// Metal fetches the vertices itself from the index buffer, start offset and
|
||||
/// base vertex of each `drawIndexedPrimitives` call.
|
||||
#[test]
|
||||
fn indexed_draw_known_answers() {
|
||||
let gpu = context();
|
||||
let upload = bc1_upload();
|
||||
let vertices = vertices();
|
||||
let wide = wide_indices();
|
||||
let (cases, expected) = (cases(), expected());
|
||||
assert_eq!(cases.len(), expected.len());
|
||||
let mut checked = 0;
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
// One independently derived fetch list per draw keeps the fixtures aligned.
|
||||
assert_eq!(want.fetch.len(), case.draws.len(), "{}", case.name);
|
||||
let draws = metal_draws(case);
|
||||
let color = native(
|
||||
gpu.render_indexed(&IndexedPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: case.clear_color,
|
||||
vertices: &vertices,
|
||||
indices: if case.wide {
|
||||
IndexBuffer::U32(&wide)
|
||||
} else {
|
||||
IndexBuffer::U16(&INDICES)
|
||||
},
|
||||
draws: &draws,
|
||||
// Only textured cases need BC support, so a device without it fails
|
||||
// those cases alone, as a capability error.
|
||||
texture: case
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| draw.fill == Fill::Texture)
|
||||
.then_some(&upload),
|
||||
}),
|
||||
);
|
||||
assert_eq!(color.len(), SIZE * SIZE * 4);
|
||||
for (index, (pixel, wanted)) in color.as_chunks::<4>().0.iter().zip(&want.color).enumerate()
|
||||
{
|
||||
let (x, y) = (index % SIZE, index / SIZE);
|
||||
assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name);
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
println!("checked {checked} indexed passes of {} pixels", SIZE * SIZE);
|
||||
}
|
||||
|
||||
/// Every malformed draw is rejected before encoding, with its own reason.
|
||||
#[test]
|
||||
fn invalid_indexed_draws_are_rejected() {
|
||||
let gpu = context();
|
||||
let vertices = vertices();
|
||||
let restart = [0, 1, u16::MAX];
|
||||
let flat = DepthFill::Flat([255; 4]);
|
||||
let run = |indices, start_index, index_count, base_vertex, fill| {
|
||||
gpu.render_indexed(&IndexedPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: [0; 4],
|
||||
vertices: &vertices,
|
||||
indices,
|
||||
draws: &[IndexedDraw {
|
||||
start_index,
|
||||
index_count,
|
||||
base_vertex,
|
||||
fill,
|
||||
}],
|
||||
texture: None,
|
||||
})
|
||||
.expect_err("invalid draw must be rejected")
|
||||
.to_string()
|
||||
};
|
||||
let short = IndexBuffer::U16(&INDICES);
|
||||
let count = "index count must be a nonzero multiple of 3";
|
||||
let range = "index range past the index buffer";
|
||||
let outside = "outside the vertex buffer";
|
||||
let restart_value = "primitive-restart value";
|
||||
for (reason, error, wanted) in [
|
||||
// First: Metal itself would draw this one, so only the check rejects it.
|
||||
(
|
||||
"count not a multiple of 3",
|
||||
run(short, 0, 4, 0, flat),
|
||||
count,
|
||||
),
|
||||
("zero count", run(short, 0, 0, 0, flat), count),
|
||||
("range past buffer", run(short, 19, 3, 0, flat), range),
|
||||
("start overflow", run(short, usize::MAX, 3, 0, flat), range),
|
||||
("negative vertex", run(short, 0, 3, -1, flat), outside),
|
||||
("vertex past buffer", run(short, 9, 3, 2, flat), outside),
|
||||
(
|
||||
"32-bit index past buffer",
|
||||
run(IndexBuffer::U32(&[0, 1, 13]), 0, 3, 0, flat),
|
||||
outside,
|
||||
),
|
||||
(
|
||||
"16-bit restart value",
|
||||
run(IndexBuffer::U16(&restart), 0, 3, 0, flat),
|
||||
restart_value,
|
||||
),
|
||||
// In range after the base vertex, but still the raw restart value.
|
||||
(
|
||||
"16-bit restart value with base vertex",
|
||||
run(IndexBuffer::U16(&[65533, 65534, 65535]), 0, 3, -65533, flat),
|
||||
restart_value,
|
||||
),
|
||||
(
|
||||
"32-bit restart value",
|
||||
run(IndexBuffer::U32(&[0, 1, u32::MAX]), 0, 3, 0, flat),
|
||||
restart_value,
|
||||
),
|
||||
("base overflow", run(short, 0, 3, i32::MAX, flat), outside),
|
||||
(
|
||||
"texture missing",
|
||||
run(short, 0, 3, 0, DepthFill::Bc1Texture),
|
||||
"textured draw without texture",
|
||||
),
|
||||
] {
|
||||
println!("{reason}: {error}");
|
||||
assert!(
|
||||
error.contains("indexed pass") && error.contains(wanted),
|
||||
"{reason}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ mod depth;
|
||||
mod depth_cases;
|
||||
#[path = "native/guest_buffer.rs"]
|
||||
mod guest_buffer;
|
||||
#[path = "native/indexed.rs"]
|
||||
mod indexed;
|
||||
#[path = "support/indexed_cases.rs"]
|
||||
mod indexed_cases;
|
||||
#[path = "native/offscreen.rs"]
|
||||
mod offscreen;
|
||||
#[path = "native/texture.rs"]
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Original indexed-draw fixtures shared by the CPU reference check and the
|
||||
//! native Metal test, and the parser for the independently derived
|
||||
//! expectations in `fixtures/indexed_expected.txt`.
|
||||
|
||||
pub const SIZE: usize = 16;
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const GREEN: [u8; 4] = [0, 255, 0, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
const BLACK: [u8; 4] = [0, 0, 0, 255];
|
||||
|
||||
/// The four original BC1 blocks of the depth fixtures (8x8 texels), using
|
||||
/// only endpoint and transparent selectors so every decoded texel is exact.
|
||||
pub const BC1_BLOCKS: [u8; 32] = [
|
||||
0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour
|
||||
0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour
|
||||
0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black
|
||||
0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black
|
||||
];
|
||||
|
||||
/// Vertex buffer in pixel coordinates; no pixel centre lies on any edge of
|
||||
/// a triangle the cases draw.
|
||||
const VERTICES: [[f32; 2]; 13] = [
|
||||
[0.0, 0.0],
|
||||
[16.0, 0.0],
|
||||
[0.0, 12.0],
|
||||
[4.0, 3.0],
|
||||
[16.0, 4.0],
|
||||
[6.0, 16.0],
|
||||
[0.0, 8.0],
|
||||
[10.0, 8.0],
|
||||
[0.0, 16.0],
|
||||
[0.0, 0.0],
|
||||
[16.0, 0.0],
|
||||
[16.0, 15.0],
|
||||
[0.0, 16.0],
|
||||
];
|
||||
|
||||
/// The index buffer of the 16-bit cases.
|
||||
pub const INDICES: [u16; 21] = [
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 11, 12, 2, 1, 0, 10, 11, 12,
|
||||
];
|
||||
|
||||
/// The index buffer of the 32-bit cases: [`INDICES`] and three indices that
|
||||
/// need more than 16 bits.
|
||||
pub fn wide_indices() -> Vec<u32> {
|
||||
INDICES
|
||||
.iter()
|
||||
.map(|&index| u32::from(index))
|
||||
.chain([65545, 65546, 65547])
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Clip-space positions of [`VERTICES`] at depth 0.5.
|
||||
pub fn vertices() -> Vec<[f32; 4]> {
|
||||
VERTICES
|
||||
.iter()
|
||||
.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0])
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Fill {
|
||||
Flat([u8; 4]),
|
||||
Texture,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Draw {
|
||||
pub start: usize,
|
||||
pub count: usize,
|
||||
pub base_vertex: i32,
|
||||
pub fill: Fill,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Case {
|
||||
pub name: &'static str,
|
||||
pub wide: bool,
|
||||
pub clear_color: [u8; 4],
|
||||
pub draws: Vec<Draw>,
|
||||
}
|
||||
|
||||
/// Every case, in fixture order.
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let draw = |start, count, base_vertex, fill| Draw {
|
||||
start,
|
||||
count,
|
||||
base_vertex,
|
||||
fill,
|
||||
};
|
||||
let (red, green, blue, texture) = (
|
||||
Fill::Flat(RED),
|
||||
Fill::Flat(GREEN),
|
||||
Fill::Flat(BLUE),
|
||||
Fill::Texture,
|
||||
);
|
||||
let case = |name, wide, draws| Case {
|
||||
name,
|
||||
wide,
|
||||
clear_color: BLACK,
|
||||
draws,
|
||||
};
|
||||
vec![
|
||||
Case {
|
||||
clear_color: [16, 32, 48, 255],
|
||||
..case("clear", false, Vec::new())
|
||||
},
|
||||
case("u16_first", false, vec![draw(0, 3, 0, red)]),
|
||||
case("u32_first", true, vec![draw(0, 3, 0, red)]),
|
||||
case("u16_odd_start", false, vec![draw(3, 3, 0, green)]),
|
||||
case("u32_start", true, vec![draw(3, 3, 0, green)]),
|
||||
case("u16_base_positive", false, vec![draw(0, 3, 6, blue)]),
|
||||
case("u16_base_negative", false, vec![draw(18, 3, -4, blue)]),
|
||||
case("u32_base_negative", true, vec![draw(18, 3, -4, blue)]),
|
||||
case("reversed_winding", false, vec![draw(15, 3, 0, red)]),
|
||||
case(
|
||||
"two_triangles_textured",
|
||||
false,
|
||||
vec![draw(9, 6, 0, texture)],
|
||||
),
|
||||
case("textured_base_vertex", false, vec![draw(0, 3, 9, texture)]),
|
||||
case(
|
||||
"painter_order",
|
||||
false,
|
||||
vec![
|
||||
draw(0, 3, 0, red),
|
||||
draw(3, 3, 0, green),
|
||||
draw(0, 3, 6, blue),
|
||||
],
|
||||
),
|
||||
case(
|
||||
"u32_mixed",
|
||||
true,
|
||||
vec![
|
||||
draw(9, 6, 0, texture),
|
||||
draw(18, 3, -1, green),
|
||||
draw(6, 3, -6, red),
|
||||
],
|
||||
),
|
||||
case("flat_two_triangles", false, vec![draw(9, 6, 0, green)]),
|
||||
case("textured_first", false, vec![draw(0, 3, 0, texture)]),
|
||||
case("u32_high_indices", true, vec![draw(21, 3, -65536, red)]),
|
||||
]
|
||||
}
|
||||
|
||||
/// One case of `indexed_expected.txt`: fetched vertices per draw and colours.
|
||||
#[derive(Debug)]
|
||||
pub struct Expected {
|
||||
pub name: String,
|
||||
pub fetch: Vec<Vec<usize>>,
|
||||
pub color: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
/// Parse the independently derived expectations.
|
||||
pub fn expected() -> Vec<Expected> {
|
||||
let text = include_str!("../fixtures/indexed_expected.txt");
|
||||
let mut out = Vec::new();
|
||||
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
|
||||
while let Some(header) = lines.next() {
|
||||
let name = header.strip_prefix("case ").expect("case line").to_owned();
|
||||
let (mut fetch, mut palette, mut color) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for line in lines.by_ref() {
|
||||
let mut words = line.split_whitespace();
|
||||
match words.next().expect("keyword") {
|
||||
"fetch" => fetch.push(words.map(|word| word.parse().unwrap()).collect()),
|
||||
"palette" => {
|
||||
let key = words.next().unwrap().chars().next().unwrap();
|
||||
let rgba: Vec<u8> = words.map(|word| word.parse().unwrap()).collect();
|
||||
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
|
||||
}
|
||||
"color" => color.extend(words.next().unwrap().chars().map(|c| {
|
||||
palette
|
||||
.iter()
|
||||
.find(|(key, _)| *key == c)
|
||||
.expect("palette key")
|
||||
.1
|
||||
})),
|
||||
"end" => break,
|
||||
other => panic!("unexpected fixture line {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
|
||||
out.push(Expected { name, fetch, color });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU reference for indexed triangle-list draws.
|
||||
//!
|
||||
//! A draw reads `count` indices starting at index `start` and fetches vertex
|
||||
//! `index + base_vertex` for each, as `DrawIndexedInstanced` and Metal's
|
||||
//! `drawIndexedPrimitives` describe. Every fetched vertex must lie inside the
|
||||
//! vertex buffer, and no index may be the primitive-restart value (all bits
|
||||
//! set); the reference rejects the draw instead of defining either behaviour. The triangles are then rasterised by
|
||||
//! [`crate::depth::render_depth`] without a depth attachment.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::depth::{CompareFunction, RefDraw, RefFill, RefTexture, render_depth};
|
||||
|
||||
/// An index buffer of 16- or 32-bit unsigned indices.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum RefIndices<'a> {
|
||||
U16(&'a [u16]),
|
||||
U32(&'a [u32]),
|
||||
}
|
||||
|
||||
impl RefIndices<'_> {
|
||||
fn len(self) -> usize {
|
||||
match self {
|
||||
Self::U16(indices) => indices.len(),
|
||||
Self::U32(indices) => indices.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn restart(self) -> u32 {
|
||||
match self {
|
||||
Self::U16(_) => u32::from(u16::MAX),
|
||||
Self::U32(_) => u32::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(self, position: usize) -> Option<u32> {
|
||||
match self {
|
||||
Self::U16(indices) => indices.get(position).map(|&index| u32::from(index)),
|
||||
Self::U32(indices) => indices.get(position).copied(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One indexed draw: a range of the index buffer, a signed base vertex and a fill.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefIndexedDraw {
|
||||
pub start: usize,
|
||||
pub count: usize,
|
||||
pub base_vertex: i32,
|
||||
pub fill: RefFill,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum IndexedRefError {
|
||||
/// The index count of the draw is zero or not a multiple of 3: (draw).
|
||||
Count(usize),
|
||||
/// The index range of the draw ends past the index buffer: (draw).
|
||||
IndexRange(usize),
|
||||
/// `index + base_vertex` lies outside the vertex buffer: (draw, index position).
|
||||
VertexRange(usize, usize),
|
||||
/// The index is the primitive-restart value: (draw, index position).
|
||||
Restart(usize, usize),
|
||||
/// The resolved triangles could not be rasterised.
|
||||
Raster(crate::depth::DepthRefError),
|
||||
}
|
||||
|
||||
impl fmt::Display for IndexedRefError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IndexedRefError {}
|
||||
|
||||
/// The vertex numbers draw `draw` of a pass fetches, in index order.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for a count that is zero or not a multiple of 3, an index
|
||||
/// range past the buffer, a primitive-restart index, or a fetched vertex
|
||||
/// outside `0..vertex_count`.
|
||||
pub fn fetch(
|
||||
draw_number: usize,
|
||||
draw: &RefIndexedDraw,
|
||||
indices: RefIndices<'_>,
|
||||
vertex_count: usize,
|
||||
) -> Result<Vec<usize>, IndexedRefError> {
|
||||
if draw.count == 0 || !draw.count.is_multiple_of(3) {
|
||||
return Err(IndexedRefError::Count(draw_number));
|
||||
}
|
||||
let end = draw
|
||||
.start
|
||||
.checked_add(draw.count)
|
||||
.filter(|&end| end <= indices.len())
|
||||
.ok_or(IndexedRefError::IndexRange(draw_number))?;
|
||||
(draw.start..end)
|
||||
.map(|position| {
|
||||
let index = indices.get(position).expect("position checked above");
|
||||
if index == indices.restart() {
|
||||
return Err(IndexedRefError::Restart(draw_number, position));
|
||||
}
|
||||
usize::try_from(i64::from(index) + i64::from(draw.base_vertex))
|
||||
.ok()
|
||||
.filter(|&vertex| vertex < vertex_count)
|
||||
.ok_or(IndexedRefError::VertexRange(draw_number, position))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Render indexed draws in order over a target cleared to `clear_color`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when [`fetch`] rejects a draw or the resolved triangles
|
||||
/// cannot be rasterised (see [`render_depth`]).
|
||||
pub fn render_indexed(
|
||||
extent: [usize; 2],
|
||||
clear_color: [u8; 4],
|
||||
vertices: &[[f32; 4]],
|
||||
indices: RefIndices<'_>,
|
||||
draws: &[RefIndexedDraw],
|
||||
texture: Option<RefTexture<'_>>,
|
||||
) -> Result<Vec<[u8; 4]>, IndexedRefError> {
|
||||
let mut triangles = Vec::new();
|
||||
for (number, draw) in draws.iter().enumerate() {
|
||||
let fetched = fetch(number, draw, indices, vertices.len())?;
|
||||
triangles.extend(fetched.as_chunks::<3>().0.iter().map(|triangle| RefDraw {
|
||||
positions: triangle.map(|vertex| vertices[vertex]),
|
||||
fill: draw.fill,
|
||||
compare: CompareFunction::Always,
|
||||
write: false,
|
||||
}));
|
||||
}
|
||||
render_depth(extent, clear_color, None, &triangles, texture)
|
||||
.map(|(color, _)| color)
|
||||
.map_err(IndexedRefError::Raster)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn draw(start: usize, count: usize, base_vertex: i32) -> RefIndexedDraw {
|
||||
RefIndexedDraw {
|
||||
start,
|
||||
count,
|
||||
base_vertex,
|
||||
fill: RefFill::Flat([255; 4]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_applies_start_and_signed_base_vertex() {
|
||||
let indices = RefIndices::U16(&[7, 0, 1, 2, 5]);
|
||||
assert_eq!(fetch(0, &draw(1, 3, 2), indices, 5), Ok(vec![2, 3, 4]));
|
||||
assert_eq!(fetch(0, &draw(2, 3, -1), indices, 5), Ok(vec![0, 1, 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_rejects_bad_counts_ranges_and_vertices() {
|
||||
let indices = RefIndices::U32(&[0, 1, 2, u32::MAX]);
|
||||
assert_eq!(
|
||||
fetch(3, &draw(0, 0, 0), indices, 3),
|
||||
Err(IndexedRefError::Count(3))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(0, 2, 0), indices, 3),
|
||||
Err(IndexedRefError::Count(0))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(2, 3, 0), indices, 3),
|
||||
Err(IndexedRefError::IndexRange(0))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(usize::MAX, 3, 0), indices, 3),
|
||||
Err(IndexedRefError::IndexRange(0))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(0, 3, -1), indices, 3),
|
||||
Err(IndexedRefError::VertexRange(0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(0, 3, 1), indices, 3),
|
||||
Err(IndexedRefError::VertexRange(0, 2))
|
||||
);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(1, 3, 0), indices, 3),
|
||||
Err(IndexedRefError::Restart(0, 3))
|
||||
);
|
||||
// The raw restart value is rejected even when the base vertex would
|
||||
// bring it into range.
|
||||
let high = RefIndices::U16(&[65533, 65534, 65535]);
|
||||
assert_eq!(
|
||||
fetch(0, &draw(0, 3, -65533), high, 3),
|
||||
Err(IndexedRefError::Restart(0, 2))
|
||||
);
|
||||
let high = RefIndices::U16(&[65532, 65533, 65534]);
|
||||
assert_eq!(fetch(0, &draw(0, 3, -65532), high, 3), Ok(vec![0, 1, 2]));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling and depth-tested rendering.
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling, depth-tested rendering and indexed draws.
|
||||
|
||||
pub mod depth;
|
||||
pub mod indexed;
|
||||
pub mod texture_sampling;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
Generated
+80
@@ -8,6 +8,15 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.3"
|
||||
@@ -26,12 +35,51 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@@ -75,12 +123,35 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-decoder"
|
||||
version = "0.1.0"
|
||||
@@ -94,6 +165,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"libfuzzer-sys",
|
||||
"xenora-decoder",
|
||||
"xenora-loader",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
@@ -102,6 +174,14 @@ dependencies = [
|
||||
name = "xenora-isa"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ref"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -11,6 +11,7 @@ cargo-fuzz = true
|
||||
[dependencies]
|
||||
libfuzzer-sys = "=0.4.13"
|
||||
xenora-decoder = { path = "../crates/decoder" }
|
||||
xenora-loader = { path = "../crates/loader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
|
||||
@@ -28,6 +29,12 @@ path = "fuzz_targets/fixture.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "pe_parse"
|
||||
path = "fuzz_targets/pe_parse.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "reference"
|
||||
path = "fuzz_targets/reference.rs"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_MAPPED_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let Ok(pe) = xenora_loader::ParsedPe::parse(data) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let _ = pe.rva_to_file_offset(pe.entry_point_rva);
|
||||
let mut mapped_bytes = 0u64;
|
||||
for section in &pe.sections {
|
||||
let _ = pe.rva_to_file_offset(section.virtual_address);
|
||||
// The loader allocates each section separately, independent of size_of_image.
|
||||
let section_size = u64::from(section.virtual_size.max(section.raw_data_size));
|
||||
mapped_bytes = mapped_bytes.saturating_add(section_size);
|
||||
}
|
||||
|
||||
if mapped_bytes <= MAX_MAPPED_BYTES && u64::from(pe.size_of_image) <= MAX_MAPPED_BYTES {
|
||||
let _ = pe.load_into_memory(data);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user