// L0 native Apple Metal bindings (`laplaceliu/tycho_metal`).
//
// Wraps `metal_stub.c` (pure C99 dlopen + libobjc runtime bridge against
// Metal.framework, QuartzCore.framework, and Foundation.framework).

// ---------------------------------------------------------------------------
// Raw C FFI
// ---------------------------------------------------------------------------

extern "c" fn mtl_is_available_ffi() -> Int32 = "tycho_mtl_is_available"

extern "c" fn mtl_last_error_len_ffi() -> Int32 = "tycho_mtl_last_error_len"

#borrow(dst)
extern "c" fn mtl_last_error_copy_ffi(dst : FixedArray[Byte], cap : Int32) = "tycho_mtl_last_error_copy"

extern "c" fn mtl_device_create_ffi(validation : Int32) -> UInt64 = "tycho_mtl_device_create"

extern "c" fn mtl_device_destroy_ffi(dev : UInt64) = "tycho_mtl_device_destroy"

extern "c" fn mtl_device_name_len_ffi(dev : UInt64) -> Int32 = "tycho_mtl_device_name_len"

#borrow(dst)
extern "c" fn mtl_device_name_copy_ffi(
  dev : UInt64,
  dst : FixedArray[Byte],
  cap : Int32,
) = "tycho_mtl_device_name_copy"

#borrow(out8)
extern "c" fn mtl_device_caps_ffi(dev : UInt64, out8 : FixedArray[Int32]) = "tycho_mtl_device_caps"

extern "c" fn mtl_device_validation_errors_ffi(dev : UInt64) -> Int32 = "tycho_mtl_device_validation_errors"

extern "c" fn mtl_device_wait_idle_ffi(dev : UInt64) = "tycho_mtl_device_wait_idle"

extern "c" fn mtl_device_active_allocs_ffi(dev : UInt64) -> Int32 = "tycho_mtl_device_active_allocs"

extern "c" fn mtl_device_used_bytes_ffi(dev : UInt64) -> UInt64 = "tycho_mtl_device_used_bytes"

extern "c" fn mtl_buffer_create_ffi(
  dev : UInt64,
  size : Int32,
  storage_mode : Int32,
) -> UInt64 = "tycho_mtl_buffer_create"

extern "c" fn mtl_buffer_destroy_ffi(buf : UInt64) = "tycho_mtl_buffer_destroy"

#borrow(data)
extern "c" fn mtl_buffer_upload_ffi(
  buf : UInt64,
  data : Bytes,
  offset : Int32,
  len : Int32,
) -> Int32 = "tycho_mtl_buffer_upload"

#borrow(data)
extern "c" fn mtl_buffer_upload_floats_ffi(
  buf : UInt64,
  data : FixedArray[Float],
  offset_bytes : Int32,
  count : Int32,
) -> Int32 = "tycho_mtl_buffer_upload_floats"

#borrow(out)
extern "c" fn mtl_buffer_download_ffi(
  buf : UInt64,
  out : FixedArray[Byte],
  len : Int32,
) -> Int32 = "tycho_mtl_buffer_download"

extern "c" fn mtl_texture_create_ffi(
  dev : UInt64,
  width : Int32,
  height : Int32,
  fmt_code : Int32,
  mip_levels : Int32,
  layers : Int32,
  samples : Int32,
  is_cube : Int32,
  usage_bits : Int32,
) -> UInt64 = "tycho_mtl_texture_create"

extern "c" fn mtl_texture_destroy_ffi(tex : UInt64) = "tycho_mtl_texture_destroy"

#borrow(data)
extern "c" fn mtl_texture_upload_region_ffi(
  tex : UInt64,
  x : Int32,
  y : Int32,
  w : Int32,
  h : Int32,
  layer : Int32,
  mip : Int32,
  data : Bytes,
  data_len : Int32,
) -> Int32 = "tycho_mtl_texture_upload_region"

extern "c" fn mtl_texture_generate_mipmaps_ffi(tex : UInt64) -> Int32 = "tycho_mtl_texture_generate_mipmaps"

#borrow(out)
extern "c" fn mtl_texture_readback_ffi(
  tex : UInt64,
  mip : Int32,
  layer : Int32,
  out : FixedArray[Byte],
  out_len : Int32,
) -> Int32 = "tycho_mtl_texture_readback"

extern "c" fn mtl_sampler_create_ffi(
  dev : UInt64,
  min_linear : Int32,
  mag_linear : Int32,
  mip_linear : Int32,
  addr_u : Int32,
  addr_v : Int32,
  addr_w : Int32,
  border_color : Int32,
  max_aniso : Float,
  min_lod : Float,
  max_lod : Float,
  compare_op : Int32,
) -> UInt64 = "tycho_mtl_sampler_create"

extern "c" fn mtl_sampler_destroy_ffi(smp : UInt64) = "tycho_mtl_sampler_destroy"

#borrow(vs_words, fs_words, vs_entry, fs_entry, state, color_formats, blend_params, vtx_layouts, vtx_attrs)
extern "c" fn mtl_render_pipeline_create_ffi(
  dev : UInt64,
  vs_words : FixedArray[UInt32],
  vs_word_count : Int32,
  fs_words : FixedArray[UInt32],
  fs_word_count : Int32,
  vs_entry : Bytes,
  vs_entry_len : Int32,
  fs_entry : Bytes,
  fs_entry_len : Int32,
  state : FixedArray[Int32],
  state_len : Int32,
  bias_const : Float,
  bias_slope : Float,
  color_formats : FixedArray[Int32],
  color_count : Int32,
  blend_params : FixedArray[Int32],
  blend_count : Int32,
  vtx_layouts : FixedArray[Int32],
  vtx_layout_count : Int32,
  vtx_attrs : FixedArray[Int32],
  vtx_attr_count : Int32,
) -> UInt64 = "tycho_mtl_render_pipeline_create"

extern "c" fn mtl_render_pipeline_destroy_ffi(pipe : UInt64) = "tycho_mtl_render_pipeline_destroy"

#borrow(cs_words)
extern "c" fn mtl_compute_pipeline_create_ffi(
  dev : UInt64,
  cs_words : FixedArray[UInt32],
  cs_word_count : Int32,
  local_x : Int32,
  local_y : Int32,
  local_z : Int32,
) -> UInt64 = "tycho_mtl_compute_pipeline_create"

extern "c" fn mtl_compute_pipeline_destroy_ffi(pipe : UInt64) = "tycho_mtl_compute_pipeline_destroy"

extern "c" fn mtl_bindless_create_ffi(dev : UInt64, capacity : Int32) -> UInt64 = "tycho_mtl_bindless_create"

extern "c" fn mtl_bindless_destroy_ffi(heap : UInt64) = "tycho_mtl_bindless_destroy"

extern "c" fn mtl_bindless_register_ffi(
  heap : UInt64,
  tex : UInt64,
  smp : UInt64,
) -> Int32 = "tycho_mtl_bindless_register"

extern "c" fn mtl_bindless_unregister_ffi(heap : UInt64, slot : Int32) = "tycho_mtl_bindless_unregister"

extern "c" fn mtl_swapchain_create_ffi(
  dev : UInt64,
  layer : UInt64,
  width : Int32,
  height : Int32,
  has_depth : Int32,
  depth_format : Int32,
  enable_readback : Int32,
  vsync : Int32,
) -> UInt64 = "tycho_mtl_swapchain_create"

extern "c" fn mtl_swapchain_destroy_ffi(sc : UInt64) = "tycho_mtl_swapchain_destroy"

extern "c" fn mtl_swapchain_resize_ffi(
  sc : UInt64,
  width : Int32,
  height : Int32,
) -> Int32 = "tycho_mtl_swapchain_resize"

#borrow(out)
extern "c" fn mtl_swapchain_readback_ffi(
  sc : UInt64,
  out : FixedArray[Byte],
  out_len : Int32,
) -> Int32 = "tycho_mtl_swapchain_readback"

extern "c" fn mtl_swapchain_begin_frame_ffi(
  sc : UInt64,
  begin_pass : Int32,
  r : Float,
  g : Float,
  b : Float,
  a : Float,
) -> UInt64 = "tycho_mtl_swapchain_begin_frame"

extern "c" fn mtl_swapchain_end_frame_ffi(sc : UInt64, cmd : UInt64) -> Int32 = "tycho_mtl_swapchain_end_frame"

extern "c" fn mtl_swapchain_present_texture_ffi(
  sc : UInt64,
  tex : UInt64,
) -> Int32 = "tycho_mtl_swapchain_present_texture"

extern "c" fn mtl_timestamp_pool_create_ffi(count : Int32) -> UInt64 = "tycho_mtl_timestamp_pool_create"

extern "c" fn mtl_timestamp_pool_destroy_ffi(pool : UInt64) = "tycho_mtl_timestamp_pool_destroy"

#borrow(out)
extern "c" fn mtl_timestamp_pool_read_ffi(
  pool : UInt64,
  out : FixedArray[Double],
  count : Int32,
) = "tycho_mtl_timestamp_pool_read"

extern "c" fn mtl_fence_create_ffi(signaled : Int32) -> UInt64 = "tycho_mtl_fence_create"

extern "c" fn mtl_fence_destroy_ffi(fence : UInt64) = "tycho_mtl_fence_destroy"

extern "c" fn mtl_fence_wait_ffi(fence : UInt64) = "tycho_mtl_fence_wait"

extern "c" fn mtl_fence_reset_ffi(fence : UInt64) = "tycho_mtl_fence_reset"

extern "c" fn mtl_cmd_begin_ffi(dev : UInt64) -> UInt64 = "tycho_mtl_cmd_begin"

extern "c" fn mtl_cmd_end_wait_ffi(cmd : UInt64) -> Int32 = "tycho_mtl_cmd_end_wait"

extern "c" fn mtl_cmd_submit_async_ffi(cmd : UInt64, fence : UInt64) -> Int32 = "tycho_mtl_cmd_submit_async"

#borrow(color_texs, resolve_texs, color_load_ops, color_store_ops, clear_rgba, color_layers, color_mips)
extern "c" fn mtl_cmd_begin_render_pass_ffi(
  cmd : UInt64,
  color_texs : FixedArray[UInt64],
  resolve_texs : FixedArray[UInt64],
  color_load_ops : FixedArray[Int32],
  color_store_ops : FixedArray[Int32],
  clear_rgba : FixedArray[Float],
  color_layers : FixedArray[Int32],
  color_mips : FixedArray[Int32],
  color_count : Int32,
  depth_tex : UInt64,
  depth_load : Int32,
  depth_store : Int32,
  clear_depth : Float,
  stencil_load : Int32,
  stencil_store : Int32,
  clear_stencil : UInt32,
  depth_layer : Int32,
  depth_mip : Int32,
) -> Int32 = "tycho_mtl_cmd_begin_render_pass"

extern "c" fn mtl_cmd_end_render_pass_ffi(cmd : UInt64) = "tycho_mtl_cmd_end_render_pass"

extern "c" fn mtl_cmd_begin_swapchain_pass_ffi(
  cmd : UInt64,
  sc : UInt64,
  load_op : Int32,
  r : Float,
  g : Float,
  b : Float,
  a : Float,
) -> Int32 = "tycho_mtl_cmd_begin_swapchain_pass"

extern "c" fn mtl_cmd_bind_render_pipeline_ffi(cmd : UInt64, pipe : UInt64) = "tycho_mtl_cmd_bind_render_pipeline"

extern "c" fn mtl_cmd_bind_compute_pipeline_ffi(cmd : UInt64, pipe : UInt64) = "tycho_mtl_cmd_bind_compute_pipeline"

extern "c" fn mtl_cmd_bind_vertex_ffi(
  cmd : UInt64,
  slot : Int32,
  buf : UInt64,
  offset : Int32,
) = "tycho_mtl_cmd_bind_vertex"

extern "c" fn mtl_cmd_bind_index_ffi(
  cmd : UInt64,
  buf : UInt64,
  is_u32 : Int32,
  offset : Int32,
) = "tycho_mtl_cmd_bind_index"

extern "c" fn mtl_cmd_bind_buffer_ffi(
  cmd : UInt64,
  binding : Int32,
  buf : UInt64,
  offset : Int32,
  is_compute : Int32,
) = "tycho_mtl_cmd_bind_buffer"

extern "c" fn mtl_cmd_bind_texture_ffi(
  cmd : UInt64,
  binding : Int32,
  tex : UInt64,
  smp : UInt64,
  is_compute : Int32,
) = "tycho_mtl_cmd_bind_texture"

extern "c" fn mtl_cmd_bind_bindless_ffi(
  cmd : UInt64,
  heap : UInt64,
  is_compute : Int32,
) = "tycho_mtl_cmd_bind_bindless"

extern "c" fn mtl_cmd_set_viewport_ffi(
  cmd : UInt64,
  x : Float,
  y : Float,
  w : Float,
  h : Float,
) = "tycho_mtl_cmd_set_viewport"

extern "c" fn mtl_cmd_set_scissor_ffi(
  cmd : UInt64,
  x : Int32,
  y : Int32,
  w : Int32,
  h : Int32,
) = "tycho_mtl_cmd_set_scissor"

extern "c" fn mtl_cmd_set_stencil_ref_ffi(cmd : UInt64, ref_val : Int32) = "tycho_mtl_cmd_set_stencil_ref"

#borrow(data)
extern "c" fn mtl_cmd_push_constants_ffi(
  cmd : UInt64,
  data : Bytes,
  len : Int32,
  is_compute : Int32,
) = "tycho_mtl_cmd_push_constants"

#borrow(data)
extern "c" fn mtl_cmd_push_constants_floats_ffi(
  cmd : UInt64,
  data : FixedArray[Float],
  count : Int32,
  is_compute : Int32,
) = "tycho_mtl_cmd_push_constants_floats"

extern "c" fn mtl_cmd_draw_ffi(
  cmd : UInt64,
  vertex_count : Int32,
  instance_count : Int32,
  first_vertex : Int32,
  first_instance : Int32,
) = "tycho_mtl_cmd_draw"

extern "c" fn mtl_cmd_draw_indexed_ffi(
  cmd : UInt64,
  index_count : Int32,
  instance_count : Int32,
  first_index : Int32,
  vertex_offset : Int32,
  first_instance : Int32,
) = "tycho_mtl_cmd_draw_indexed"

extern "c" fn mtl_cmd_draw_indirect_ffi(
  cmd : UInt64,
  buf : UInt64,
  offset : Int32,
  draw_count : Int32,
  stride : Int32,
) = "tycho_mtl_cmd_draw_indirect"

extern "c" fn mtl_cmd_draw_indexed_indirect_ffi(
  cmd : UInt64,
  buf : UInt64,
  offset : Int32,
  draw_count : Int32,
  stride : Int32,
) = "tycho_mtl_cmd_draw_indexed_indirect"

extern "c" fn mtl_cmd_draw_indirect_count_ffi(
  cmd : UInt64,
  buf : UInt64,
  count_buf : UInt64,
  offset : Int32,
  count_offset : Int32,
  max_draws : Int32,
  stride : Int32,
) = "tycho_mtl_cmd_draw_indirect_count"

extern "c" fn mtl_cmd_draw_indexed_indirect_count_ffi(
  cmd : UInt64,
  buf : UInt64,
  count_buf : UInt64,
  offset : Int32,
  count_offset : Int32,
  max_draws : Int32,
  stride : Int32,
) = "tycho_mtl_cmd_draw_indexed_indirect_count"

extern "c" fn mtl_cmd_dispatch_ffi(
  cmd : UInt64,
  gx : Int32,
  gy : Int32,
  gz : Int32,
) = "tycho_mtl_cmd_dispatch"

extern "c" fn mtl_cmd_dispatch_indirect_ffi(
  cmd : UInt64,
  buf : UInt64,
  offset : Int32,
) = "tycho_mtl_cmd_dispatch_indirect"

extern "c" fn mtl_cmd_copy_buffer_ffi(
  cmd : UInt64,
  src : UInt64,
  dst : UInt64,
  bytes : Int32,
) = "tycho_mtl_cmd_copy_buffer"

extern "c" fn mtl_cmd_blit_texture_ffi(
  cmd : UInt64,
  src : UInt64,
  dst : UInt64,
  linear : Int32,
) -> Int32 = "tycho_mtl_cmd_blit_texture"

extern "c" fn mtl_cmd_blit_to_swapchain_ffi(
  cmd : UInt64,
  src : UInt64,
  sc : UInt64,
) -> Int32 = "tycho_mtl_cmd_blit_to_swapchain"

extern "c" fn mtl_cmd_barrier_ffi(cmd : UInt64) = "tycho_mtl_cmd_barrier"

extern "c" fn mtl_cmd_write_timestamp_ffi(
  cmd : UInt64,
  pool : UInt64,
  index : Int32,
  is_end : Int32,
) = "tycho_mtl_cmd_write_timestamp"

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn ascii_bytes_to_string(buf : FixedArray[Byte], len : Int) -> String {
  let sb = StringBuilder()
  for i = 0; i < len; i = i + 1 {
    let b = buf[i].to_int()
    if b == 0 {
      break
    }
    sb.write_char(Int::unsafe_to_char(b))
  }
  sb.to_string()
}

fn string_to_ascii_bytes(s : String) -> Bytes {
  let n = s.length()
  let out = FixedArray::make(n, (0 : Byte))
  for i = 0; i < n; i = i + 1 {
    let c = s[i].to_int()
    out[i] = (c & 0xFF).to_byte()
  }
  Bytes::from_array(out[:])
}

// ---------------------------------------------------------------------------
// Public L0 Typed API
// ---------------------------------------------------------------------------

///|
pub fn is_available() -> Bool {
  mtl_is_available_ffi() != 0
}

///|
pub fn last_error() -> String {
  let n = mtl_last_error_len_ffi().to_int()
  if n <= 0 {
    return ""
  }
  let buf = FixedArray::make(n, (0 : Byte))
  mtl_last_error_copy_ffi(buf, n.to_int())
  ascii_bytes_to_string(buf, n)
}

///|
pub(all) struct DeviceCaps {
  name : String
  is_discrete : Bool
  arg_buf_tier : Int
  d24s8_supported : Bool
  max_samples : Int
  supports_raytracing : Bool
  supports_mesh : Bool
  max_dim_2d : Int
  max_anisotropy : Int
}

///|
pub struct Device {
  raw : UInt64
}

///|
pub struct Buffer {
  raw : UInt64
}

///|
pub struct Texture {
  raw : UInt64
}

///|
pub struct Sampler {
  raw : UInt64
}

///|
pub struct RenderPipeline {
  raw : UInt64
}

///|
pub struct ComputePipeline {
  raw : UInt64
}

///|
pub struct BindlessHeap {
  raw : UInt64
}

///|
pub struct Swapchain {
  raw : UInt64
}

///|
pub struct CommandBuffer {
  raw : UInt64
}

///|
pub struct TimestampPool {
  raw : UInt64
}

///|
pub struct Fence {
  raw : UInt64
}

///|
pub fn Device::create(validation? : Bool = false) -> Device? {
  let raw = mtl_device_create_ffi(if validation { 1 } else { 0 })
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Device::destroy(self : Device) -> Unit {
  mtl_device_destroy_ffi(self.raw)
}

///|
pub fn Device::caps(self : Device) -> DeviceCaps {
  let n = mtl_device_name_len_ffi(self.raw).to_int()
  let name = if n > 0 {
    let buf = FixedArray::make(n, (0 : Byte))
    mtl_device_name_copy_ffi(self.raw, buf, n.to_int())
    ascii_bytes_to_string(buf, n)
  } else {
    "Apple Metal"
  }
  let out = FixedArray::make(8, (0 : Int32))
  mtl_device_caps_ffi(self.raw, out)
  {
    name,
    is_discrete: out[0] != 0,
    arg_buf_tier: out[1].to_int(),
    d24s8_supported: out[2] != 0,
    max_samples: if out[3] > 0 { out[3].to_int() } else { 1 },
    supports_raytracing: out[4] != 0,
    supports_mesh: out[5] != 0,
    max_dim_2d: if out[6] > 0 { out[6].to_int() } else { 16384 },
    max_anisotropy: if out[7] > 0 { out[7].to_int() } else { 16 },
  }
}

///|
pub fn Device::validation_errors(self : Device) -> Int32 {
  mtl_device_validation_errors_ffi(self.raw)
}

///|
pub fn Device::wait_idle(self : Device) -> Unit {
  mtl_device_wait_idle_ffi(self.raw)
}

///|
pub fn Device::active_allocs(self : Device) -> Int32 {
  mtl_device_active_allocs_ffi(self.raw)
}

///|
pub fn Device::used_bytes(self : Device) -> UInt64 {
  mtl_device_used_bytes_ffi(self.raw)
}

///|
pub fn Buffer::create(
  dev : Device,
  size : Int,
  storage_mode? : Int = 0,
) -> Buffer? {
  let raw = mtl_buffer_create_ffi(dev.raw, size, storage_mode)
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Buffer::destroy(self : Buffer) -> Unit {
  mtl_buffer_destroy_ffi(self.raw)
}

///|
pub fn Buffer::upload(
  self : Buffer,
  data : Bytes,
  offset : Int,
  len : Int,
) -> Bool {
  mtl_buffer_upload_ffi(self.raw, data, offset, len) == 0
}

///|
pub fn Buffer::upload_floats(
  self : Buffer,
  data : FixedArray[Float],
  offset_bytes : Int,
  count : Int,
) -> Bool {
  mtl_buffer_upload_floats_ffi(self.raw, data, offset_bytes, count) == 0
}

///|
pub fn Buffer::download(
  self : Buffer,
  out : FixedArray[Byte],
  len : Int,
) -> Bool {
  mtl_buffer_download_ffi(self.raw, out, len) == 0
}

///|
pub fn Texture::create(
  dev : Device,
  width : Int,
  height : Int,
  format_code : Int,
  mip_levels? : Int = 1,
  layers? : Int = 1,
  samples? : Int = 1,
  is_cube? : Bool = false,
  usage_bits? : Int = 5,
) -> Texture? {
  let raw = mtl_texture_create_ffi(
    dev.raw,
    width,
    height,
    format_code,
    mip_levels,
    layers,
    samples,
    if is_cube { 1 } else { 0 },
    usage_bits,
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Texture::destroy(self : Texture) -> Unit {
  mtl_texture_destroy_ffi(self.raw)
}

///|
pub fn Texture::upload_region(
  self : Texture,
  x : Int,
  y : Int,
  w : Int,
  h : Int,
  layer : Int,
  mip : Int,
  data : Bytes,
) -> Bool {
  mtl_texture_upload_region_ffi(
    self.raw,
    x,
    y,
    w,
    h,
    layer,
    mip,
    data,
    data.length(),
  ) == 0
}

///|
pub fn Texture::generate_mipmaps(self : Texture) -> Bool {
  mtl_texture_generate_mipmaps_ffi(self.raw) == 0
}

///|
pub fn Texture::readback(
  self : Texture,
  mip : Int,
  layer : Int,
  out : FixedArray[Byte],
) -> Bool {
  mtl_texture_readback_ffi(self.raw, mip, layer, out, out.length()) == 0
}

///|
pub fn Sampler::create(
  dev : Device,
  min_linear : Bool,
  mag_linear : Bool,
  mip_linear : Bool,
  addr_u : Int,
  addr_v : Int,
  addr_w : Int,
  border_color : Int,
  max_aniso : Float,
  min_lod : Float,
  max_lod : Float,
  compare_op : Int,
) -> Sampler? {
  let raw = mtl_sampler_create_ffi(
    dev.raw,
    if min_linear { 1 } else { 0 },
    if mag_linear { 1 } else { 0 },
    if mip_linear { 1 } else { 0 },
    addr_u,
    addr_v,
    addr_w,
    border_color,
    max_aniso,
    min_lod,
    max_lod,
    compare_op,
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Sampler::destroy(self : Sampler) -> Unit {
  mtl_sampler_destroy_ffi(self.raw)
}

///|
pub fn RenderPipeline::create(
  dev : Device,
  vs_words : FixedArray[UInt32],
  fs_words : FixedArray[UInt32],
  vs_entry : String,
  fs_entry : String,
  state : FixedArray[Int32],
  bias_const : Float,
  bias_slope : Float,
  color_formats : FixedArray[Int32],
  blend_params : FixedArray[Int32],
  vtx_layouts : FixedArray[Int32],
  vtx_attrs : FixedArray[Int32],
) -> RenderPipeline? {
  let vs_e = string_to_ascii_bytes(vs_entry)
  let fs_e = string_to_ascii_bytes(fs_entry)
  let raw = mtl_render_pipeline_create_ffi(
    dev.raw,
    vs_words,
    vs_words.length(),
    fs_words,
    fs_words.length(),
    vs_e,
    vs_e.length(),
    fs_e,
    fs_e.length(),
    state,
    state.length(),
    bias_const,
    bias_slope,
    color_formats,
    color_formats.length(),
    blend_params,
    blend_params.length() / 8,
    vtx_layouts,
    vtx_layouts.length() / 3,
    vtx_attrs,
    vtx_attrs.length() / 4,
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn RenderPipeline::destroy(self : RenderPipeline) -> Unit {
  mtl_render_pipeline_destroy_ffi(self.raw)
}

///|
pub fn ComputePipeline::create(
  dev : Device,
  cs_words : FixedArray[UInt32],
  local_x : Int,
  local_y : Int,
  local_z : Int,
) -> ComputePipeline? {
  let raw = mtl_compute_pipeline_create_ffi(
    dev.raw,
    cs_words,
    cs_words.length(),
    local_x,
    local_y,
    local_z,
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn ComputePipeline::destroy(self : ComputePipeline) -> Unit {
  mtl_compute_pipeline_destroy_ffi(self.raw)
}

///|
pub fn BindlessHeap::create(dev : Device, capacity : Int) -> BindlessHeap? {
  let raw = mtl_bindless_create_ffi(dev.raw, capacity)
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

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

///|
pub fn BindlessHeap::register_texture(
  self : BindlessHeap,
  tex : Texture,
  smp : Sampler,
) -> Int32 {
  mtl_bindless_register_ffi(self.raw, tex.raw, smp.raw)
}

///|
pub fn BindlessHeap::unregister_texture(
  self : BindlessHeap,
  slot : Int,
) -> Unit {
  mtl_bindless_unregister_ffi(self.raw, slot)
}

///|
pub fn Swapchain::create(
  dev : Device,
  layer : UInt64,
  width : Int,
  height : Int,
  has_depth : Bool,
  depth_format : Int,
  enable_readback : Bool,
  vsync : Bool,
) -> Swapchain? {
  let raw = mtl_swapchain_create_ffi(
    dev.raw,
    layer,
    width,
    height,
    if has_depth { 1 } else { 0 },
    depth_format,
    if enable_readback { 1 } else { 0 },
    if vsync { 1 } else { 0 },
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Swapchain::destroy(self : Swapchain) -> Unit {
  mtl_swapchain_destroy_ffi(self.raw)
}

///|
pub fn Swapchain::resize(self : Swapchain, width : Int, height : Int) -> Bool {
  mtl_swapchain_resize_ffi(self.raw, width, height) == 0
}

///|
pub fn Swapchain::readback(self : Swapchain, out : FixedArray[Byte]) -> Bool {
  mtl_swapchain_readback_ffi(self.raw, out, out.length()) == 0
}

///|
pub fn Swapchain::begin_frame(
  self : Swapchain,
  begin_pass : Bool,
  r : Float,
  g : Float,
  b : Float,
  a : Float,
) -> CommandBuffer? {
  let raw = mtl_swapchain_begin_frame_ffi(
    self.raw,
    if begin_pass { 1 } else { 0 },
    r,
    g,
    b,
    a,
  )
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn Swapchain::end_frame(self : Swapchain, cmd : CommandBuffer) -> Bool {
  mtl_swapchain_end_frame_ffi(self.raw, cmd.raw) == 0
}

///|
pub fn Swapchain::present_texture(self : Swapchain, tex : Texture) -> Bool {
  mtl_swapchain_present_texture_ffi(self.raw, tex.raw) == 0
}

///|
pub fn TimestampPool::create(count : Int) -> TimestampPool? {
  let raw = mtl_timestamp_pool_create_ffi(count)
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn TimestampPool::destroy(self : TimestampPool) -> Unit {
  mtl_timestamp_pool_destroy_ffi(self.raw)
}

///|
pub fn TimestampPool::read(
  self : TimestampPool,
  out : FixedArray[Double],
) -> Unit {
  mtl_timestamp_pool_read_ffi(self.raw, out, out.length())
}

///|
pub fn Fence::create(signaled : Bool) -> Fence? {
  let raw = mtl_fence_create_ffi(if signaled { 1 } else { 0 })
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

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

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

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

///|
pub fn CommandBuffer::begin(dev : Device) -> CommandBuffer? {
  let raw = mtl_cmd_begin_ffi(dev.raw)
  if raw == (0 : UInt64) {
    None
  } else {
    Some({ raw, })
  }
}

///|
pub fn CommandBuffer::end_wait(self : CommandBuffer) -> Bool {
  mtl_cmd_end_wait_ffi(self.raw) == 0
}

///|
pub fn CommandBuffer::submit_async(self : CommandBuffer, fence : Fence) -> Bool {
  mtl_cmd_submit_async_ffi(self.raw, fence.raw) == 0
}

///|
pub fn CommandBuffer::begin_render_pass(
  self : CommandBuffer,
  color_texs : FixedArray[UInt64],
  resolve_texs : FixedArray[UInt64],
  color_load_ops : FixedArray[Int32],
  color_store_ops : FixedArray[Int32],
  clear_rgba : FixedArray[Float],
  color_layers : FixedArray[Int32],
  color_mips : FixedArray[Int32],
  color_count : Int,
  depth_tex : UInt64,
  depth_load : Int,
  depth_store : Int,
  clear_depth : Float,
  stencil_load : Int,
  stencil_store : Int,
  clear_stencil : UInt32,
  depth_layer : Int,
  depth_mip : Int,
) -> Bool {
  mtl_cmd_begin_render_pass_ffi(
    self.raw,
    color_texs,
    resolve_texs,
    color_load_ops,
    color_store_ops,
    clear_rgba,
    color_layers,
    color_mips,
    color_count,
    depth_tex,
    depth_load,
    depth_store,
    clear_depth,
    stencil_load,
    stencil_store,
    clear_stencil,
    depth_layer,
    depth_mip,
  ) == 0
}

///|
pub fn CommandBuffer::end_render_pass(self : CommandBuffer) -> Unit {
  mtl_cmd_end_render_pass_ffi(self.raw)
}

///|
pub fn CommandBuffer::begin_swapchain_pass(
  self : CommandBuffer,
  sc : Swapchain,
  load_op : Int,
  r : Float,
  g : Float,
  b : Float,
  a : Float,
) -> Bool {
  mtl_cmd_begin_swapchain_pass_ffi(self.raw, sc.raw, load_op, r, g, b, a) == 0
}

///|
pub fn CommandBuffer::bind_render_pipeline(
  self : CommandBuffer,
  pipe : RenderPipeline,
) -> Unit {
  mtl_cmd_bind_render_pipeline_ffi(self.raw, pipe.raw)
}

///|
pub fn CommandBuffer::bind_compute_pipeline(
  self : CommandBuffer,
  pipe : ComputePipeline,
) -> Unit {
  mtl_cmd_bind_compute_pipeline_ffi(self.raw, pipe.raw)
}

///|
pub fn CommandBuffer::bind_vertex(
  self : CommandBuffer,
  slot : Int,
  buf : Buffer,
  offset : Int,
) -> Unit {
  mtl_cmd_bind_vertex_ffi(self.raw, slot, buf.raw, offset)
}

///|
pub fn CommandBuffer::bind_index(
  self : CommandBuffer,
  buf : Buffer,
  is_u32 : Bool,
  offset : Int,
) -> Unit {
  mtl_cmd_bind_index_ffi(self.raw, buf.raw, if is_u32 { 1 } else { 0 }, offset)
}

///|
pub fn CommandBuffer::bind_buffer(
  self : CommandBuffer,
  binding : Int,
  buf : Buffer,
  offset : Int,
  is_compute : Bool,
) -> Unit {
  mtl_cmd_bind_buffer_ffi(
    self.raw,
    binding,
    buf.raw,
    offset,
    if is_compute { 1 } else { 0 },
  )
}

///|
pub fn CommandBuffer::bind_texture(
  self : CommandBuffer,
  binding : Int,
  tex : Texture,
  smp_raw : UInt64,
  is_compute : Bool,
) -> Unit {
  mtl_cmd_bind_texture_ffi(
    self.raw,
    binding,
    tex.raw,
    smp_raw,
    if is_compute { 1 } else { 0 },
  )
}

///|
pub fn CommandBuffer::bind_bindless(
  self : CommandBuffer,
  heap : BindlessHeap,
  is_compute : Bool,
) -> Unit {
  mtl_cmd_bind_bindless_ffi(self.raw, heap.raw, if is_compute { 1 } else { 0 })
}

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

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

///|
pub fn CommandBuffer::set_stencil_reference(
  self : CommandBuffer,
  ref_val : Int,
) -> Unit {
  mtl_cmd_set_stencil_ref_ffi(self.raw, ref_val)
}

///|
pub fn CommandBuffer::push_constants(
  self : CommandBuffer,
  data : Bytes,
  len : Int,
  is_compute : Bool,
) -> Unit {
  mtl_cmd_push_constants_ffi(
    self.raw,
    data,
    len,
    if is_compute { 1 } else { 0 },
  )
}

///|
pub fn CommandBuffer::push_constants_floats(
  self : CommandBuffer,
  data : FixedArray[Float],
  count : Int,
  is_compute : Bool,
) -> Unit {
  mtl_cmd_push_constants_floats_ffi(
    self.raw,
    data,
    count,
    if is_compute { 1 } else { 0 },
  )
}

///|
pub fn CommandBuffer::draw(
  self : CommandBuffer,
  vertex_count : Int,
  instance_count : Int,
  first_vertex : Int,
  first_instance : Int,
) -> Unit {
  mtl_cmd_draw_ffi(
    self.raw,
    vertex_count,
    instance_count,
    first_vertex,
    first_instance,
  )
}

///|
pub fn CommandBuffer::draw_indexed(
  self : CommandBuffer,
  index_count : Int,
  instance_count : Int,
  first_index : Int,
  vertex_offset : Int,
  first_instance : Int,
) -> Unit {
  mtl_cmd_draw_indexed_ffi(
    self.raw,
    index_count,
    instance_count,
    first_index,
    vertex_offset,
    first_instance,
  )
}

///|
pub fn CommandBuffer::draw_indirect(
  self : CommandBuffer,
  buf : Buffer,
  offset : Int,
  draw_count : Int,
  stride : Int,
) -> Unit {
  mtl_cmd_draw_indirect_ffi(self.raw, buf.raw, offset, draw_count, stride)
}

///|
pub fn CommandBuffer::draw_indexed_indirect(
  self : CommandBuffer,
  buf : Buffer,
  offset : Int,
  draw_count : Int,
  stride : Int,
) -> Unit {
  mtl_cmd_draw_indexed_indirect_ffi(
    self.raw,
    buf.raw,
    offset,
    draw_count,
    stride,
  )
}

///|
pub fn CommandBuffer::draw_indirect_count(
  self : CommandBuffer,
  buf : Buffer,
  count_buf : Buffer,
  offset : Int,
  count_offset : Int,
  max_draws : Int,
  stride : Int,
) -> Unit {
  mtl_cmd_draw_indirect_count_ffi(
    self.raw,
    buf.raw,
    count_buf.raw,
    offset,
    count_offset,
    max_draws,
    stride,
  )
}

///|
pub fn CommandBuffer::draw_indexed_indirect_count(
  self : CommandBuffer,
  buf : Buffer,
  count_buf : Buffer,
  offset : Int,
  count_offset : Int,
  max_draws : Int,
  stride : Int,
) -> Unit {
  mtl_cmd_draw_indexed_indirect_count_ffi(
    self.raw,
    buf.raw,
    count_buf.raw,
    offset,
    count_offset,
    max_draws,
    stride,
  )
}

///|
pub fn CommandBuffer::dispatch(
  self : CommandBuffer,
  gx : Int,
  gy : Int,
  gz : Int,
) -> Unit {
  mtl_cmd_dispatch_ffi(self.raw, gx, gy, gz)
}

///|
pub fn CommandBuffer::dispatch_indirect(
  self : CommandBuffer,
  buf : Buffer,
  offset : Int,
) -> Unit {
  mtl_cmd_dispatch_indirect_ffi(self.raw, buf.raw, offset)
}

///|
pub fn CommandBuffer::copy_buffer(
  self : CommandBuffer,
  src : Buffer,
  dst : Buffer,
  bytes : Int,
) -> Unit {
  mtl_cmd_copy_buffer_ffi(self.raw, src.raw, dst.raw, bytes)
}

///|
pub fn CommandBuffer::blit_texture(
  self : CommandBuffer,
  src : Texture,
  dst : Texture,
  linear : Bool,
) -> Bool {
  mtl_cmd_blit_texture_ffi(
    self.raw,
    src.raw,
    dst.raw,
    if linear { 1 } else { 0 },
  ) == 0
}

///|
pub fn CommandBuffer::blit_to_swapchain(
  self : CommandBuffer,
  src : Texture,
  sc : Swapchain,
) -> Bool {
  mtl_cmd_blit_to_swapchain_ffi(self.raw, src.raw, sc.raw) == 0
}

///|
pub fn CommandBuffer::barrier(self : CommandBuffer) -> Unit {
  mtl_cmd_barrier_ffi(self.raw)
}

///|
pub fn CommandBuffer::write_timestamp(
  self : CommandBuffer,
  pool : TimestampPool,
  index : Int,
  is_end : Bool,
) -> Unit {
  mtl_cmd_write_timestamp_ffi(
    self.raw,
    pool.raw,
    index,
    if is_end { 1 } else { 0 },
  )
}