module main

import vendor.raylib rl

let PipeRectangles = type struct {
  top: rl.Rectangle,
  bottom: rl.Rectangle,
}

let playfield_pixel_height_for(screen_height: i32): i32 =
  (screen_height.(f64) * (1.0 - base_height_fraction)).(i32)

let playfield_pixel_height(): i32 =
  playfield_pixel_height_for(rl.get_screen_height())

let world_to_pixel_x(world_x: f64): i32 {
  // Horizontal world units use screen height as their scale. A wider window
  // displays more world space without changing the width of game objects.
  return (world_x * playfield_pixel_height().(f64)).(i32)
}

let world_to_pixel_y(world_y: f64): i32 {
  return ((1.0 - world_y) * playfield_pixel_height().(f64)).(i32)
}

let world_size_to_pixels(size: f64): i32 {
  return (size * playfield_pixel_height().(f64)).(i32)
}

let base_rectangle(): rl.Rectangle {
  let screen_height = rl.get_screen_height()
  let playfield_height = playfield_pixel_height()

  return .{
    x = 0.0,
    y = playfield_height.(f32),
    width = rl.get_screen_width().(f32),
    height = (screen_height - playfield_height).(f32),
  }
}

let bird_rectangle(state: *GameState): rl.Rectangle {
  let bird_pixel_size = world_size_to_pixels(bird_size)
  let bird_pixel_x = world_to_pixel_x(bird_x)
  let bird_pixel_y = world_to_pixel_y(state.bird_y)

  return .{
    x = (bird_pixel_x - bird_pixel_size / 2).(f32),
    y = (bird_pixel_y - bird_pixel_size / 2).(f32),
    width = bird_pixel_size.(f32),
    height = bird_pixel_size.(f32),
  }
}

let pipe_rectangles(pipe: *Pipe): PipeRectangles {
  let playfield_height = playfield_pixel_height()
  let pipe_pixel_width = world_size_to_pixels(pipe_width)
  let pipe_pixel_left = world_to_pixel_x(pipe.x) - pipe_pixel_width / 2
  let gap_centre_pixel_y = world_to_pixel_y(pipe.gap_y)
  let gap_pixel_size = world_size_to_pixels(pipe_gap_size)
  let gap_top = gap_centre_pixel_y - gap_pixel_size / 2
  let gap_bottom = gap_centre_pixel_y + gap_pixel_size / 2

  return .{
    top = .{
      x = pipe_pixel_left.(f32),
      y = 0.0,
      width = pipe_pixel_width.(f32),
      height = gap_top.(f32),
    },
    bottom = .{
      x = pipe_pixel_left.(f32),
      y = gap_bottom.(f32),
      width = pipe_pixel_width.(f32),
      height = (playfield_height - gap_bottom).(f32),
    },
  }
}

let bird_collides_with_pipes(state: *GameState): bool {
  let bird = bird_rectangle(state)

  for let mut i: usz = 0; i < @len(state.pipes); i += 1 {
    let rectangles = pipe_rectangles(state.pipes[i].&)

    if rl.check_collision_recs(bird, rectangles.top) ||
       rl.check_collision_recs(bird, rectangles.bottom) {
      return true
    }
  }

  return false
}