// Tycho RHI public API façade.
// Users import only `"laplaceliu/tycho" @tycho` — zero Vulkan handles, descriptor
// sets, sync primitives, or C stubs are exposed.

// Backend selection: the Vulkan path keeps its existing state objects, the DX12
// path holds the matching laplaceliu/tycho_dx12 handles. Methods that only exist
// on one backend funnel through `vk()` / `dx12()` and raise `BackendUnsupported`
// instead of silently doing nothing.

///|
priv enum DeviceBackend {
  VkDevice(VkDeviceState)
  Dx12Device(Dx12DeviceState)
}

///|
priv enum SwapchainBackend {
  VkSwapchain(VkSwapchainState)
  Dx12Swapchain(Dx12SwapchainState)
}

///|
priv enum PipelineBackend {
  VkPipeline(VkPipelineState)
  Dx12Pipeline(Dx12PipelineState)
  Dx12Compute(Dx12ComputeState)
}

///|
priv enum BufferBackend {
  VkBuffer(VkBufferState)
  Dx12Buffer(Dx12BufferState)
}

///|
priv enum CommandsBackend {
  VkCommands(VkCmdState)
  Dx12Commands(Dx12CommandState)
}

///|
pub struct Device {
  priv backend : DeviceBackend
}

///|
pub struct Swapchain {
  priv backend : SwapchainBackend
}

///|
pub struct Pipeline {
  priv backend : PipelineBackend
}

///|
fn Device::vk(self : Device) -> VkDeviceState raise RhiError {
  match self.backend {
    VkDevice(state) => state
    Dx12Device(_) =>
      raise RhiError::BackendUnsupported(
        "this device operation is not implemented on the DX12 backend",
      )
  }
}

///|
fn Swapchain::vk(self : Swapchain) -> VkSwapchainState raise RhiError {
  match self.backend {
    VkSwapchain(state) => state
    Dx12Swapchain(_) =>
      raise RhiError::BackendUnsupported(
        "this swapchain operation is not implemented on the DX12 backend",
      )
  }
}

///|
fn CommandBuffer::vk(self : CommandBuffer) -> VkCmdState raise RhiError {
  match self.backend {
    VkCommands(state) => state
    Dx12Commands(_) =>
      raise RhiError::BackendUnsupported(
        "this command is not implemented on the DX12 backend",
      )
  }
}

///|
pub struct Buffer {
  priv backend : BufferBackend
}

///|
priv enum TextureBackend {
  VkTexture(VkTextureState)
  Dx12Texture(Dx12TextureState)
}

///|
priv struct Dx12TextureState {
  device : @dx12.Device
  tex : @dx12.Texture
  width : Int
  height : Int
  format : TextureFormat
  is_depth : Bool
}

///|
pub struct Texture {
  priv backend : TextureBackend
}

///|
fn Texture::vk(self : Texture) -> VkTextureState raise RhiError {
  match self.backend {
    VkTexture(state) => state
    Dx12Texture(_) =>
      raise RhiError::BackendUnsupported(
        "this texture operation is not implemented on the DX12 backend",
      )
  }
}

///|
///|
priv enum SamplerBackend {
  VkSampler(VkSamplerState)
  /// A slot in the DX12 device's shader-visible sampler heap.
  Dx12Sampler(@dx12.Sampler)
}

///|
pub struct Sampler {
  priv backend : SamplerBackend
}

///|
fn Sampler::vk(self : Sampler) -> VkSamplerState raise RhiError {
  match self.backend {
    VkSampler(state) => state
    Dx12Sampler(_) =>
      raise RhiError::BackendUnsupported("expected a Vulkan sampler, found a DX12 one")
  }
}

///|
pub struct Fence {
  priv inner : VkFenceState
}

///|
priv enum TimestampPoolBackend {
  VkTimestampPool(VkTimestampPoolState)
  Dx12TimestampPool(@dx12.TimestampPool)
}

///|
/// GPU timestamps. On DX12 the queries are resolved by `end_commands`, which is
/// the only point where every write is recorded and the copy still reaches the
/// GPU, so reading is valid as soon as the submission returns.
pub struct TimestampPool {
  priv backend : TimestampPoolBackend
}

///|
pub struct BindlessHeap {
  priv inner : VkBindlessHeapState
}

///|
priv enum AccelBackend {
  VkAccel(VkAccelStructState)
  Dx12Accel(@dx12.AccelStruct)
}

///|
/// A BLAS or TLAS. Ray queries read it from a shader; there is no
/// `trace_rays` pipeline path yet (that would need D3D12 state objects and a
/// shader binding table).
pub struct AccelStruct {
  priv backend : AccelBackend
}

///|
pub struct CommandBuffer {
  priv backend : CommandsBackend
  // First backend misuse / unsupported command recorded while recording. Both
  // backends funnel it through `end_commands` (or `Swapchain::end_frame`) so a
  // cross-backend mistake is reported deterministically instead of being
  // silently dropped at the call site.
  priv mut first_error : String?
}

///|
/// Keeps the first recorded error so a later, less specific message cannot mask
/// the original cause.
fn record_first(current : String?, what : String) -> String? {
  match current {
    None => Some(what)
    Some(_) => current
  }
}

///|
fn CommandBuffer::fail_later(self : CommandBuffer, what : String) -> Unit {
  self.first_error = record_first(self.first_error, what)
}

///|
/// The first recorded error, if any. `end_commands` raises it; callers can also
/// inspect it when they only want to log.
pub fn CommandBuffer::first_error(self : CommandBuffer) -> String? {
  self.first_error
}

///|
fn Buffer::vk(self : Buffer) -> VkBufferState raise RhiError {
  match self.backend {
    VkBuffer(state) => state
    Dx12Buffer(_) =>
      raise RhiError::BackendUnsupported("this buffer operation is not implemented on DX12")
  }
}

///|
fn Buffer::dx12(self : Buffer) -> Dx12BufferState? {
  match self.backend {
    Dx12Buffer(state) => Some(state)
    VkBuffer(_) => None
  }
}

// Vulkan-only handles: they are only ever produced by the Vulkan backend, so the
// accessors below cannot fail.

fn Fence::vk(self : Fence) -> VkFenceState {
  self.inner
}

fn BindlessHeap::vk(self : BindlessHeap) -> VkBindlessHeapState {
  self.inner
}

fn AccelStruct::vk(self : AccelStruct) -> VkAccelStructState raise RhiError {
  match self.backend {
    VkAccel(state) => state
    Dx12Accel(_) =>
      raise RhiError::BackendUnsupported("this acceleration-structure operation is Vulkan only")
  }
}

///|
pub fn Device::new(
  app_name : String,
  validation : Bool,
) -> Device raise RhiError {
  Device::new_desc(DeviceDesc::new(app_name, validation~, headless=false))
}

///|
/// Whether the DX12 backend can be created on this host (`d3d12.dll` / `dxgi.dll`
/// loadable). Callers use this to SKIP instead of failing on non-Windows hosts.
pub fn dx12_available() -> Bool {
  @dx12.available()
}

///|
pub fn Device::new_desc(desc : DeviceDesc) -> Device raise RhiError {
  match desc.backend {
    BackendKind::Vulkan => { backend: VkDevice(vk_device_create(desc)) }
    BackendKind::Dx12 => { backend: Dx12Device(dx12_device_create(desc)) }
  }
}

///|
pub fn Device::capabilities(self : Device) -> DeviceCapabilities {
  match self.backend {
    VkDevice(state) => state.caps
    Dx12Device(state) => dx12_capabilities(state)
  }
}

///|
pub fn Device::pipeline_cache_data(self : Device) -> Bytes {
  match self.backend {
    VkDevice(state) => vk_device_pipeline_cache_data(state)
    Dx12Device(_) => b""
  }
}

///|
pub fn Device::backend(self : Device) -> BackendKind {
  match self.backend {
    VkDevice(_) => BackendKind::Vulkan
    Dx12Device(_) => BackendKind::Dx12
  }
}

///|
pub fn Device::validation_errors(self : Device) -> Int {
  match self.backend {
    VkDevice(state) => g_rhi_validation_errors.val - state.error_baseline
    Dx12Device(state) => state.device.validation_errors()
  }
}

///|
pub fn Device::allocator_stats(self : Device) -> (Int, Int) {
  match self.backend {
    VkDevice(state) => state.alloc.stats()
    // The DX12 backend runs the same RegionPool, wrapped around a placed heap.
    Dx12Device(state) =>
      match state.buffers {
        Some(pool) =>
          (pool.pool.alloc_count, pool.pool.used_bytes().to_int())
        None => (0, 0)
      }
  }
}

///|
pub fn Device::allocator_used_bytes(self : Device) -> UInt64 {
  match self.backend {
    VkDevice(state) => state.alloc.used_bytes()
    Dx12Device(state) =>
      match state.buffers {
        Some(pool) => pool.pool.used_bytes()
        None => (0 : UInt64)
      }
  }
}

///|
pub fn Device::wait_idle(self : Device) -> Unit {
  match self.backend {
    VkDevice(state) => vk_device_wait_idle(state)
    Dx12Device(state) => {
      let _ = state.device.wait_idle()
    }
  }
}

///|
pub fn Device::destroy(self : Device) -> Unit {
  match self.backend {
    VkDevice(state) => vk_device_destroy(state)
    Dx12Device(state) => dx12_device_destroy(state)
  }
}

///|
pub fn Device::create_swapchain(
  self : Device,
  title : String,
  width : Int,
  height : Int,
) -> Swapchain raise RhiError {
  self.create_swapchain_desc(SwapchainDesc::new(title, width, height))
}

///|
pub fn Device::create_swapchain_desc(
  self : Device,
  desc : SwapchainDesc,
) -> Swapchain raise RhiError {
  match self.backend {
    VkDevice(state) => { backend: VkSwapchain(vk_swapchain_create(state, desc)) }
    Dx12Device(state) => { backend: Dx12Swapchain(dx12_swapchain_create(state, desc)) }
  }
}

///|
pub fn Swapchain::width(self : Swapchain) -> Int {
  match self.backend {
    VkSwapchain(state) => state.width
    Dx12Swapchain(state) => state.width
  }
}

///|
pub fn Swapchain::height(self : Swapchain) -> Int {
  match self.backend {
    VkSwapchain(state) => state.height
    Dx12Swapchain(state) => state.height
  }
}

///|
pub fn Swapchain::color_format(self : Swapchain) -> TextureFormat {
  match self.backend {
    VkSwapchain(state) => vk_swapchain_color_format(state)
    Dx12Swapchain(_) => TextureFormat::RGBA8
  }
}

///|
pub fn Swapchain::has_depth(self : Swapchain) -> Bool {
  match self.backend {
    VkSwapchain(state) => state.has_depth
    Dx12Swapchain(_) => false
  }
}

///|
pub fn Swapchain::depth_format(self : Swapchain) -> TextureFormat {
  match self.backend {
    VkSwapchain(state) => state.depth_format
    Dx12Swapchain(_) => TextureFormat::Depth32F
  }
}

///|
/// The native window handle backing this swapchain (HWND on Windows).
///|
/// The window this swapchain presents to, as a typed `@win.Window` so callers
/// never handle the raw platform pointer.
pub fn Swapchain::window(self : Swapchain) -> @win.Window {
  let handle = match self.backend {
    VkSwapchain(state) => state.window
    Dx12Swapchain(state) => state.window
  }
  @win.Window::from_handle(handle)
}

///|
pub fn Swapchain::should_close(self : Swapchain) -> Bool {
  self.window().should_close()
}

///|
pub fn Swapchain::sync_size(self : Swapchain) -> Unit raise RhiError {
  vk_swapchain_sync_size(self.vk())
}

///|
pub fn Swapchain::wait_events(timeout_ms? : Int = 4) -> Unit {
  @win.wait_events(timeout_ms)
}

///|
pub fn Swapchain::poll_events(self : Swapchain) -> Array[Event] {
  self.window().poll_events()
}

///|
pub fn Swapchain::set_title(self : Swapchain, title : String) -> Unit {
  self.window().set_title(title)
}

///|
pub fn Swapchain::set_cursor_mode(self : Swapchain, mode : CursorMode) -> Unit {
  self.window().set_cursor_mode(mode)
}

///|
pub fn Swapchain::set_cursor_shape(
  self : Swapchain,
  shape : CursorShape,
) -> Unit {
  self.window().set_cursor_shape(shape)
}

///|
pub fn Swapchain::clipboard_text(self : Swapchain) -> String {
  self.window().clipboard_text()
}

///|
pub fn Swapchain::set_clipboard_text(self : Swapchain, text : String) -> Unit {
  self.window().set_clipboard_text(text)
}

///|
pub fn Swapchain::set_fullscreen(self : Swapchain, fullscreen : Bool) -> Unit {
  self.window().set_fullscreen(fullscreen)
}

///|
pub fn Swapchain::is_fullscreen(self : Swapchain) -> Bool {
  self.window().is_fullscreen()
}

///|
pub fn Swapchain::content_scale(self : Swapchain) -> Double {
  self.window().content_scale()
}

///|
pub fn Swapchain::framebuffer_size(self : Swapchain) -> (Int, Int) {
  self.window().framebuffer_size()
}

///|
pub fn Swapchain::mouse_pos(self : Swapchain) -> (Double, Double) {
  self.window().mouse_pos()
}

///|
pub fn Swapchain::is_mouse_down(self : Swapchain, button : @win.MouseButton) -> Bool {
  self.window().is_mouse_down(button)
}

///|
pub fn Swapchain::time() -> Double {
  @win.time()
}

///|
pub fn Swapchain::begin_frame(self : Swapchain) -> CommandBuffer raise RhiError {
  match self.backend {
    VkSwapchain(state) => {
      backend: VkCommands(vk_swapchain_begin_frame(state)),
      first_error: None,
    }
    Dx12Swapchain(state) => {
      backend: Dx12Commands(dx12_begin_frame(state)),
      first_error: None,
    }
  }
}

///|
pub fn Swapchain::begin_frame_commands(
  self : Swapchain,
) -> CommandBuffer raise RhiError {
  match self.backend {
    VkSwapchain(state) => {
      backend: VkCommands(vk_swapchain_begin_frame_commands(state)),
      first_error: None,
    }
    Dx12Swapchain(state) => {
      backend: Dx12Commands(dx12_begin_frame_commands(state)),
      first_error: None,
    }
  }
}

///|
/// Records an unsupported command on DX12 (it surfaces from `end_commands`)
/// and does nothing on Vulkan, mirroring `on_vk`.
fn CommandBuffer::dx12_unsupported(self : CommandBuffer, what : String) -> Unit {
  match self.backend {
    Dx12Commands(cmd) => dx12_unsupported(cmd, what)
    VkCommands(_) => ()
  }
}

///|
/// Runs `apply` with the Vulkan command state. On the DX12 backend the command
/// is recorded as an error (surfacing from `end_commands`) instead of being
/// dropped silently.
fn CommandBuffer::on_vk(
  self : CommandBuffer,
  apply : (VkCmdState) -> Unit,
  what? : String = "this command",
) -> Unit {
  match self.backend {
    VkCommands(state) => apply(state)
    Dx12Commands(_) => self.fail_later("\{what} is not implemented on the DX12 backend")
  }
}

///|
/// Runs `apply` with the Vulkan command state and a Vulkan buffer. A mismatch
/// is recorded as an error instead of being ignored.
fn CommandBuffer::on_vk_buffer(
  self : CommandBuffer,
  buffer : Buffer,
  apply : (VkCmdState, VkBufferState) -> Unit,
  what? : String = "this buffer binding",
) -> Unit {
  match (self.backend, buffer.backend) {
    (VkCommands(cmd), VkBuffer(state)) => apply(cmd, state)
    (Dx12Commands(_), _) => self.fail_later("\{what} is not implemented on the DX12 backend")
    (VkCommands(_), Dx12Buffer(_)) =>
      self.fail_later("\{what} received a DX12 buffer on a Vulkan command buffer")
  }
}

///|
fn CommandBuffer::on_vk_buffers(
  self : CommandBuffer,
  first : Buffer,
  second : Buffer,
  apply : (VkCmdState, VkBufferState, VkBufferState) -> Unit,
  what? : String = "this buffer copy",
) -> Unit {
  match (self.backend, first.backend, second.backend) {
    (VkCommands(cmd), VkBuffer(a), VkBuffer(b)) => apply(cmd, a, b)
    (Dx12Commands(_), _, _) => self.fail_later("\{what} is not implemented on the DX12 backend")
    _ => self.fail_later("\{what} mixes buffers from different backends")
  }
}

///|
pub fn CommandBuffer::frame_slot(self : CommandBuffer) -> Int {
  match self.backend {
    VkCommands(state) => state.frame_idx
    Dx12Commands(_) => 0
  }
}

///|
pub fn CommandBuffer::blit_to_swapchain(
  self : CommandBuffer,
  src : Texture,
  swapchain : Swapchain,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      match swapchain.backend {
        VkSwapchain(sc) =>
          match src.backend {
            VkTexture(texture) => vk_cmd_blit_to_swapchain(state, texture, sc)
            Dx12Texture(_) =>
              self.fail_later("blit_to_swapchain received a DX12 texture on a Vulkan command buffer")
          }
        Dx12Swapchain(_) =>
          self.fail_later("blit_to_swapchain received a DX12 swapchain on a Vulkan command buffer")
      }
    // Texture upload/blit is a Vulkan-backend feature today.
    Dx12Commands(_) => self.dx12_unsupported("a blit to the swapchain")
  }
}

///|
pub fn Swapchain::present_texture(
  self : Swapchain,
  src : Texture,
) -> Unit raise RhiError {
  let cmd = self.begin_frame_commands()
  cmd.blit_to_swapchain(src, self)
  self.end_frame(cmd)
}

///|
pub fn CommandBuffer::begin_swapchain_pass(
  self : CommandBuffer,
  swapchain : Swapchain,
  load_op? : LoadOp = LoadOp::Clear,
  clear_color? : ClearColor,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      match swapchain.backend {
        VkSwapchain(sc) => vk_cmd_begin_swapchain_pass(state, sc, load_op, clear_color)
        Dx12Swapchain(_) => ()
      }
    Dx12Commands(state) => dx12_begin_swapchain_pass(state, load_op, clear_color)
  }
}

///|
pub fn CommandBuffer::end_swapchain_pass(self : CommandBuffer) -> Unit {
  match self.backend {
    VkCommands(state) => vk_cmd_end_swapchain_pass(state)
    // The DX12 pass ending is the barrier to PRESENT, emitted by end_frame.
    Dx12Commands(_) => ()
  }
}

///|
pub fn Swapchain::end_frame(
  self : Swapchain,
  cmd : CommandBuffer,
) -> Unit raise RhiError {
  match self.backend {
    VkSwapchain(state) =>
      match cmd.backend {
        VkCommands(commands) => vk_swapchain_end_frame(state, commands)
        Dx12Commands(_) =>
          raise RhiError::InvalidArgument("DX12 command buffer given to a Vulkan swapchain")
      }
    Dx12Swapchain(state) =>
      match cmd.backend {
        Dx12Commands(commands) => dx12_end_frame(state, commands)
        VkCommands(_) =>
          raise RhiError::InvalidArgument("Vulkan command buffer given to a DX12 swapchain")
      }
  }
  // The frame is submitted either way; a recorded backend misuse is reported
  // now instead of being lost with the command buffer.
  match cmd.first_error {
    Some(message) => raise RhiError::BackendUnsupported(message)
    None => ()
  }
}

///|
pub fn Swapchain::readback(self : Swapchain) -> FixedArray[Byte] {
  match self.backend {
    VkSwapchain(state) => vk_swapchain_readback(state)
    Dx12Swapchain(state) => dx12_swapchain_readback(state)
  }
}

///|
pub fn Swapchain::destroy(self : Swapchain) -> Unit {
  match self.backend {
    VkSwapchain(state) => vk_swapchain_destroy(state)
    Dx12Swapchain(state) => dx12_swapchain_destroy(state)
  }
}

///|
pub fn Swapchain::create_pipeline(
  self : Swapchain,
  vert_spv : FixedArray[UInt32],
  frag_spv : FixedArray[UInt32],
  uniform_slots : Int,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Swapchain(state) =>
      return {
        backend: Dx12Pipeline(
          dx12_pipeline_create(
            state.device,
            vert_spv,
            frag_spv,
            uniform_slots,
            false,
            true,
            0,
            0,
            FixedArray::make(1, 0),
            [],
            [],
          ),
        ),
      }
    VkSwapchain(_) => ()
  }
  self.create_pipeline_desc(
    PipelineDesc::new(vert_spv, frag_spv, uniform_slots~),
  )
}

///|
pub fn Swapchain::create_pipeline_desc(
  self : Swapchain,
  desc : PipelineDesc,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Swapchain(state) => {
      if desc.texture_slots > 0 ||
        desc.storage_slots > 0 ||
        desc.storage_image_slots > 0 ||
        desc.accel_slots > 0 {
        raise RhiError::BackendUnsupported(
          "the DX12 backend implements uniform slots only (texture/storage/accel slots need a descriptor heap)",
        )
      }
      let (inputs, strides) = dx12_vertex_input(desc)
      let ds = desc.depth_or_default()
      return {
        backend: Dx12Pipeline(
          dx12_pipeline_create(
            state.device,
            desc.vert,
            desc.frag,
            desc.uniform_slots,
            ds.depth_test && (match ds.format {
              Some(_) => true
              None => false
            }),
            ds.write,
            desc.texture_slots,
            desc.push_constant_size,
            dx12_color_formats(desc),
            inputs,
            strides,
          ),
        ),
      }
    }
    VkSwapchain(_) => ()
  }
  {
    backend: VkPipeline(vk_graphics_pipeline_create(self.vk().device, desc, self.vk().format)),
  }
}

///|
pub fn Device::create_graphics_pipeline(
  self : Device,
  desc : PipelineDesc,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Device(state) => { backend: Dx12Pipeline(dx12_pipeline_create_from_desc(state, desc)) }
    VkDevice(_) => { backend: VkPipeline(vk_graphics_pipeline_create_default(self.vk(), desc)) }
  }
}

///|
pub fn Device::create_mesh_pipeline(
  self : Device,
  desc : MeshPipelineDesc,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Device(state) => { backend: Dx12Pipeline(dx12_mesh_pipeline_create(state, desc)) }
    VkDevice(_) => { backend: VkPipeline(vk_mesh_pipeline_create_default(self.vk(), desc)) }
  }
}

///|
pub fn Swapchain::create_mesh_pipeline(
  self : Swapchain,
  desc : MeshPipelineDesc,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Swapchain(state) => {
      backend: Dx12Pipeline(
        dx12_mesh_pipeline_create({ device: state.device, buffers: None }, desc),
      ),
    }
    VkSwapchain(_) => {
      backend: VkPipeline(vk_mesh_pipeline_create(self.vk().device, desc, self.vk().format)),
    }
  }
}

///|
pub fn Device::create_compute_pipeline(
  self : Device,
  spv : FixedArray[UInt32],
  uniform_slots : Int,
  storage_slots : Int,
  storage_image_slots? : Int = 0,
  accel_slots? : Int = 0,
  push_constant_size? : Int = 0,
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Device(state) => {
      if storage_slots > 0 && storage_image_slots > 0 {
        raise RhiError::BackendUnsupported(
          "the DX12 compute path binds either storage buffers or storage images in its single UAV table",
        )
      }
      return {
        backend: Dx12Compute(
          dx12_compute_pipeline_create(
            state,
            spv,
            uniform_slots,
            storage_image_slots + storage_slots,
            accel_slots,
            push_constant_size,
          ),
        ),
      }
    }
    VkDevice(_) => ()
  }
  let u_binds = resolve_slot_bindings(uniform_slots, [], 0)
  let t_binds = FixedArray::make(0, 0)
  let s_binds = resolve_slot_bindings(storage_slots, [], uniform_slots)
  let si_binds = resolve_slot_bindings(
    storage_image_slots,
    [],
    uniform_slots + storage_slots,
  )
  let a_binds = resolve_slot_bindings(
    accel_slots,
    [],
    uniform_slots + storage_slots + storage_image_slots,
  )
  {
    backend: VkPipeline(vk_compute_pipeline_create(
      self.vk(),
      spv,
      u_binds,
      t_binds,
      s_binds,
      si_binds,
      a_binds,
      push_constant_size,
    )),
  }
}

///|
pub fn Device::create_compute_pipeline_auto(
  self : Device,
  spv : FixedArray[UInt32],
) -> Pipeline raise RhiError {
  match self.backend {
    Dx12Device(_) =>
      raise RhiError::BackendUnsupported(
        "DXIL carries no SPIR-V reflection; use create_compute_pipeline with explicit slot counts on DX12",
      )
    VkDevice(_) => ()
  }
  let refl = @shader.reflect_spirv(spv)
  let u_arr : Array[Int] = []
  let t_arr : Array[Int] = []
  let s_arr : Array[Int] = []
  let si_arr : Array[Int] = []
  let a_arr : Array[Int] = []
  for b in refl.bindings {
    if b.set != 0 {
      continue
    }
    match b.kind {
      @shader.ReflectedDescriptorKind::UniformBuffer =>
        push_unique_int(u_arr, b.binding)
      @shader.ReflectedDescriptorKind::CombinedImageSampler |
      @shader.ReflectedDescriptorKind::SampledImage =>
        push_unique_int(t_arr, b.binding)
      @shader.ReflectedDescriptorKind::StorageBuffer =>
        push_unique_int(s_arr, b.binding)
      @shader.ReflectedDescriptorKind::StorageImage =>
        push_unique_int(si_arr, b.binding)
      @shader.ReflectedDescriptorKind::AccelerationStructure =>
        push_unique_int(a_arr, b.binding)
      @shader.ReflectedDescriptorKind::Sampler => ()
    }
  }
  u_arr.sort_by(fn(a, b) { a - b })
  t_arr.sort_by(fn(a, b) { a - b })
  s_arr.sort_by(fn(a, b) { a - b })
  si_arr.sort_by(fn(a, b) { a - b })
  a_arr.sort_by(fn(a, b) { a - b })
  {
    backend: VkPipeline(vk_compute_pipeline_create(
      self.vk(),
      spv,
      FixedArray::makei(u_arr.length(), fn(i) { u_arr[i] }),
      FixedArray::makei(t_arr.length(), fn(i) { t_arr[i] }),
      FixedArray::makei(s_arr.length(), fn(i) { s_arr[i] }),
      FixedArray::makei(si_arr.length(), fn(i) { si_arr[i] }),
      FixedArray::makei(a_arr.length(), fn(i) { a_arr[i] }),
      refl.push_constant_size,
    )),
  }
}

///|
pub fn Pipeline::destroy(self : Pipeline) -> Unit {
  match self.backend {
    VkPipeline(state) => vk_pipeline_destroy(state)
    Dx12Pipeline(state) =>
      match state.pipe {
        Graphics(graphics) => graphics.destroy()
        Mesh(mesh) => mesh.destroy()
      }
    Dx12Compute(state) => state.pipe.destroy()
  }
}

///|
pub fn Device::create_buffer(
  self : Device,
  size : Int,
  kind : BufferKind,
) -> Buffer raise RhiError {
  self.create_buffer_with(size, kind)
}

///|
pub fn Device::create_buffer_with(
  self : Device,
  size : Int,
  kind : BufferKind,
  location? : MemoryLocation = MemoryLocation::CpuToGpu,
) -> Buffer raise RhiError {
  match self.backend {
    VkDevice(state) => { backend: VkBuffer(vk_buffer_create(state, size, kind, location~)) }
    Dx12Device(state) => { backend: Dx12Buffer(dx12_buffer_create(state, size, kind, location)) }
  }
}

///|
/// Allocate a buffer with composable usage flags. This is the entry point for
/// combinations the single-role `BufferKind` cannot express, e.g.
/// `BufferUsage::storage().combine(BufferUsage::indirect())`.
pub fn Device::create_buffer_usage(
  self : Device,
  size : Int,
  usage : BufferUsage,
  location? : MemoryLocation = MemoryLocation::CpuToGpu,
) -> Buffer raise RhiError {
  match self.backend {
    VkDevice(state) =>
      { backend: VkBuffer(vk_buffer_create_usage(state, size, usage, location~)) }
    Dx12Device(state) =>
      { backend: Dx12Buffer(dx12_buffer_create(state, size, usage.as_kind(), location)) }
  }
}

///|
pub fn Buffer::size(self : Buffer) -> Int {
  match self.backend {
    VkBuffer(state) => state.size
    Dx12Buffer(state) => state.size
  }
}

///|
fn resolve_upload_count(count : Int, data_len : Int) -> Int raise RhiError {
  if count == -1 {
    data_len
  } else if count < 0 || count > data_len {
    raise InvalidArgument(
      "Upload element count \{count} out of range [0, \{data_len}]",
    )
  } else {
    count
  }
}

///|
pub fn Buffer::upload_bytes(
  self : Buffer,
  data : Bytes,
  offset? : Int = 0,
  count? : Int = -1,
) -> Unit raise RhiError {
  let n = resolve_upload_count(count, data.length())
  match self.dx12() {
    Some(state) => dx12_buffer_write(state, data, offset, n)
    None => vk_buffer_upload_bytes(self.vk(), data, offset, n)
  }
}

///|
pub fn Buffer::upload_floats(
  self : Buffer,
  data : FixedArray[Float],
  offset? : Int = 0,
  count? : Int = -1,
) -> Unit raise RhiError {
  let n = resolve_upload_count(count, data.length())
  match self.dx12() {
    Some(state) => {
      if !state.buffer.write_floats(data, offset~) {
        raise AllocationFailed("DX12 uniform upload exceeded the buffer size")
      }
    }
    None => vk_buffer_upload_floats(self.vk(), data, offset, n)
  }
}

///|
/// Upload a column-major `Mat4` (16 floats) at `offset` bytes.
///
/// Provisional (ADR-002 §3.2): a completeness twin of `upload_floats`, covered by
/// the equivalence test in `examples/rhi/hardening`; the shape may still change
/// in a 0.x minor until it sees external use.
pub fn Buffer::upload_mat4(
  self : Buffer,
  m : @tmath.Mat4,
  offset? : Int = 0,
) -> Unit raise RhiError {
  self.upload_floats(m.to_cols_array(), offset~)
}

///|
pub fn Buffer::upload_uint32(
  self : Buffer,
  data : FixedArray[UInt32],
  offset? : Int = 0,
  count? : Int = -1,
) -> Unit raise RhiError {
  let n = resolve_upload_count(count, data.length())
  match self.dx12() {
    // Little-endian byte order matches both backends' expectations for indices.
    Some(state) => {
      let bytes = Bytes::makei(n * 4, fn(i) {
        let value = data[i / 4].reinterpret_as_int()
        ((value >> ((i % 4) * 8)) & 0xFF).to_byte()
      })
      dx12_buffer_write(state, bytes, offset, n * 4)
    }
    None => vk_buffer_upload_uint32(self.vk(), data, offset, n)
  }
}

///|
fn dx12_buffer_write(
  state : Dx12BufferState,
  data : Bytes,
  offset : Int,
  count : Int,
) -> Unit raise RhiError {
  let slice = Bytes::makei(count, fn(i) { data[i] })
  if !state.buffer.write(slice, offset~) {
    raise AllocationFailed("DX12 upload exceeded the buffer size")
  }
}

///|
pub fn Buffer::upload_uint16(
  self : Buffer,
  data : FixedArray[UInt16],
  offset? : Int = 0,
  count? : Int = -1,
) -> Unit raise RhiError {
  let n = resolve_upload_count(count, data.length())
  let bytes = Bytes::makei(n * 2, fn(i) {
    let v = data[i / 2].to_int()
    if i % 2 == 0 {
      (v & 0xFF).to_byte()
    } else {
      ((v >> 8) & 0xFF).to_byte()
    }
  })
  self.upload_bytes(bytes, offset~)
}

///|
pub fn Buffer::download(self : Buffer) -> Bytes raise RhiError {
  match self.backend {
    VkBuffer(state) => vk_buffer_download(state)
    Dx12Buffer(state) =>
      match state.buffer.download(state.device, state.size) {
        Some(bytes) => Bytes::makei(bytes.length(), fn(i) { bytes[i] })
        None => raise RhiError::CommandFailed("DX12 buffer readback failed")
      }
  }
}

///|
pub fn Buffer::destroy(self : Buffer) -> Unit {
  match self.backend {
    VkBuffer(state) => vk_buffer_destroy(state)
    Dx12Buffer(state) => state.buffer.destroy()
  }
}

///|
/// The single texture-creation entry point: shape, usage flags, format, mips
/// and sample count come from one `TextureDesc`, instead of a factory per
/// combination. The `create_texture*` helpers below are thin wrappers.
pub fn Device::create_texture_desc(
  self : Device,
  desc : TextureDesc,
  data? : Bytes = b"",
) -> Texture raise RhiError {
  match self.backend {
    VkDevice(state) => { backend: VkTexture(vk_texture_create_desc(state, desc, data)) }
    Dx12Device(state) => {
      match desc.dimension {
        TextureDimension::D2 => ()
        _ =>
          raise RhiError::BackendUnsupported(
            "the DX12 backend only creates 2D textures so far",
          )
      }
      if desc.samples != SampleCount::X1 {
        raise RhiError::BackendUnsupported("MSAA textures are not implemented on DX12")
      }
      if is_depth_format(desc.format) {
        if desc.format != TextureFormat::Depth32F {
          raise RhiError::BackendUnsupported("the DX12 depth path only allocates Depth32F so far")
        }
        { backend: Dx12Texture(dx12_depth_create(state, desc.width, desc.height, desc.format)) }
      } else if desc.usage.contains(TextureUsage::render_attachment()) {
        if !dx12_is_linear_4bpp(desc.format) {
          raise RhiError::BackendUnsupported(
            "the DX12 render-target path takes 4-byte colour formats (RGBA8/BGRA8 and their sRGB variants)",
          )
        }
        { backend: Dx12Texture(dx12_render_target_create(state, desc.width, desc.height, desc.format)) }
      } else if desc.usage.contains(TextureUsage::storage()) {
        if desc.format != TextureFormat::RGBA8 {
          raise RhiError::BackendUnsupported("the DX12 UAV path only takes RGBA8 so far")
        }
        { backend: Dx12Texture(dx12_storage_texture_create(state, desc.width, desc.height)) }
      } else if data.length() > 0 {
        if !dx12_is_linear_4bpp(desc.format) {
          raise RhiError::BackendUnsupported(
            "the DX12 upload path takes 4-byte colour formats (RGBA8/BGRA8 and their sRGB variants)",
          )
        }
        { backend: Dx12Texture(dx12_texture_upload_create(state, desc.width, desc.height, data, desc.format)) }
      } else {
        raise RhiError::BackendUnsupported(
          "the DX12 backend cannot create an empty sampled texture yet",
        )
      }
    }
  }
}

///|
pub fn Device::create_texture(
  self : Device,
  width : Int,
  height : Int,
  pixels : Bytes,
) -> Texture raise RhiError {
  self.create_texture_format(width, height, TextureFormat::RGBA8, pixels)
}

///|
pub fn Device::create_texture_format(
  self : Device,
  width : Int,
  height : Int,
  format : TextureFormat,
  pixels : Bytes,
) -> Texture raise RhiError {
  self.create_texture_desc(
    TextureDesc::new(
      width,
      height,
      format,
      usage=TextureUsage::sampled()
      .combine(TextureUsage::copy_src())
      .combine(TextureUsage::copy_dst()),
    ),
    data=pixels,
  )
}

///|
pub fn Device::create_texture_mipmapped(
  self : Device,
  width : Int,
  height : Int,
  format : TextureFormat,
  pixels : Bytes,
) -> Texture raise RhiError {
  { backend: VkTexture(vk_texture_create_mipmapped(self.vk(), width, height, format, pixels)) }
}

///|
pub fn Device::create_storage_texture(
  self : Device,
  width : Int,
  height : Int,
  format : TextureFormat,
) -> Texture raise RhiError {
  match self.backend {
    Dx12Device(state) => {
      if format != TextureFormat::RGBA8 {
        raise RhiError::BackendUnsupported("the DX12 UAV path only takes RGBA8 so far")
      }
      { backend: Dx12Texture(dx12_storage_texture_create(state, width, height)) }
    }
    VkDevice(_) =>
      { backend: VkTexture(vk_texture_create_storage(self.vk(), width, height, format)) }
  }
}

///|
pub fn Device::create_cubemap(
  self : Device,
  size : Int,
  format : TextureFormat,
  faces : Array[Bytes],
) -> Texture raise RhiError {
  if faces.length() != 6 {
    raise InvalidArgument("Cubemap requires exactly 6 face byte buffers")
  }
  let face_bytes = size * size * texture_format_bytes(format)
  let total = Bytes::makei(face_bytes * 6, fn(i) {
    let f = i / face_bytes
    let off = i % face_bytes
    if off < faces[f].length() {
      faces[f][off]
    } else {
      (0 : Byte)
    }
  })
  { backend: VkTexture(vk_texture_create_cubemap(self.vk(), size, format, total)) }
}

///|
/// Create a cubemap with an explicit, CPU-prefiltered mip chain.
/// `levels[m][f]` is mip `m` face `f` (mip 0 is `size` x `size`).
pub fn Device::create_cubemap_mipmapped(
  self : Device,
  size : Int,
  format : TextureFormat,
  levels : Array[Array[Bytes]],
) -> Texture raise RhiError {
  if levels.length() == 0 {
    raise InvalidArgument("Cubemap requires at least one mip level")
  }
  let bpp = texture_format_bytes(format)
  let all : Array[Byte] = []
  for m = 0; m < levels.length(); m = m + 1 {
    let s = if size >> m < 1 { 1 } else { size >> m }
    let faces = levels[m]
    if faces.length() != 6 {
      raise InvalidArgument("Each cubemap mip needs exactly 6 faces")
    }
    let need = s * s * bpp
    for f = 0; f < 6; f = f + 1 {
      let buf = faces[f]
      for i = 0; i < need; i = i + 1 {
        all.push(if i < buf.length() { buf[i] } else { (0 : Byte) })
      }
    }
  }
  { backend: VkTexture(vk_texture_create_cubemap_mipmapped(
      self.vk(),
      size,
      format,
      levels.length(),
      Bytes::from_array(all),
    )) }
}

///|
pub fn Device::create_texture_array(
  self : Device,
  width : Int,
  height : Int,
  layers : Int,
  format : TextureFormat,
  pixels : Bytes,
) -> Texture raise RhiError {
  { backend: VkTexture(vk_texture_create_2d_array(
      self.vk(),
      width,
      height,
      layers,
      format,
      pixels,
    )) }
}

///|
pub fn Device::create_render_target(
  self : Device,
  width : Int,
  height : Int,
  format : TextureFormat,
  samples? : SampleCount = SampleCount::X1,
) -> Texture raise RhiError {
  if is_depth_format(format) {
    raise InvalidArgument("Use create_depth_texture for depth targets")
  }
  // A single-sample colour target is sampled and copied from later; an MSAA
  // target is only ever an attachment.
  let usage = match samples {
    SampleCount::X1 =>
      TextureUsage::render_attachment()
      .combine(TextureUsage::sampled())
      .combine(TextureUsage::copy_src())
      .combine(TextureUsage::copy_dst())
    SampleCount::X4 => TextureUsage::render_attachment()
  }
  self.create_texture_desc(TextureDesc::new(
    width,
    height,
    format,
    usage=usage,
    samples=samples,
  ))
}

///|
pub fn Device::create_depth_texture(
  self : Device,
  width : Int,
  height : Int,
  samples? : SampleCount = SampleCount::X1,
) -> Texture raise RhiError {
  self.create_depth_texture_format(
    width,
    height,
    TextureFormat::Depth32F,
    samples~,
  )
}

///|
pub fn Device::create_depth_texture_format(
  self : Device,
  width : Int,
  height : Int,
  format : TextureFormat,
  samples? : SampleCount = SampleCount::X1,
) -> Texture raise RhiError {
  if !is_depth_format(format) {
    raise InvalidArgument("Expected Depth32F or Depth24Stencil8 format")
  }
  self.create_texture_desc(TextureDesc::new(
    width,
    height,
    format,
    usage=TextureUsage::render_attachment().combine(TextureUsage::sampled()),
    samples=samples,
  ))
}

///|
pub fn Texture::width(self : Texture) -> Int {
  match self.backend {
    Dx12Texture(state) => state.width
    VkTexture(state) => state.width
  }
}

///|
pub fn Texture::format(self : Texture) -> TextureFormat {
  match self.backend {
    Dx12Texture(state) => state.format
    VkTexture(state) => state.format
  }
}

///|
pub fn Texture::height(self : Texture) -> Int {
  match self.backend {
    Dx12Texture(state) => state.height
    VkTexture(state) => state.height
  }
}

///|
pub fn Texture::mip_levels(self : Texture) -> Int {
  match self.backend {
    Dx12Texture(_) => 1
    VkTexture(state) => state.mip_levels
  }
}

///|
pub fn Texture::layers(self : Texture) -> Int {
  match self.backend {
    Dx12Texture(_) => 1
    VkTexture(state) => state.layers
  }
}

///|
// Upload several subregions in one submit. Each entry is (x, y, w, h, pixels);
// all regions target layer 0 / mip 0. Prefer this over repeated
// upload_subregion calls when populating an atlas.
pub fn Texture::upload_subregions(
  self : Texture,
  regions : Array[(Int, Int, Int, Int, Bytes)],
) -> Unit raise RhiError {
  vk_texture_upload_subregions(self.vk(), regions)
}

///|
pub fn Texture::upload_subregion(
  self : Texture,
  x : Int,
  y : Int,
  width : Int,
  height : Int,
  pixels : Bytes,
  layer? : Int = 0,
  mip_level? : Int = 0,
) -> Unit raise RhiError {
  vk_texture_upload_subregion(
    self.vk(),
    x,
    y,
    width,
    height,
    pixels,
    layer,
    mip_level,
  )
}

///|
pub fn Texture::readback(self : Texture) -> FixedArray[Byte] raise RhiError {
  match self.backend {
    VkTexture(state) => vk_texture_readback(state)
    Dx12Texture(state) => dx12_texture_readback(state)
  }
}

///|
pub fn Texture::readback_mip(
  self : Texture,
  level : Int,
) -> FixedArray[Byte] raise RhiError {
  vk_texture_readback_mip(self.vk(), level)
}

///|
pub fn Texture::destroy(self : Texture) -> Unit {
  match self.backend {
    VkTexture(state) => vk_texture_destroy(state)
    Dx12Texture(state) => state.tex.destroy()
  }
}

///|
pub fn Device::create_sampler(self : Device) -> Sampler raise RhiError {
  self.create_sampler_desc(SamplerDesc::new())
}

///|
pub fn Device::create_sampler_desc(
  self : Device,
  desc : SamplerDesc,
) -> Sampler raise RhiError {
  match self.backend {
    Dx12Device(state) => {
      let filter = if desc.anisotropy > 1.0 {
        @dx12.SamplerFilter::Anisotropic
      } else if desc.mag == Filter::Nearest &&
        desc.min == Filter::Nearest &&
        desc.mipmap == Filter::Nearest {
        @dx12.SamplerFilter::Point
      } else {
        @dx12.SamplerFilter::Linear
      }
      let address = match desc.address {
        AddressMode::Repeat => @dx12.SamplerAddress::Wrap
        AddressMode::ClampToEdge => @dx12.SamplerAddress::Clamp
        AddressMode::ClampToBorder => @dx12.SamplerAddress::Border
      }
      match @dx12.Sampler::create(
        state.device,
        filter,
        address,
        anisotropy=desc.anisotropy,
        min_lod=desc.min_lod,
        max_lod=desc.max_lod,
        mip_lod_bias=desc.mip_lod_bias,
      ) {
        Some(sampler) => { backend: Dx12Sampler(sampler) }
        None => raise RhiError::AllocationFailed("DX12 sampler heap slot")
      }
    }
    VkDevice(_) => { backend: VkSampler(vk_sampler_create(self.vk(), desc)) }
  }
}

///|
pub fn Sampler::destroy(self : Sampler) -> Unit {
  match self.backend {
    VkSampler(s) => enqueue_delete(s.device, DeleteSampler(s.sampler))
    Dx12Sampler(sampler) => sampler.destroy()
  }
}

///|
pub fn Device::create_fence(
  self : Device,
  signaled : Bool,
) -> Fence raise RhiError {
  { inner: vk_fence_create(self.vk(), signaled) }
}

///|
pub fn Fence::wait(self : Fence) -> Unit {
  vk_fence_wait(self.vk())
}

///|
pub fn Fence::reset(self : Fence) -> Unit {
  vk_fence_reset(self.vk())
}

///|
pub fn Fence::destroy(self : Fence) -> Unit {
  vk_fence_destroy(self.vk())
}

///|
pub fn Device::create_timestamp_pool(
  self : Device,
  count : Int,
) -> TimestampPool raise RhiError {
  match self.backend {
    Dx12Device(state) => { backend: Dx12TimestampPool(dx12_timestamp_pool_create(state, count)) }
    VkDevice(_) => { backend: VkTimestampPool(vk_timestamp_pool_create(self.vk(), count)) }
  }
}

///|
pub fn TimestampPool::resolve_ns(
  self : TimestampPool,
) -> FixedArray[Double] raise RhiError {
  match self.backend {
    VkTimestampPool(state) => vk_timestamp_pool_resolve_ns(state)
    Dx12TimestampPool(pool) => {
      let n = pool.count()
      let out = FixedArray::make(n, 0.0)
      let freq = pool.frequency()
      // Ticks -> nanoseconds; a queue that refuses to report a frequency leaves
      // the values at zero rather than inventing a scale.
      if freq > (0 : Int64) {
        let scale = 1000000000.0 / freq.to_double()
        for i = 0; i < n; i = i + 1 {
          out[i] = pool.read(i).to_double() * scale
        }
      }
      out
    }
  }
}

///|
pub fn TimestampPool::elapsed_ms(
  self : TimestampPool,
  start_idx : Int,
  end_idx : Int,
) -> Double raise RhiError {
  let count = match self.backend {
    VkTimestampPool(state) => state.count
    Dx12TimestampPool(pool) => pool.count()
  }
  if start_idx < 0 || end_idx < 0 || start_idx >= count || end_idx >= count {
    raise InvalidArgument("Timestamp query index out of range")
  }
  let ns = self.resolve_ns()
  let diff = ns[end_idx] - ns[start_idx]
  if diff < 0.0 { 0.0 } else { diff / 1000000.0 }
}

///|
pub fn TimestampPool::destroy(self : TimestampPool) -> Unit {
  match self.backend {
    VkTimestampPool(state) => vk_timestamp_pool_destroy(state)
    Dx12TimestampPool(pool) => pool.destroy()
  }
}

///|
pub fn Device::create_bindless_heap(
  self : Device,
  max_textures? : Int = 1024,
) -> BindlessHeap raise RhiError {
  { inner: vk_bindless_heap_create(self.vk(), max_textures) }
}

///|
pub fn BindlessHeap::register_texture(
  self : BindlessHeap,
  texture : Texture,
  sampler : Sampler,
) -> Int raise RhiError {
  vk_bindless_heap_register(self.vk(), texture.vk(), sampler.vk())
}

///|
pub fn BindlessHeap::unregister_texture(self : BindlessHeap, index : Int) -> Unit {
  vk_bindless_heap_unregister(self.vk(), index)
}

///|
pub fn BindlessHeap::destroy(self : BindlessHeap) -> Unit {
  vk_bindless_heap_destroy(self.vk())
}

///|
pub fn Device::begin_commands(self : Device) -> CommandBuffer raise RhiError {
  match self.backend {
    Dx12Device(state) =>
      return { backend: Dx12Commands(dx12_commands_create(state)), first_error: None }
    VkDevice(_) => ()
  }
  let d = self.vk()
  let cmd = begin_one_time(d)
  let fi = (d.current_gen.to_int() + d.active_recordings) & 1
  d.active_recordings = d.active_recordings + 1
  let frame_gen = d.next_cmd_gen
  d.next_cmd_gen = d.next_cmd_gen + (1 : UInt64)
  {
    backend: VkCommands({
      device: d,
      cmd,
      frame_idx: fi,
      frame_gen,
      pending_uniforms: [],
      pending_textures: [],
      pending_storage: [],
      pending_storage_images: [],
      pending_accel: [],
      bound: None,
      active_render_targets: [],
      active_depth_target: None,
      in_swapchain_pass: false,
      swapchain_image_initialized: false,
      render_w: 0,
      render_h: 0,
    }),
    first_error: None,
  }
}

///|
pub fn Device::end_commands(
  self : Device,
  cmd : CommandBuffer,
) -> Unit raise RhiError {
  match (self.backend, cmd.backend) {
    (Dx12Device(_), Dx12Commands(state)) => return dx12_commands_finish(state)
    (Dx12Device(_), VkCommands(_)) =>
      raise RhiError::InvalidArgument("Vulkan command buffer given to a DX12 device")
    (VkDevice(_), Dx12Commands(_)) =>
      raise RhiError::InvalidArgument("DX12 command buffer given to a Vulkan device")
    (VkDevice(_), VkCommands(_)) => ()
  }
  let d = self.vk()
  if d.active_recordings > 0 {
    d.active_recordings = d.active_recordings - 1
  }
  end_one_time(d, cmd.vk().cmd)
  d.completed_gen = d.current_gen
  d.current_gen = d.current_gen + (1 : UInt64)
  flush_deletes(d, false)
  match cmd.first_error {
    Some(message) => raise RhiError::BackendUnsupported(message)
    None => ()
  }
}

///|
pub fn Device::submit_commands(
  self : Device,
  cmd : CommandBuffer,
  fence : Fence,
) -> Unit raise RhiError {
  vk_device_submit_commands(self.vk(), cmd.vk(), fence.inner)
}

///|
pub fn CommandBuffer::begin_render_pass(
  self : CommandBuffer,
  colors : Array[RenderTargetDesc],
  depth? : DepthTargetDesc,
) -> Unit raise RhiError {
  match self.backend {
    VkCommands(state) => vk_cmd_begin_render_pass(state, colors, depth)
    Dx12Commands(state) => dx12_begin_render_pass(state, colors, depth)
  }
}

///|
pub fn CommandBuffer::end_render_pass(self : CommandBuffer) -> Unit {
  match self.backend {
    VkCommands(state) =>
      // The signature stays non-raising, but a failure is recorded so
      // `end_commands` reports it instead of losing the message.
      try {
        let _ = vk_cmd_end_render_pass(state)
      } catch {
        err => self.fail_later("end_render_pass failed: \{err}")
      }
    Dx12Commands(state) => dx12_end_render_pass(state)
  }
}

///|
pub fn CommandBuffer::bind_pipeline(
  self : CommandBuffer,
  pipeline : Pipeline,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      match pipeline.backend {
        VkPipeline(pipe) => vk_cmd_bind_pipeline(state, pipe)
        Dx12Pipeline(_) | Dx12Compute(_) =>
          self.fail_later("bind_pipeline received a DX12 pipeline on a Vulkan command buffer")
      }
    Dx12Commands(state) =>
      match pipeline.backend {
        Dx12Pipeline(pipe) => dx12_bind_pipeline(state, pipe)
        Dx12Compute(pipe) => dx12_bind_compute_pipeline(state, pipe)
        VkPipeline(_) =>
          self.fail_later("bind_pipeline received a Vulkan pipeline on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::bind_uniform(
  self : CommandBuffer,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      match (pipeline.backend, buffer.backend) {
        (VkPipeline(pipe), VkBuffer(b)) => self.on_vk(fn(state) {
          state.pending_uniforms.push((pipe, slot, b, offset, size))
        })
        _ => self.fail_later("bind_uniform mixes pipelines/buffers from different backends")
      }
    Dx12Commands(cmd) =>
      match (pipeline.backend, buffer.backend) {
        (Dx12Pipeline(pipe), Dx12Buffer(state)) => {
          // Uniform binding is recorded immediately (root CBV); failures surface
          // at the next raising call, matching the Vulkan path.
          let _ = dx12_bind_uniform(cmd, pipe.uniform_slots, slot, state, offset)
        }
        (Dx12Compute(pipe), Dx12Buffer(state)) => {
          let _ = dx12_bind_uniform(cmd, pipe.uniform_slots, slot, state, offset)
        }
        _ => self.fail_later("bind_uniform mixes pipelines/buffers from different backends")
      }
  }
}

///|
pub fn CommandBuffer::bind_texture(
  self : CommandBuffer,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
  sampler : Sampler,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      match (pipeline.backend, texture.backend, sampler.backend) {
        (VkPipeline(pipe), VkTexture(tex), VkSampler(samp)) => self.on_vk(fn(state) {
          state.pending_textures.push((pipe, slot, tex, samp))
        })
        _ => self.fail_later("bind_texture mixes pipelines/textures/samplers from different backends")
      }
    Dx12Commands(cmd) =>
      match (pipeline.backend, texture.backend) {
        (Dx12Pipeline(pipe), Dx12Texture(tex)) => {
          // The SRV table sits right after the root CBVs in the signature, and
          // the sampler table right after that; both are bound here.
          let dx12_sampler = match sampler.backend {
            Dx12Sampler(sampler) => Some(sampler)
            VkSampler(_) => None
          }
          // Slot i owns the root table right after the root CBVs; the sampler
          // table follows every texture slot.
          let _ = cmd.commands.set_texture(
            pipe.uniform_slots + slot,
            pipe.uniform_slots + pipe.texture_slots,
            tex.tex,
            sampler?=dx12_sampler,
          )
        }
        _ => self.fail_later("bind_texture mixes pipelines/textures from different backends")
      }
  }
}

///|
pub fn CommandBuffer::bind_storage(
  self : CommandBuffer,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  match (pipeline.backend, buffer.backend) {
    (VkPipeline(pipe), VkBuffer(b)) => self.on_vk(fn(state) {
      state.pending_storage.push((pipe, slot, b, offset, size))
    })
    (Dx12Compute(pipe), Dx12Buffer(state_buf)) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if !dx12_bind_storage_buffer(cmd, pipe, slot, state_buf) {
            dx12_unsupported(cmd, "this storage buffer binding")
          }
        }
        VkCommands(_) =>
          self.fail_later("bind_storage received a DX12 storage buffer on a Vulkan command buffer")
      }
    _ => self.fail_later("bind_storage mixes pipelines/buffers from different backends")
  }
}

///|
pub fn CommandBuffer::bind_storage_image(
  self : CommandBuffer,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      match (pipeline.backend, texture.backend) {
        (VkPipeline(pipe), VkTexture(tex)) =>
          self.on_vk(fn(state) { state.pending_storage_images.push((pipe, slot, tex)) })
        _ => self.fail_later("bind_storage_image mixes pipelines/textures from different backends")
      }
    Dx12Commands(cmd) =>
      match (pipeline.backend, texture.backend) {
        (Dx12Compute(pipe), Dx12Texture(tex)) => {
          let _ = dx12_bind_uav(cmd, pipe, slot, tex)
        }
        _ => self.fail_later("bind_storage_image mixes pipelines/textures from different backends")
      }
  }
}

///|
pub fn CommandBuffer::transition_for_compute(
  self : CommandBuffer,
  texture : Texture,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      match texture.backend {
        VkTexture(texture) => vk_cmd_transition_for_compute(state, texture)
        Dx12Texture(_) =>
          self.fail_later("transition_for_compute received a DX12 texture on a Vulkan command buffer")
      }
    Dx12Commands(state) =>
      match state.target {
        Some(target) => {
          let _ = state.commands.transition(target, @dx12.ResourceState::UnorderedAccess)
        }
        None => ()
      }
  }
}

///|
pub fn CommandBuffer::transition_for_sampling(
  self : CommandBuffer,
  texture : Texture,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      match texture.backend {
        VkTexture(texture) => vk_cmd_transition_for_sampling(state, texture)
        Dx12Texture(_) =>
          self.fail_later("transition_for_sampling received a DX12 texture on a Vulkan command buffer")
      }
    Dx12Commands(state) =>
      match texture.backend {
        Dx12Texture(tex) => {
          let _ = state.commands.transition(tex.tex, @dx12.ResourceState::ShaderResource)
        }
        VkTexture(_) =>
          self.fail_later("transition_for_sampling received a Vulkan texture on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::blit_texture(
  self : CommandBuffer,
  src : Texture,
  dst : Texture,
  filter? : Filter = Filter::Linear,
) -> Unit {
  match (src.backend, dst.backend) {
    (VkTexture(a), VkTexture(b)) =>
      self.on_vk(fn(state) { vk_cmd_blit_texture(state, a, b, filter) })
    _ => self.fail_later("blit_texture mixes textures from different backends")
  }
}

///|
pub fn CommandBuffer::reset_timestamps(
  self : CommandBuffer,
  pool : TimestampPool,
) -> Unit {
  match (self.backend, pool.backend) {
    (VkCommands(state), VkTimestampPool(pool)) => vk_cmd_reset_timestamps(state, pool)
    // D3D12 has no reset: a query is overwritten by the next EndQuery and the
    // resolve copies the heap wholesale, so there is nothing to clear.
    (Dx12Commands(_), Dx12TimestampPool(_)) => ()
    _ => self.fail_later("reset_timestamps received a pool from a different backend")
  }
}

///|
pub fn CommandBuffer::write_timestamp(
  self : CommandBuffer,
  pool : TimestampPool,
  index : Int,
  at_start? : Bool = false,
) -> Unit {
  match (self.backend, pool.backend) {
    (VkCommands(state), VkTimestampPool(pool)) =>
      vk_cmd_write_timestamp(state, pool, index, at_start)
    (Dx12Commands(cmd), Dx12TimestampPool(pool)) => {
      // `at_start` has no D3D12 equivalent: the query is recorded exactly where
      // the call sits in the command stream, which is what the parameter means.
      let _ = pool.write(cmd.commands, index)
      let mut seen = false
      for existing in cmd.ts_pools {
        if existing.handle() == pool.handle() {
          seen = true
        }
      }
      if !seen {
        cmd.ts_pools.push(pool)
      }
    }
    _ => self.fail_later("write_timestamp received a pool from a different backend")
  }
}

///|
pub fn CommandBuffer::bind_vertex(
  self : CommandBuffer,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      self.on_vk_buffer(buffer, fn(state, b) { vk_cmd_bind_vertex(state, slot, b, offset) })
    Dx12Commands(cmd) =>
      match buffer.backend {
        Dx12Buffer(state) => {
          let _ = dx12_bind_vertex(cmd, slot, state, offset)
        }
        VkBuffer(_) =>
          self.fail_later("bind_vertex received a Vulkan buffer on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::bind_index(
  self : CommandBuffer,
  buffer : Buffer,
  index_type : IndexType,
  offset? : Int = 0,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      self.on_vk_buffer(buffer, fn(state, b) { vk_cmd_bind_index(state, b, index_type, offset) })
    Dx12Commands(cmd) =>
      match buffer.backend {
        Dx12Buffer(state) => {
          let _ = dx12_bind_index(cmd, state, index_type, offset)
        }
        VkBuffer(_) =>
          self.fail_later("bind_index received a Vulkan buffer on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::push_constants_floats(
  self : CommandBuffer,
  pipeline : Pipeline,
  data : FixedArray[Float],
  offset? : Int = 0,
) -> Unit {
  match pipeline.backend {
    VkPipeline(pipe) => self.on_vk(fn(state) { vk_cmd_push_constants_floats(state, pipe, data, offset) })
    // Root constants take the float words verbatim (same bit pattern, 4 bytes each).
    Dx12Pipeline(state_pipe) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if data.length() * 4 != state_pipe.push_bytes ||
            !cmd.commands.set_root_constants(state_pipe.push_index, data) {
            dx12_unsupported(cmd, "these push constants")
          }
        }
        VkCommands(_) => ()
      }
    Dx12Compute(state_pipe) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if data.length() * 4 != state_pipe.push_bytes ||
            !cmd.commands.set_compute_root_constants(state_pipe.push_index, data) {
            dx12_unsupported(cmd, "these push constants")
          }
        }
        VkCommands(_) => ()
      }
  }
}

///|
/// Push a column-major `Mat4` as the 16 floats of a `mat4` push constant.
pub fn CommandBuffer::push_constants_mat4(
  self : CommandBuffer,
  pipeline : Pipeline,
  m : @tmath.Mat4,
  offset? : Int = 0,
) -> Unit {
  self.push_constants_floats(pipeline, m.to_cols_array(), offset~)
}

///|
pub fn CommandBuffer::push_constants_bytes(
  self : CommandBuffer,
  pipeline : Pipeline,
  data : Bytes,
  offset? : Int = 0,
) -> Unit {
  match pipeline.backend {
    VkPipeline(pipe) => self.on_vk(fn(state) { vk_cmd_push_constants_bytes(state, pipe, data, offset) })
    Dx12Pipeline(state_pipe) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if data.length() != state_pipe.push_bytes ||
            !cmd.commands.set_root_constants_bytes(state_pipe.push_index, data) {
            dx12_unsupported(cmd, "these push constants")
          }
        }
        VkCommands(_) => ()
      }
    Dx12Compute(state_pipe) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if data.length() != state_pipe.push_bytes ||
            !cmd.commands.set_compute_root_constants_bytes(state_pipe.push_index, data) {
            dx12_unsupported(cmd, "these push constants")
          }
        }
        VkCommands(_) => ()
      }
  }
}

///|
pub fn CommandBuffer::set_viewport(
  self : CommandBuffer,
  x : Float,
  y : Float,
  w : Float,
  h : Float,
) -> Unit {
  self.on_vk(fn(state) { vk_cmd_set_viewport(state, x, y, w, h) })
  // D3D12 has dynamic viewports too, but the backend fixes them at draw time
  // from the render target, so a caller-set viewport would be ignored.
  self.dx12_unsupported("a caller-set viewport")
}

///|
pub fn CommandBuffer::set_scissor(
  self : CommandBuffer,
  x : Int,
  y : Int,
  w : Int,
  h : Int,
) -> Unit {
  self.on_vk(fn(state) { vk_cmd_set_scissor(state, x, y, w, h) })
  self.dx12_unsupported("a caller-set scissor rect")
}

///|
pub fn CommandBuffer::set_stencil_reference(
  self : CommandBuffer,
  reference : Int,
) -> Unit {
  self.on_vk(fn(state) { vk_cmd_set_stencil_reference(state, reference) })
  self.dx12_unsupported("stencil state")
}

///|
pub fn CommandBuffer::bind_accel_struct(
  self : CommandBuffer,
  pipeline : Pipeline,
  slot : Int,
  accel : AccelStruct,
) -> Unit {
  match (pipeline.backend, accel.backend) {
    (VkPipeline(pipe), VkAccel(_)) =>
      self.on_vk(fn(cmd) { cmd.pending_accel.push((pipe, slot, accel)) })
    (Dx12Compute(pipe), Dx12Accel(dx12)) =>
      match self.backend {
        Dx12Commands(cmd) => {
          if !dx12_bind_accel_struct(cmd, pipe, slot, dx12) {
            dx12_unsupported(cmd, "this acceleration-structure binding")
          }
        }
        VkCommands(_) => ()
      }
    // Ray queries in a raster pipeline would need the accel table in the
    // graphics root signature, which is not wired yet.
    (Dx12Pipeline(_), Dx12Accel(_)) =>
      self.fail_later("bind_accel_struct is only wired for DX12 compute pipelines")
    _ => ()
  }
}

///|
/// Ray tracing capability: 0 = none, 1 = tier 1.0 / VK_KHR_ray_query. Ray
/// queries are the only ray tracing path the RHI exposes so far, so a value of 1
/// means acceleration structures plus in-shader queries are usable.
pub fn Device::raytracing_tier(self : Device) -> Int {
  match self.backend {
    Dx12Device(state) => @dx12.Device::raytracing_tier(state.device)
    VkDevice(state) => if state.caps.supports_ray_query { 1 } else { 0 }
  }
}

///|
pub fn Device::create_blas(
  self : Device,
  geometries : Array[RayGeometryDesc],
) -> AccelStruct raise RhiError {
  match self.backend {
    Dx12Device(state) => { backend: Dx12Accel(dx12_create_blas(state, geometries)) }
    VkDevice(_) => { backend: VkAccel(vk_create_blas(self.vk(), geometries)) }
  }
}

///|
pub fn Device::create_tlas(
  self : Device,
  instances : Array[RayInstanceDesc],
) -> AccelStruct raise RhiError {
  match self.backend {
    Dx12Device(state) => { backend: Dx12Accel(dx12_create_tlas(state, instances)) }
    VkDevice(_) => { backend: VkAccel(vk_create_tlas(self.vk(), instances)) }
  }
}

///|
pub fn AccelStruct::destroy(self : AccelStruct) -> Unit {
  match self.backend {
    VkAccel(state) => vk_accel_struct_destroy(state)
    Dx12Accel(accel) => accel.destroy()
  }
}

///|
pub fn CommandBuffer::draw(
  self : CommandBuffer,
  vertices : Int,
  instances : Int,
) -> Unit {
  self.draw_instanced(vertices, instances, 0, 0)
}

///|
pub fn CommandBuffer::draw_instanced(
  self : CommandBuffer,
  vertices : Int,
  instances : Int,
  first_vertex : Int,
  first_instance : Int,
) -> Unit {
  match self.backend {
    Dx12Commands(state) => dx12_draw(state, vertices, instances)
    VkCommands(state) =>
      vk_cmd_draw_instanced(state, vertices, instances, first_vertex, first_instance)
  }
}

///|
pub fn CommandBuffer::draw_indexed(
  self : CommandBuffer,
  index_count : Int,
  instances? : Int = 1,
) -> Unit {
  self.draw_indexed_full(index_count, instances, 0, 0, 0)
}

///|
pub fn CommandBuffer::draw_indexed_full(
  self : CommandBuffer,
  index_count : Int,
  instances : Int,
  first_index : Int,
  vertex_offset : Int,
  first_instance : Int,
) -> Unit {
  match self.backend {
    VkCommands(state) =>
      vk_cmd_draw_indexed_full(
        state,
        index_count,
        instances,
        first_index,
        vertex_offset,
        first_instance,
      )
    Dx12Commands(cmd) =>
      dx12_draw_indexed(cmd, index_count, instances, first_index, vertex_offset)
  }
}

///|
pub fn CommandBuffer::dispatch(
  self : CommandBuffer,
  x : Int,
  y : Int,
  z : Int,
) -> Unit {
  match self.backend {
    VkCommands(state) => vk_cmd_dispatch(state, x, y, z)
    Dx12Commands(state) => {
      let _ = state.commands.dispatch(x, y, z~)
    }
  }
}

///|
pub fn CommandBuffer::draw_indirect(
  self : CommandBuffer,
  buffer : Buffer,
  draw_count : Int,
  offset? : Int = 0,
  stride? : Int = 16,
) -> Unit {
  match self.backend {
    VkCommands(_) => self.on_vk_buffer(buffer, fn(state, b) {
      vk_cmd_draw_indirect(state, b, draw_count, offset, stride)
    })
    Dx12Commands(cmd) =>
      match buffer.backend {
        Dx12Buffer(state) =>
          dx12_indirect(cmd, state, @dx12.IndirectKind::Draw, draw_count, offset, stride)
        VkBuffer(_) =>
          self.fail_later("draw_indirect received a Vulkan buffer on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::draw_indexed_indirect(
  self : CommandBuffer,
  buffer : Buffer,
  draw_count : Int,
  offset? : Int = 0,
  stride? : Int = 20,
) -> Unit {
  match self.backend {
    VkCommands(_) => self.on_vk_buffer(buffer, fn(state, b) {
      vk_cmd_draw_indexed_indirect(state, b, draw_count, offset, stride)
    })
    Dx12Commands(cmd) =>
      match buffer.backend {
        Dx12Buffer(state) => dx12_indirect(
          cmd,
          state,
          @dx12.IndirectKind::DrawIndexed,
          draw_count,
          offset,
          stride,
        )
        VkBuffer(_) =>
          self.fail_later("draw_indexed_indirect received a Vulkan buffer on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::draw_indirect_count(
  self : CommandBuffer,
  buffer : Buffer,
  count_buffer : Buffer,
  max_draw_count : Int,
  offset? : Int = 0,
  count_offset? : Int = 0,
  stride? : Int = 16,
) -> Unit {
  match self.backend {
    VkCommands(_) => self.on_vk_buffers(buffer, count_buffer, fn(state, a, b) {
      vk_cmd_draw_indirect_count(state, a, b, max_draw_count, offset, count_offset, stride)
    })
    Dx12Commands(cmd) =>
      match (buffer.backend, count_buffer.backend) {
        (Dx12Buffer(args), Dx12Buffer(counts)) =>
          dx12_indirect_counted(
            cmd,
            args,
            counts,
            @dx12.IndirectKind::Draw,
            max_draw_count,
            offset,
            count_offset,
            stride,
          )
        _ => self.fail_later("draw_indirect_count mixes buffers from different backends")
      }
  }
}

///|
pub fn CommandBuffer::draw_indexed_indirect_count(
  self : CommandBuffer,
  buffer : Buffer,
  count_buffer : Buffer,
  max_draw_count : Int,
  offset? : Int = 0,
  count_offset? : Int = 0,
  stride? : Int = 20,
) -> Unit {
  match self.backend {
    VkCommands(_) => self.on_vk_buffers(buffer, count_buffer, fn(state, a, b) {
      vk_cmd_draw_indexed_indirect_count(
        state,
        a,
        b,
        max_draw_count,
        offset,
        count_offset,
        stride,
      )
    })
    Dx12Commands(cmd) =>
      match (buffer.backend, count_buffer.backend) {
        (Dx12Buffer(args), Dx12Buffer(counts)) =>
          dx12_indirect_counted(
            cmd,
            args,
            counts,
            @dx12.IndirectKind::DrawIndexed,
            max_draw_count,
            offset,
            count_offset,
            stride,
          )
        _ => self.fail_later("draw_indexed_indirect_count mixes buffers from different backends")
      }
  }
}

///|
pub fn CommandBuffer::dispatch_indirect(
  self : CommandBuffer,
  buffer : Buffer,
  offset? : Int = 0,
) -> Unit {
  match self.backend {
    VkCommands(_) =>
      self.on_vk_buffer(buffer, fn(state, b) { vk_cmd_dispatch_indirect(state, b, offset) })
    Dx12Commands(cmd) =>
      match buffer.backend {
        Dx12Buffer(state) =>
          dx12_indirect(cmd, state, @dx12.IndirectKind::Dispatch, 1, offset, 12)
        VkBuffer(_) =>
          self.fail_later("dispatch_indirect received a Vulkan buffer on a DX12 command buffer")
      }
  }
}

///|
pub fn CommandBuffer::draw_mesh_tasks(
  self : CommandBuffer,
  x : Int,
  y : Int,
  z : Int,
) -> Unit {
  self.on_vk(fn(state) { vk_cmd_draw_mesh_tasks(state, x, y, z) })
  match self.backend {
    Dx12Commands(cmd) =>
      match cmd.target {
        Some(target) => {
          let _ = cmd.commands.dispatch_mesh(target, x, y=y, z=z)
        }
        None => dx12_unsupported(cmd, "a mesh dispatch without a bound render target")
      }
    VkCommands(_) => ()
  }
}

///|
pub fn CommandBuffer::draw_mesh_tasks_indirect(
  self : CommandBuffer,
  buffer : Buffer,
  draw_count : Int,
  offset? : Int = 0,
  stride? : Int = 12,
) -> Unit {
  self.on_vk_buffer(buffer, fn(state, b) {
    vk_cmd_draw_mesh_tasks_indirect(state, b, draw_count, offset, stride)
  })
  self.dx12_unsupported("mesh shaders")
}

///|
pub fn CommandBuffer::bind_bindless_heap(
  self : CommandBuffer,
  pipeline : Pipeline,
  heap : BindlessHeap,
  set_index? : Int = 1,
) -> Unit {
  match pipeline.backend {
    VkPipeline(pipe) => self.on_vk(fn(state) { vk_cmd_bind_bindless_heap(state, pipe, heap.inner, set_index) })
    Dx12Pipeline(_) => self.dx12_unsupported("bindless descriptor heaps")
    Dx12Compute(_) => self.dx12_unsupported("bindless descriptor heaps")
  }
}

///|
pub fn CommandBuffer::copy_buffer(
  self : CommandBuffer,
  src : Buffer,
  dst : Buffer,
  size : Int,
) -> Unit {
  self.on_vk_buffers(src, dst, fn(state, a, b) { vk_cmd_copy_buffer(state, a, b, size) })
  self.dx12_unsupported("a buffer-to-buffer copy")
}

///|
pub fn CommandBuffer::barrier(self : CommandBuffer) -> Unit {
  self.on_vk(fn(state) { vk_cmd_barrier(state) })
}

///|
/// A scoped render pass. Drawing goes through this handle instead of the raw
/// `CommandBuffer`, and the pass is closed even when the closure raises, so a
/// recording session cannot be left half-open.
pub struct RenderPass {
  priv cmd : CommandBuffer
}

///|
/// Records `draw` inside a `begin_render_pass` / `end_render_pass` pair.
pub fn CommandBuffer::render_pass(
  self : CommandBuffer,
  colors : Array[RenderTargetDesc],
  depth? : DepthTargetDesc,
  draw : (RenderPass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  self.begin_render_pass(colors, depth?=depth)
  let pass : RenderPass = { cmd: self }
  let pending : RhiError? = try {
    draw(pass)
    None
  } catch {
    e => Some(e)
  }
  // The pass is always closed, then the callback failure is re-raised with its
  // original type.
  self.end_render_pass()
  match pending {
    Some(e) => raise e
    None => ()
  }
}

///|
pub fn RenderPass::bind_pipeline(self : RenderPass, pipeline : Pipeline) -> Unit {
  self.cmd.bind_pipeline(pipeline)
}

///|
pub fn RenderPass::bind_uniform(
  self : RenderPass,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  self.cmd.bind_uniform(pipeline, slot, buffer, offset=offset, size=size)
}

///|
pub fn RenderPass::bind_texture(
  self : RenderPass,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
  sampler : Sampler,
) -> Unit {
  self.cmd.bind_texture(pipeline, slot, texture, sampler)
}

///|
pub fn RenderPass::bind_storage(
  self : RenderPass,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  self.cmd.bind_storage(pipeline, slot, buffer, offset=offset, size=size)
}

///|
pub fn RenderPass::bind_accel_struct(
  self : RenderPass,
  pipeline : Pipeline,
  slot : Int,
  accel : AccelStruct,
) -> Unit {
  self.cmd.bind_accel_struct(pipeline, slot, accel)
}

///|
pub fn RenderPass::bind_bindless_heap(
  self : RenderPass,
  pipeline : Pipeline,
  heap : BindlessHeap,
  set_index? : Int = 1,
) -> Unit {
  self.cmd.bind_bindless_heap(pipeline, heap, set_index=set_index)
}

///|
pub fn RenderPass::bind_group(self : RenderPass, group : BindGroup) -> Unit {
  self.cmd.bind_group(group)
}

///|
pub fn RenderPass::bind_vertex(
  self : RenderPass,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
) -> Unit {
  self.cmd.bind_vertex(slot, buffer, offset=offset)
}

///|
pub fn RenderPass::bind_index(
  self : RenderPass,
  buffer : Buffer,
  index_type : IndexType,
  offset? : Int = 0,
) -> Unit {
  self.cmd.bind_index(buffer, index_type, offset=offset)
}

///|
pub fn RenderPass::push_constants_floats(
  self : RenderPass,
  pipeline : Pipeline,
  data : FixedArray[Float],
  offset? : Int = 0,
) -> Unit {
  self.cmd.push_constants_floats(pipeline, data, offset=offset)
}

///|
pub fn RenderPass::push_constants_bytes(
  self : RenderPass,
  pipeline : Pipeline,
  data : Bytes,
  offset? : Int = 0,
) -> Unit {
  self.cmd.push_constants_bytes(pipeline, data, offset=offset)
}

///|
pub fn RenderPass::push_constants_mat4(
  self : RenderPass,
  pipeline : Pipeline,
  value : @tmath.Mat4,
) -> Unit {
  self.cmd.push_constants_mat4(pipeline, value)
}

///|
pub fn RenderPass::set_viewport(
  self : RenderPass,
  x : Float,
  y : Float,
  w : Float,
  h : Float,
) -> Unit {
  self.cmd.set_viewport(x, y, w, h)
}

///|
pub fn RenderPass::set_scissor(
  self : RenderPass,
  x : Int,
  y : Int,
  w : Int,
  h : Int,
) -> Unit {
  self.cmd.set_scissor(x, y, w, h)
}

///|
pub fn RenderPass::set_stencil_reference(self : RenderPass, reference : Int) -> Unit {
  self.cmd.set_stencil_reference(reference)
}

///|
pub fn RenderPass::draw(self : RenderPass, vertices : Int, instances : Int) -> Unit {
  self.cmd.draw(vertices, instances)
}

///|
pub fn RenderPass::draw_instanced(
  self : RenderPass,
  vertices : Int,
  instances : Int,
  first_vertex : Int,
  first_instance : Int,
) -> Unit {
  self.cmd.draw_instanced(vertices, instances, first_vertex, first_instance)
}

///|
pub fn RenderPass::draw_indexed(
  self : RenderPass,
  index_count : Int,
  instances? : Int = 1,
) -> Unit {
  self.cmd.draw_indexed(index_count, instances=instances)
}

///|
pub fn RenderPass::draw_indexed_full(
  self : RenderPass,
  index_count : Int,
  instances : Int,
  first_index : Int,
  vertex_offset : Int,
  first_instance : Int,
) -> Unit {
  self.cmd.draw_indexed_full(
    index_count,
    instances,
    first_index,
    vertex_offset,
    first_instance,
  )
}

///|
pub fn RenderPass::draw_indirect(
  self : RenderPass,
  buffer : Buffer,
  draw_count : Int,
  offset? : Int = 0,
  stride? : Int = 16,
) -> Unit {
  self.cmd.draw_indirect(buffer, draw_count, offset=offset, stride=stride)
}

///|
pub fn RenderPass::draw_indexed_indirect(
  self : RenderPass,
  buffer : Buffer,
  draw_count : Int,
  offset? : Int = 0,
  stride? : Int = 20,
) -> Unit {
  self.cmd.draw_indexed_indirect(buffer, draw_count, offset=offset, stride=stride)
}

///|
pub fn RenderPass::draw_indirect_count(
  self : RenderPass,
  buffer : Buffer,
  count_buffer : Buffer,
  max_draw_count : Int,
  offset? : Int = 0,
  count_offset? : Int = 0,
  stride? : Int = 16,
) -> Unit {
  self.cmd.draw_indirect_count(
    buffer,
    count_buffer,
    max_draw_count,
    offset=offset,
    count_offset=count_offset,
    stride=stride,
  )
}

///|
pub fn RenderPass::draw_indexed_indirect_count(
  self : RenderPass,
  buffer : Buffer,
  count_buffer : Buffer,
  max_draw_count : Int,
  offset? : Int = 0,
  count_offset? : Int = 0,
  stride? : Int = 20,
) -> Unit {
  self.cmd.draw_indexed_indirect_count(
    buffer,
    count_buffer,
    max_draw_count,
    offset=offset,
    count_offset=count_offset,
    stride=stride,
  )
}

///|
pub fn RenderPass::draw_mesh_tasks(self : RenderPass, x : Int, y : Int, z : Int) -> Unit {
  self.cmd.draw_mesh_tasks(x, y, z)
}

///|
pub fn RenderPass::transition_for_sampling(
  self : RenderPass,
  texture : Texture,
) -> Unit {
  self.cmd.transition_for_sampling(texture)
}

///|
/// Records `draw` inside a `begin_swapchain_pass` / `end_swapchain_pass` pair,
/// closing the pass even when the callback raises.
pub fn CommandBuffer::swapchain_pass(
  self : CommandBuffer,
  swapchain : Swapchain,
  load_op? : LoadOp = LoadOp::Clear,
  clear_color? : ClearColor,
  draw : (RenderPass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  self.begin_swapchain_pass(swapchain, load_op=load_op, clear_color?=clear_color)
  let pass : RenderPass = { cmd: self }
  let pending : RhiError? = try {
    draw(pass)
    None
  } catch {
    e => Some(e)
  }
  self.end_swapchain_pass()
  match pending {
    Some(e) => raise e
    None => ()
  }
}

///|
/// A scoped compute encoder. Compute has no begin/end on either backend, so the
/// handle only narrows the API surface to compute-relevant calls.
pub struct ComputePass {
  priv cmd : CommandBuffer
}

///|
pub fn CommandBuffer::compute_pass(
  self : CommandBuffer,
  encode : (ComputePass) -> Unit raise RhiError,
) -> Unit raise RhiError {
  encode({ cmd: self })
}

///|
pub fn ComputePass::bind_pipeline(self : ComputePass, pipeline : Pipeline) -> Unit {
  self.cmd.bind_pipeline(pipeline)
}

///|
pub fn ComputePass::bind_uniform(
  self : ComputePass,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  self.cmd.bind_uniform(pipeline, slot, buffer, offset=offset, size=size)
}

///|
pub fn ComputePass::bind_storage(
  self : ComputePass,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> Unit {
  self.cmd.bind_storage(pipeline, slot, buffer, offset=offset, size=size)
}

///|
pub fn ComputePass::bind_storage_image(
  self : ComputePass,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
) -> Unit {
  self.cmd.bind_storage_image(pipeline, slot, texture)
}

///|
pub fn ComputePass::bind_group(self : ComputePass, group : BindGroup) -> Unit {
  self.cmd.bind_group(group)
}

///|
pub fn ComputePass::bind_bindless_heap(
  self : ComputePass,
  pipeline : Pipeline,
  heap : BindlessHeap,
  set_index? : Int = 1,
) -> Unit {
  self.cmd.bind_bindless_heap(pipeline, heap, set_index=set_index)
}

///|
pub fn ComputePass::push_constants_bytes(
  self : ComputePass,
  pipeline : Pipeline,
  data : Bytes,
  offset? : Int = 0,
) -> Unit {
  self.cmd.push_constants_bytes(pipeline, data, offset=offset)
}

///|
pub fn ComputePass::push_constants_floats(
  self : ComputePass,
  pipeline : Pipeline,
  data : FixedArray[Float],
  offset? : Int = 0,
) -> Unit {
  self.cmd.push_constants_floats(pipeline, data, offset=offset)
}

///|
pub fn ComputePass::transition_for_compute(
  self : ComputePass,
  texture : Texture,
) -> Unit {
  self.cmd.transition_for_compute(texture)
}

///|
pub fn ComputePass::dispatch(self : ComputePass, x : Int, y : Int, z : Int) -> Unit {
  self.cmd.dispatch(x, y, z)
}

///|
pub fn ComputePass::dispatch_indirect(
  self : ComputePass,
  buffer : Buffer,
  offset? : Int = 0,
) -> Unit {
  self.cmd.dispatch_indirect(buffer, offset=offset)
}

///|
pub fn ComputePass::write_timestamp(
  self : ComputePass,
  pool : TimestampPool,
  index : Int,
  at_start? : Bool = false,
) -> Unit {
  self.cmd.write_timestamp(pool, index, at_start=at_start)
}

///|
/// One recorded binding.
priv enum BindOp {
  Uniform(Pipeline, Int, Buffer, Int, Int)
  Texture(Pipeline, Int, Texture, Sampler)
  Storage(Pipeline, Int, Buffer, Int, Int)
  StorageImage(Pipeline, Int, Texture)
  Accel(Pipeline, Int, AccelStruct)
}

///|
/// A reusable set of bindings. Recording the descriptor set once and replaying
/// it per object removes the `bind_uniform(pipeline, slot, ...)` repetition that
/// the flat `CommandBuffer` API forces on every draw.
pub(all) struct BindGroup {
  priv ops : Array[BindOp]
}

///|
pub fn BindGroup::new() -> BindGroup {
  { ops: [] }
}

///|
pub fn BindGroup::uniform(
  self : BindGroup,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> BindGroup {
  self.ops.push(BindOp::Uniform(pipeline, slot, buffer, offset, size))
  self
}

///|
pub fn BindGroup::texture(
  self : BindGroup,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
  sampler : Sampler,
) -> BindGroup {
  self.ops.push(BindOp::Texture(pipeline, slot, texture, sampler))
  self
}

///|
pub fn BindGroup::storage(
  self : BindGroup,
  pipeline : Pipeline,
  slot : Int,
  buffer : Buffer,
  offset? : Int = 0,
  size? : Int = -1,
) -> BindGroup {
  self.ops.push(BindOp::Storage(pipeline, slot, buffer, offset, size))
  self
}

///|
pub fn BindGroup::storage_image(
  self : BindGroup,
  pipeline : Pipeline,
  slot : Int,
  texture : Texture,
) -> BindGroup {
  self.ops.push(BindOp::StorageImage(pipeline, slot, texture))
  self
}

///|
pub fn BindGroup::accel(
  self : BindGroup,
  pipeline : Pipeline,
  slot : Int,
  accel : AccelStruct,
) -> BindGroup {
  self.ops.push(BindOp::Accel(pipeline, slot, accel))
  self
}

///|
pub fn BindGroup::len(self : BindGroup) -> Int {
  self.ops.length()
}

///|
pub fn BindGroup::is_empty(self : BindGroup) -> Bool {
  self.ops.length() == 0
}

///|
/// Replays every recorded binding in insertion order.
pub fn CommandBuffer::bind_group(self : CommandBuffer, group : BindGroup) -> Unit {
  for op in group.ops {
    match op {
      Uniform(p, slot, b, off, sz) =>
        self.bind_uniform(p, slot, b, offset=off, size=sz)
      Texture(p, slot, t, s) => self.bind_texture(p, slot, t, s)
      Storage(p, slot, b, off, sz) =>
        self.bind_storage(p, slot, b, offset=off, size=sz)
      StorageImage(p, slot, t) => self.bind_storage_image(p, slot, t)
      Accel(p, slot, a) => self.bind_accel_struct(p, slot, a)
    }
  }
}