///|
priv struct OrientedPart {
  index : Int32
  degrees : Int32
  mirrored : Bool
  priority : Int32
  material : @moonclip.Paths64
  clearance : @moonclip.Paths64?
  source_x : Int64
  source_y : Int64
  rotated_x : Int64
  rotated_y : Int64
  area2 : Int64
  bounds : (Int64, Int64, Int64, Int64)
  clearance_bounds : (Int64, Int64, Int64, Int64)
  setup_cost : Double
  edge_clearance : Double
}

///|
priv struct GeometryCache {
  clearances : Array[(OrientedPart, Int64, GapJoin, OrientedPart)]
}

///|
fn GeometryCache::default() -> GeometryCache {
  { clearances: [], }
}

///|
priv struct Engine {
  config : GeometryConfig
  sheet_contour : @moonclip.Path64
  sheet_holes : @moonclip.Paths64
  part_gaps : Array[Int64]
  pair_gaps : Array[(Int32, Int32, Int64)]
  margin : Int64
  sheet_margin : SheetMargin?
  hole_clearance : Int64
  join : GapJoin
  quality : Array[QualityRegion]
  strategy : SearchStrategy
  budget : SearchBudget
  suites : Array[SuiteSpec]
  cache : GeometryCache
  rotations : Array[Int32]
  started_at : @bench.Timestamp
  mut stats : Stats
}

///|
priv struct Obstacle {
  part : Int32
  material : @moonclip.Paths64
}

///|
priv struct CandidateEvaluation {
  distance : Int64
  bounds_area : Int64
  utilization_gain : Int64
  future_space : Int64
  quality_cost : Int64
  setup_cost : Int64
}

///|
priv struct Candidate {
  orientation : OrientedPart
  x : Int64
  y : Int64
  origin : PlacementOrigin
  quality_cost : Int64
  source : CandidateSource
}

///|
fn Engine::part_gap(self : Engine, index : Int32) -> Int64 {
  self.part_gaps[index]
}

///|
fn Engine::pair_gap(self : Engine, first : Int32, second : Int32) -> Int64 {
  if first < 0 || second < 0 {
    return 0L
  }
  for (a, b, gap) in self.pair_gaps {
    if (a == first && b == second) || (a == second && b == first) {
      return gap
    }
  }
  let first_gap = self.part_gap(first)
  let second_gap = self.part_gap(second)
  if first_gap > second_gap {
    first_gap
  } else {
    second_gap
  }
}

///|
fn Engine::time_exhausted(self : Engine) -> Bool {
  if self.budget.max_milliseconds > 0L {
    let elapsed = @bench.monotonic_clock_end(self.stats.started_at)
    let threshold = self.budget.max_milliseconds.to_double() * 1000.0
    if elapsed >= threshold {
      self.stats.budget_exhausted = true
      return true
    }
  }
  false
}

///|
fn Engine::candidate_budget_exhausted(self : Engine) -> Bool {
  if self.budget.max_candidates > 0 &&
    self.stats.candidates >= self.budget.max_candidates {
    self.stats.budget_exhausted = true
    return true
  }
  false
}

///|
fn Engine::clearance(
  self : Engine,
  orientation : OrientedPart,
) -> OrientedPart raise NestError {
  let gap = self.part_gap(orientation.index)
  for (cached, cached_gap, cached_join, result) in self.cache.clearances {
    if cached_gap == gap &&
      cached_join == self.join &&
      physical_equal(cached, orientation) {
      self.stats.cache_hits += 1
      return result
    }
  }
  let result = oriented_clearance(orientation, gap, self.config, self.join)
  self.cache.clearances.push((orientation, gap, self.join, result))
  result
}

///|
fn rotation_angles(policy : RotationPolicy) -> Array[Int32] {
  let step = policy.step_degrees
  if step == 0 {
    let result = []
    for angle in 0..<360 {
      if angle % 5 == 0 {
        result.push(angle)
      }
    }
    result
  } else if step > 0 && 90 % step == 0 {
    let result = []
    let mut angle = 0
    while angle < 360 {
      result.push(angle)
      angle += step
    }
    result
  } else {
    []
  }
}

///|
fn candidate_feasible(
  candidate : Candidate,
  occupied : Array[Obstacle],
  sheet : @moonclip.Paths64,
  engine : Engine,
) -> Bool raise NestError {
  let oriented = candidate.orientation
  let clearance = engine.clearance(oriented)
  let clearance_paths = match clearance.clearance {
    Some(paths) => paths
    None => clearance.material
  }
  let translated_clearance = clearance_paths.map(fn(path) {
    translate_paths([path], candidate.x, candidate.y)[0]
  })
  if !fits_sheet(translated_clearance, sheet, engine.config) ||
    !edge_clearance_ok(
      translated_clearance,
      sheet,
      oriented.edge_clearance,
      engine.config,
    ) {
    return false
  }
  let material = oriented.material.map(fn(path) {
    translate_paths([path], candidate.x, candidate.y)[0]
  })
  for obstacle in occupied {
    let stationary = inflate_material(
      obstacle.material,
      engine.pair_gap(oriented.index, obstacle.part),
      engine.config,
      engine.join,
    )
    if paths_overlap(material, stationary, engine.config) {
      return false
    }
  }
  !quality_violation(oriented.index, material, engine)
}

///|
fn occupied_from_candidates(
  placed : Array[Candidate],
  preoccupied : @moonclip.Paths64,
) -> Array[Obstacle] {
  let occupied : Array[Obstacle] = []
  if !preoccupied.is_empty() {
    occupied.push({ part: -1, material: preoccupied, })
  }
  for candidate in placed {
    occupied.push({
      part: candidate.orientation.index,
      material: candidate.orientation.material.map(fn(path) {
        translate_paths([path], candidate.x, candidate.y)[0]
      }),
    })
  }
  occupied
}

///|
fn candidate_set_cost(
  placed : Array[Candidate],
  engine : Engine,
) -> Int64 raise NestError {
  let mut cost = 0L
  for candidate in placed {
    let material = candidate.orientation.material.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    cost += quality_cost(material, engine)
  }
  cost
}

///|
fn candidate_set_better(
  candidate : Array[Candidate],
  current : Array[Candidate],
  engine : Engine,
) -> Bool raise NestError {
  let (candidate_width, candidate_height) = placed_bounds_size(
    candidate,
    engine.config.scale,
  )
  let (current_width, current_height) = placed_bounds_size(
    current,
    engine.config.scale,
  )
  let candidate_area = candidate_width * candidate_height
  let current_area = current_width * current_height
  if candidate_area != current_area {
    return candidate_area < current_area
  }
  candidate_set_cost(candidate, engine) < candidate_set_cost(current, engine)
}

///|
fn nest_suites(
  placed : Array[Candidate],
  preoccupied : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  engine : Engine,
) -> Array[Candidate] raise NestError {
  let result = placed
  for suite in engine.suites {
    for inner_part in suite.inner {
      for inner_index in 0.. Array[(Int32, Int32, Int64, Int64)] {
  let offsets : Array[(Int32, Int32, Int64, Int64)] = []
  for suite in engine.suites {
    for inner_index in 0.. Array[Candidate] {
  let result = placed
  for (inner_index, outer_index, dx, dy) in offsets {
    let inner = result[inner_index]
    result[inner_index] = {
      orientation: inner.orientation,
      x: result[outer_index].x + dx,
      y: result[outer_index].y + dy,
      origin: inner.origin,
      quality_cost: inner.quality_cost,
      source: inner.source,
    }
  }
  result
}

///|
fn improve_candidates(
  placed : Array[Candidate],
  preoccupied : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  engine : Engine,
  orientations : Array[Array[OrientedPart]],
) -> Array[Candidate] raise NestError {
  let mut result = placed
  for _ in 0..<2 {
    if engine.time_exhausted() || engine.candidate_budget_exhausted() {
      return result
    }
    let mut changed = false
    for i in 0.. (Double, Double) {
  if placed.is_empty() {
    return (0.0, 0.0)
  }
  let mut min_x = 9_223_372_036_854_775_807L
  let mut min_y = 9_223_372_036_854_775_807L
  let mut max_x = -9_223_372_036_854_775_808L
  let mut max_y = -9_223_372_036_854_775_808L
  for candidate in placed {
    let (part_min_x, part_min_y, part_max_x, part_max_y) = candidate.orientation.bounds
    min_x = min64(min_x, part_min_x + candidate.x)
    min_y = min64(min_y, part_min_y + candidate.y)
    max_x = max64(max_x, part_max_x + candidate.x)
    max_y = max64(max_y, part_max_y + candidate.y)
  }
  (
    (max_x - min_x).to_double() / scale.to_double(),
    (max_y - min_y).to_double() / scale.to_double(),
  )
}

///|
fn compress_candidates(
  placed : Array[Candidate],
  preoccupied : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  engine : Engine,
) -> (Array[Candidate], CompressionReport) raise NestError {
  let (before_width, before_height) = placed_bounds_size(
    placed,
    engine.config.scale,
  )
  let result = placed
  let mut iterations = 0
  let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds(sheet)
  let directions = match engine.strategy.gravity {
    Gravity::LeftBottom => [(-1L, 0L), (0L, -1L)]
    Gravity::RightBottom => [(1L, 0L), (0L, -1L)]
    Gravity::LeftTop => [(-1L, 0L), (0L, 1L)]
    Gravity::RightTop => [(1L, 0L), (0L, 1L)]
  }
  for (dx, dy) in directions {
    for i in 0.. 0L {
        sheet_max_x - candidate.x - bounds.2
      } else if dy < 0L {
        candidate.y + bounds.1 - sheet_min_y
      } else {
        sheet_max_y - candidate.y - bounds.3
      }
      if max_shift <= 0L {
        continue
      }
      let mut low = 0L
      let mut high = max_shift
      let original_material = candidate.orientation.material.map(fn(path) {
        translate_paths([path], candidate.x, candidate.y)[0]
      })
      let original_cost = quality_cost(original_material, engine)
      while low < high {
        if engine.time_exhausted() || engine.candidate_budget_exhausted() {
          break
        }
        let middle = (low + high + 1L) / 2L
        let moved : Candidate = {
          orientation: candidate.orientation,
          x: candidate.x + dx * middle,
          y: candidate.y + dy * middle,
          origin: candidate.origin,
          quality_cost: candidate.quality_cost,
          source: candidate.source,
        }
        let moved_material = candidate.orientation.material.map(fn(path) {
          translate_paths([path], moved.x, moved.y)[0]
        })
        if candidate_feasible(moved, occupied, sheet, engine) &&
          quality_cost(moved_material, engine) <= original_cost {
          low = middle
        } else {
          high = middle - 1L
        }
      }
      if low > 0L {
        result[i] = {
          orientation: candidate.orientation,
          x: candidate.x + dx * low,
          y: candidate.y + dy * low,
          origin: candidate.origin,
          quality_cost: candidate.quality_cost,
          source: candidate.source,
        }
        iterations += 1
      }
    }
  }
  let (after_width, after_height) = placed_bounds_size(
    result,
    engine.config.scale,
  )
  (
    result,
    { before_width, before_height, after_width, after_height, iterations, },
  )
}

///|
fn unplaced_from_placed(
  requested : Array[Int32],
  placed : Array[Candidate],
) -> Array[Int32] {
  let counts : Array[Int32] = Array::make(requested.length(), 0)
  for candidate in placed {
    counts[candidate.orientation.index] += 1
  }
  let result : Array[Int32] = []
  for i in 0.. Bool {
  state.remaining.any(fn(count) { count > 0 })
}

///|
fn placed_bounds_area(placed : Array[Candidate]) -> Int64 {
  if placed.is_empty() {
    return 0L
  }
  let mut min_x = 9_223_372_036_854_775_807L
  let mut min_y = 9_223_372_036_854_775_807L
  let mut max_x = -9_223_372_036_854_775_808L
  let mut max_y = -9_223_372_036_854_775_808L
  for candidate in placed {
    let (part_min_x, part_min_y, part_max_x, part_max_y) = candidate.orientation.bounds
    min_x = min64(min_x, part_min_x + candidate.x)
    min_y = min64(min_y, part_min_y + candidate.y)
    max_x = max64(max_x, part_max_x + candidate.x)
    max_y = max64(max_y, part_max_y + candidate.y)
  }
  (max_x - min_x) * (max_y - min_y)
}

///|
fn beam_state_better(candidate : BeamState, current : BeamState) -> Bool {
  if candidate.placed.length() != current.placed.length() {
    return candidate.placed.length() > current.placed.length()
  }
  if candidate.occupied_area != current.occupied_area {
    return candidate.occupied_area > current.occupied_area
  }
  let candidate_bounds = placed_bounds_area(candidate.placed)
  let current_bounds = placed_bounds_area(current.placed)
  if candidate_bounds != current_bounds {
    return candidate_bounds < current_bounds
  }
  candidate.quality_cost < current.quality_cost
}

///|
fn same_beam_state(first : BeamState, second : BeamState) -> Bool {
  if first.placed.length() != second.placed.length() ||
    first.remaining != second.remaining {
    return false
  }
  for i in 0.. Int64 {
  let oriented = candidate.orientation
  let center_x = oriented.clearance_bounds.0 +
    (oriented.clearance_bounds.2 - oriented.clearance_bounds.0) / 2L +
    candidate.x
  let center_y = oriented.clearance_bounds.1 +
    (oriented.clearance_bounds.3 - oriented.clearance_bounds.1) / 2L +
    candidate.y
  let (min_x, min_y, max_x, max_y) = paths_bounds(sheet)
  let gravity_x = match engine.strategy.gravity {
    Gravity::LeftBottom | Gravity::LeftTop => center_x - min_x
    Gravity::RightBottom | Gravity::RightTop => max_x - center_x
  }
  let gravity_y = match engine.strategy.gravity {
    Gravity::LeftBottom | Gravity::RightBottom => center_y - min_y
    Gravity::LeftTop | Gravity::RightTop => max_y - center_y
  }
  gravity_x * gravity_x +
  gravity_y * gravity_y +
  candidate.quality_cost +
  (oriented.setup_cost * engine.config.scale.to_double()).to_int64()
}

///|
fn Engine::run_beam(
  self : Engine,
  parts : Array[Part],
  fixed : Array[Candidate],
  preoccupied : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  orientations : Array[Array[OrientedPart]],
  requested : Array[Int32],
) -> (Array[Candidate], Array[Int32]) raise NestError {
  let mut occupied_area = 0L
  let mut total_quality_cost = 0L
  for candidate in fixed {
    occupied_area = checked_add(occupied_area, candidate.orientation.area2)
    let material = candidate.orientation.material.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    total_quality_cost += quality_cost(material, self)
  }
  let mut states : Array[BeamState] = [
    {
      placed: fixed.copy(),
      remaining: parts.map(fn(part) { part.quantity }),
      occupied_area,
      quality_cost: total_quality_cost,
    },
  ]
  let mut exhausted = false
  while states.any(state_has_remaining) && !exhausted {
    let children : Array[BeamState] = []
    for state in states {
      if !state_has_remaining(state) {
        children.push(state)
        continue
      }
      self.stats.iterations += 1
      self.stats.nodes += 1
      if (
          self.budget.max_nodes > 0 && self.stats.nodes >= self.budget.max_nodes
        ) ||
        self.time_exhausted() ||
        self.candidate_budget_exhausted() {
        self.stats.budget_exhausted = true
        exhausted = true
        children.push(state)
        break
      }
      let remaining_indices : Array[Int32] = []
      for i in 0..= self.budget.beam_width {
          break
        }
        if seen.any(fn(existing) {
            existing.orientation.index == candidate.orientation.index &&
            existing.orientation.degrees == candidate.orientation.degrees &&
            existing.orientation.mirrored == candidate.orientation.mirrored &&
            existing.x == candidate.x &&
            existing.y == candidate.y
          }) {
          continue
        }
        seen.push(candidate)
        let remaining = state.remaining.copy()
        remaining[part_index] -= 1
        children.push({
          placed: state.placed.add([candidate]),
          remaining,
          occupied_area: checked_add(
            state.occupied_area,
            candidate.orientation.area2,
          ),
          quality_cost: state.quality_cost + candidate.quality_cost,
        })
        selected += 1
      }
      if selected == 0 {
        let remaining = state.remaining.copy()
        remaining[part_index] -= 1
        children.push({
          placed: state.placed,
          remaining,
          occupied_area: state.occupied_area,
          quality_cost: state.quality_cost,
        })
      }
    }
    let unique_children : Array[BeamState] = []
    for child in children {
      if !unique_children.any(fn(existing) { same_beam_state(existing, child) }) {
        unique_children.push(child)
      }
    }
    unique_children.sort_by(fn(a, b) {
      if beam_state_better(a, b) {
        -1
      } else if beam_state_better(b, a) {
        1
      } else {
        0
      }
    })
    states = []
    for i in 0..= self.budget.beam_width {
        break
      }
      states.push(unique_children[i])
    }
  }
  let mut best = states[0]
  for i in 1.. (Layout, Array[PlacementTransform]) raise NestError {
  self.stats = {
    iterations: 0,
    placements: 0,
    rejected: 0,
    nfps: 0,
    candidates: 0,
    nodes: 0,
    backtracks: 0,
    budget_exhausted: false,
    elapsed_ms: 0.0,
    cache_hits: 0,
    started_at: self.started_at,
  }
  let mut sheet = prepare_sheet(
    self.sheet_contour,
    self.sheet_holes,
    self.margin,
    self.sheet_margin,
    self.hole_clearance,
    self.config,
    self.join,
  )
  for region in self.quality {
    if region.kind is QualityKind::Forbidden {
      sheet = match
        @moonclip.boolean_op(
          sheet,
          region.contours,
          @moonclip.Difference,
          fill_rule=@moonclip.NonZero,
          limits=self.config.limits,
        ) {
        Ok(paths) => paths
        Err(error) => raise JsonError(error.message())
      }
    }
  }
  if material_area2(sheet) == 0L {
    if !fixed.is_empty() {
      raise PlacementFailed("fixed placement has no usable sheet material")
    }
    return (empty_layout(parts, self.config.digits), [])
  }
  let orientations = parts.mapi(fn(index, part) {
    self.orientations(part, index)
  })
  let mut remaining : Array[Int32] = []
  for i in 0.. paths
      None => clearance.material
    }
    let translated_clearance = translated_clearance.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    if !fits_sheet(translated_clearance, sheet, self.config) ||
      !edge_clearance_ok(
        translated_clearance,
        sheet,
        candidate.orientation.edge_clearance,
        self.config,
      ) {
      raise PlacementFailed("fixed placement violates the sheet edge clearance")
    }
    let material = candidate.orientation.material.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    if quality_violation(candidate.orientation.index, material, self) {
      raise PlacementFailed("fixed placement violates a sheet quality region")
    }
    total_quality_cost += quality_cost(material, self)
    for obstacle in occupied {
      let gap = if obstacle.part < 0 {
        0L
      } else {
        self.pair_gap(candidate.orientation.index, obstacle.part)
      }
      let stationary = inflate_material(
        obstacle.material,
        gap,
        self.config,
        self.join,
      )
      if paths_overlap(material, stationary, self.config) {
        raise PlacementFailed(
          "fixed placement conflicts with existing material",
        )
      }
    }
    occupied.push({ part: candidate.orientation.index, material, })
    occupied_area = checked_add(occupied_area, candidate.orientation.area2)
    self.stats.placements += 1
  }
  let requested = parts.map(fn(part) { part.quantity })
  for candidate in placed {
    requested[candidate.orientation.index] += 1
  }
  if self.budget.beam_width > 1 {
    let (beam_placed, beam_unplaced) = self.run_beam(
      parts, fixed, preoccupied, sheet, orientations, requested,
    )
    placed = beam_placed
    unplaced = beam_unplaced
    remaining = []
    occupied_area = 0L
    total_quality_cost = 0L
    for candidate in placed {
      occupied_area = checked_add(occupied_area, candidate.orientation.area2)
      let material = candidate.orientation.material.map(fn(path) {
        translate_paths([path], candidate.x, candidate.y)[0]
      })
      total_quality_cost += quality_cost(material, self)
    }
  } else {
    let mut best_placed = placed.copy()
    let mut best_area = occupied_area
    while !remaining.is_empty() {
      self.stats.iterations += 1
      self.stats.nodes += 1
      if (
          self.budget.max_nodes > 0 && self.stats.nodes >= self.budget.max_nodes
        ) ||
        self.time_exhausted() ||
        self.candidate_budget_exhausted() {
        self.stats.budget_exhausted = true
        placed = best_placed
        occupied_area = best_area
        unplaced = unplaced_from_placed(requested, placed)
        remaining = []
        break
      }
      let order = feasible_order(remaining, orientations, self.strategy)
      if order.is_empty() {
        unplaced = unplaced.add(remaining)
        remaining = []
        break
      }
      let choice = order[0]
      let mut candidate = None
      for oriented in order {
        if candidate is Some(_) {
          break
        }
        candidate = try_candidates(
          search_candidates(
            self.clearance(oriented.orientation),
            occupied,
            sheet,
            self.config,
            self.stats,
            self,
          ),
          occupied,
          sheet,
          self.config,
          self.stats,
          self,
        )
      }
      let candidate = match candidate {
        Some(found) => found
        None => {
          let mut backtracked = false
          if self.budget.max_backtracks > 0 &&
            self.stats.backtracks < self.budget.max_backtracks {
            let window = if self.budget.beam_width > 0 {
              self.budget.beam_width
            } else {
              placed.length()
            }
            let mut index = placed.length()
            let mut scanned = 0
            while index > 0 && scanned < window {
              index -= 1
              if placed[index].origin is PlacementOrigin::Searched {
                backtracked = true
                break
              }
              scanned += 1
            }
            if backtracked {
              let removed = placed.remove(index)
              remaining.push(removed.orientation.index)
              occupied = []
              if !preoccupied.is_empty() {
                occupied.push({ part: -1, material: preoccupied, })
              }
              occupied_area = 0L
              for candidate in placed {
                occupied.push({
                  part: candidate.orientation.index,
                  material: candidate.orientation.material.map(fn(path) {
                    translate_paths([path], candidate.x, candidate.y)[0]
                  }),
                })
                occupied_area = checked_add(
                  occupied_area,
                  candidate.orientation.area2,
                )
              }
              self.stats.backtracks += 1
            }
          }
          if backtracked {
            continue
          }
          unplaced.push(choice.orientation.index)
          let mut removed = false
          for i in 0.. best_placed.length() ||
        (placed.length() == best_placed.length() && occupied_area > best_area) {
        best_placed = placed.copy()
        best_area = occupied_area
      }
    }
    if placed.length() < best_placed.length() ||
      (placed.length() == best_placed.length() && occupied_area < best_area) {
      placed = best_placed
      occupied_area = best_area
      unplaced = unplaced_from_placed(requested, placed)
    }
  }
  let mut placed = placed
  let mut compression = CompressionReport::default()
  if !self.time_exhausted() && !self.candidate_budget_exhausted() {
    placed = improve_candidates(placed, preoccupied, sheet, self, orientations)
  }
  if !self.time_exhausted() && !self.candidate_budget_exhausted() {
    placed = nest_suites(placed, preoccupied, sheet, self)
  }
  let suite_offsets = capture_suite_offsets(placed, self)
  if !self.time_exhausted() && !self.candidate_budget_exhausted() {
    let compressed = compress_candidates(placed, preoccupied, sheet, self)
    placed = compressed.0
    compression = compressed.1
  }
  placed = apply_suite_offsets(placed, suite_offsets)
  total_quality_cost = 0L
  for candidate in placed {
    let material = candidate.orientation.material.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    total_quality_cost += quality_cost(material, self)
  }
  self.stats.placements = placed.length()
  if placed.is_empty() {
    return (empty_layout(parts, self.config.digits), [])
  }
  let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds([
    self.sheet_contour,
  ])
  let mut min_x = sheet_min_x
  let mut min_y = sheet_min_y
  let mut max_x = sheet_max_x
  let mut max_y = sheet_max_y
  for candidate in placed {
    let (part_min_x, part_min_y, part_max_x, part_max_y) = candidate.orientation.bounds
    min_x = min64(min_x, part_min_x + candidate.x)
    min_y = min64(min_y, part_min_y + candidate.y)
    max_x = max64(max_x, part_max_x + candidate.x)
    max_y = max64(max_y, part_max_y + candidate.y)
  }
  let contours : @moonclip.Paths64 = []
  let placements = []
  let transforms : Array[PlacementTransform] = []
  for instance_id in 0.. Some(digits)
        None => Some(3)
      },
    },
  }
  (layout, transforms)
}

///|
fn empty_layout(parts : Array[Part], digits : Int32?) -> Layout {
  let unplaced = []
  for i in 0.. Some(value)
        None => Some(3)
      },
    },
  }
}

///|
fn Engine::orientations(
  self : Engine,
  part : Part,
  index : Int32,
) -> Array[OrientedPart] {
  orient_part(part, index, self.rotations)
}

///|
fn oriented_part_at(
  part : Part,
  index : Int32,
  degrees : Int32,
  mirrored : Bool,
) -> OrientedPart {
  let source = paths_bounds(part.contours)
  let source_x = source.0
  let source_y = source.1
  let origin = part.contours.map(fn(path) {
    let points = path.map(fn(point) {
      let y = if mirrored { source_y - (point.y - source_y) } else { point.y }
      @moonclip.Point64::new(point.x - source_x, y - source_y)
    })
    if mirrored {
      reversed(points)
    } else {
      points
    }
  })
  let rotated = rotate_paths(origin, degrees)
  let bounds = paths_bounds(rotated)
  let material = translate_paths(rotated, -bounds.0, -bounds.1)
  {
    index,
    degrees,
    mirrored,
    priority: part.rules.priority,
    material,
    clearance: None,
    source_x,
    source_y,
    rotated_x: bounds.0,
    rotated_y: bounds.1,
    area2: material_area2(material),
    bounds: (0L, 0L, bounds.2 - bounds.0, bounds.3 - bounds.1),
    clearance_bounds: (0L, 0L, bounds.2 - bounds.0, bounds.3 - bounds.1),
    setup_cost: part.rules.rotation_setup_cost,
    edge_clearance: part.rules.edge_clearance,
  }
}

///|
fn orient_part(
  part : Part,
  index : Int32,
  rotations : Array[Int32],
) -> Array[OrientedPart] {
  let allowed = match part.rules.rotations {
    Some(value) => value
    None => rotations
  }
  let mirrors : Array[Bool] = if part.rules.mirror {
    [false, true]
  } else {
    [false]
  }
  let result : Array[OrientedPart] = []
  for degrees in allowed {
    let grain_ok = match part.rules.grain_degrees {
      None => true
      Some(grain) => {
        let raw = (degrees - grain + 360) % 360
        let distance = if raw < 180 { raw } else { 360 - raw }
        distance <= part.rules.grain_tolerance_degrees
      }
    }
    if !grain_ok {
      continue
    }
    for mirrored in mirrors {
      let orientation = oriented_part_at(part, index, degrees, mirrored)
      if !result.any(fn(existing) {
          same_paths(existing.material, orientation.material)
        }) {
        result.push(orientation)
      }
    }
  }
  result
}

///|
fn rotate_paths(
  paths : @moonclip.Paths64,
  degrees : Int32,
) -> @moonclip.Paths64 {
  paths.map(fn(path) { path.map(fn(point) { rotate_point(point, degrees) }) })
}

///|
fn rotate_point(
  point : @moonclip.Point64,
  degrees : Int32,
) -> @moonclip.Point64 {
  let cosine = exact_rotation(degrees).0
  let sine = exact_rotation(degrees).1
  let x = point.x.to_double() * cosine - point.y.to_double() * sine
  let y = point.x.to_double() * sine + point.y.to_double() * cosine
  @moonclip.Point64::new(
    @double.round(x).to_int64(),
    @double.round(y).to_int64(),
  )
}

///|
fn unrotate_point(
  point : @moonclip.Point64,
  degrees : Int32,
) -> @moonclip.Point64 {
  rotate_point(point, -degrees)
}

///|
fn exact_rotation(degrees : Int32) -> (Double, Double) {
  let normalized = (degrees % 360 + 360) % 360
  match normalized {
    0 => (1.0, 0.0)
    90 => (0.0, 1.0)
    180 => (-1.0, 0.0)
    270 => (0.0, -1.0)
    angle => {
      let radians = angle.to_double() * @math.PI / 180.0
      (@math.cos(radians), @math.sin(radians))
    }
  }
}

///|
fn same_paths(a : @moonclip.Paths64, b : @moonclip.Paths64) -> Bool {
  if a.length() != b.length() {
    return false
  }
  let canonical_a = a.map(canonical_path)
  let canonical_b = b.map(canonical_path)
  for path in canonical_a {
    if !canonical_b.contains(path) {
      return false
    }
  }
  true
}

///|
fn canonical_path(path : @moonclip.Path64) -> @moonclip.Path64 {
  if path.is_empty() {
    return path
  }
  let mut best = path
  for offset in 0.. Bool {
  for i in 0.. Array[Candidate] {
  let result : Array[Candidate] = []
  for part_index in remaining {
    let oriented = orientations[part_index]
    if oriented.is_empty() {
      continue
    }
    for orientation in oriented {
      result.push({
        orientation,
        x: 0L,
        y: 0L,
        origin: PlacementOrigin::Searched,
        quality_cost: 0L,
        source: CandidateSource::SheetCorner,
      })
    }
  }
  result.sort_by(fn(a, b) {
    let a_priority = a.orientation.priority
    let b_priority = b.orientation.priority
    let a_area = a.orientation.area2
    let b_area = b.orientation.area2
    let a_width = a.orientation.bounds.2 - a.orientation.bounds.0
    let a_height = a.orientation.bounds.3 - a.orientation.bounds.1
    let b_width = b.orientation.bounds.2 - b.orientation.bounds.0
    let b_height = b.orientation.bounds.3 - b.orientation.bounds.1
    let a_metric = match strategy.order {
      PartOrder::Area => a_area
      PartOrder::LongestSide =>
        if a_width > a_height {
          a_width
        } else {
          a_height
        }
      PartOrder::Perimeter => 2L * (a_width + a_height)
      PartOrder::BoundsArea => a_width * a_height
    }
    let b_metric = match strategy.order {
      PartOrder::Area => b_area
      PartOrder::LongestSide =>
        if b_width > b_height {
          b_width
        } else {
          b_height
        }
      PartOrder::Perimeter => 2L * (b_width + b_height)
      PartOrder::BoundsArea => b_width * b_height
    }
    if a_priority != b_priority {
      if a_priority > b_priority {
        -1
      } else {
        1
      }
    } else if a_metric != b_metric {
      if a_metric > b_metric {
        -1
      } else {
        1
      }
    } else if a_area != b_area {
      if a_area > b_area {
        -1
      } else {
        1
      }
    } else if a.orientation.index != b.orientation.index {
      if a.orientation.index < b.orientation.index {
        -1
      } else {
        1
      }
    } else {
      0
    }
  })
  result
}

///|
fn oriented_clearance(
  orientation : OrientedPart,
  gap : Int64,
  config : GeometryConfig,
  join : GapJoin,
) -> OrientedPart raise NestError {
  if gap == 0L {
    return orientation
  }
  let clearance = inflate_material(orientation.material, gap, config, join)
  let bounds = paths_bounds(clearance)
  {
    index: orientation.index,
    degrees: orientation.degrees,
    mirrored: orientation.mirrored,
    priority: orientation.priority,
    material: orientation.material,
    clearance: Some(clearance),
    source_x: orientation.source_x,
    source_y: orientation.source_y,
    rotated_x: orientation.rotated_x,
    rotated_y: orientation.rotated_y,
    area2: orientation.area2,
    bounds: orientation.bounds,
    clearance_bounds: (
      bounds.0 - orientation.bounds.0,
      bounds.1 - orientation.bounds.1,
      bounds.2 - orientation.bounds.0,
      bounds.3 - orientation.bounds.1,
    ),
    setup_cost: orientation.setup_cost,
    edge_clearance: orientation.edge_clearance,
  }
}

///|
fn search_candidates(
  oriented : OrientedPart,
  occupied : Array[Obstacle],
  sheet : @moonclip.Paths64,
  config : GeometryConfig,
  stats : Stats,
  engine : Engine,
) -> Array[Candidate] raise NestError {
  let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds(sheet)
  let edge = round_away(oriented.edge_clearance * config.scale.to_double()).to_int64()
  let min_x = sheet_min_x + edge
  let min_y = sheet_min_y + edge
  let max_x = sheet_max_x - edge
  let max_y = sheet_max_y - edge
  if min_x > max_x || min_y > max_y {
    return []
  }
  let moving_bounds = oriented.clearance_bounds
  let width = moving_bounds.2 - moving_bounds.0
  let height = moving_bounds.3 - moving_bounds.1
  if width > max_x - min_x || height > max_y - min_y {
    return []
  }
  let points : Array[(Int64, Int64, CandidateSource)] = [
    (
      min_x - moving_bounds.0,
      min_y - moving_bounds.1,
      CandidateSource::SheetCorner,
    ),
  ]
  for contour in sheet {
    for point in contour {
      points.push(
        (
          point.x - moving_bounds.0,
          point.y - moving_bounds.1,
          CandidateSource::VertexContact,
        ),
      )
      points.push(
        (
          point.x - moving_bounds.2,
          point.y - moving_bounds.3,
          CandidateSource::VertexContact,
        ),
      )
      points.push(
        (
          point.x - moving_bounds.0,
          point.y - moving_bounds.3,
          CandidateSource::VertexContact,
        ),
      )
      points.push(
        (
          point.x - moving_bounds.2,
          point.y - moving_bounds.1,
          CandidateSource::VertexContact,
        ),
      )
    }
  }
  for region in engine.quality {
    for contour in region.contours {
      for point in contour {
        points.push(
          (
            point.x - moving_bounds.0,
            point.y - moving_bounds.1,
            CandidateSource::VertexContact,
          ),
        )
        points.push(
          (
            point.x - moving_bounds.2,
            point.y - moving_bounds.3,
            CandidateSource::VertexContact,
          ),
        )
        points.push(
          (
            point.x - moving_bounds.0,
            point.y - moving_bounds.3,
            CandidateSource::VertexContact,
          ),
        )
        points.push(
          (
            point.x - moving_bounds.2,
            point.y - moving_bounds.1,
            CandidateSource::VertexContact,
          ),
        )
      }
    }
  }
  if !occupied.is_empty() {
    let translation_bounds = (
      min_x - moving_bounds.0,
      min_y - moving_bounds.1,
      max_x - moving_bounds.2,
      max_y - moving_bounds.3,
    )
    for obstacle in occupied {
      if engine.time_exhausted() || engine.candidate_budget_exhausted() {
        return []
      }
      let gap = engine.pair_gap(oriented.index, obstacle.part)
      let stationary = inflate_material(
        obstacle.material,
        gap,
        config,
        engine.join,
      )
      stats.nfps += 1
      let forbidden = no_fit_region_paths(oriented.material, stationary, config)
      for contour in forbidden {
        if exact_area2(contour) > 0L {
          append_clipped_candidates(
            points,
            contour,
            translation_bounds,
            CandidateSource::NfpEdge,
          )
        }
      }
    }
  }
  let unique : Array[(Int64, Int64)] = []
  let candidates : Array[Candidate] = []
  for (x, y, source) in points {
    if x < min_x - moving_bounds.0 ||
      y < min_y - moving_bounds.1 ||
      x + moving_bounds.2 > max_x ||
      y + moving_bounds.3 > max_y {
      continue
    }
    if unique.contains((x, y)) {
      continue
    }
    unique.push((x, y))
    candidates.push({
      orientation: oriented,
      x,
      y,
      origin: PlacementOrigin::Searched,
      quality_cost: 0L,
      source,
    })
  }
  candidates
}

///|
fn append_clipped_candidates(
  points : Array[(Int64, Int64, CandidateSource)],
  polygon : @moonclip.Path64,
  bounds : (Int64, Int64, Int64, Int64),
  source : CandidateSource,
) -> Unit {
  let (min_x, min_y, max_x, max_y) = bounds
  let mut previous = polygon[polygon.length() - 1]
  for current in polygon {
    append_segment_candidates(points, previous, current, bounds, source)
    previous = current
  }
  if min_x <= max_x && min_y <= max_y {
    points.push((min_x, min_y, source))
    points.push((min_x, max_y, source))
    points.push((max_x, min_y, source))
    points.push((max_x, max_y, source))
  }
}

///|
fn append_segment_candidates(
  points : Array[(Int64, Int64, CandidateSource)],
  start : @moonclip.Point64,
  finish : @moonclip.Point64,
  bounds : (Int64, Int64, Int64, Int64),
  source : CandidateSource,
) -> Unit {
  let (min_x, min_y, max_x, max_y) = bounds
  let first_x = start.x.to_double()
  let first_y = start.y.to_double()
  let delta_x = finish.x.to_double() - first_x
  let delta_y = finish.y.to_double() - first_y
  if delta_x == 0.0 && delta_y == 0.0 {
    return
  }
  let mut first = 0.0
  let mut last = 1.0
  for
    (origin, delta, lower, upper) in [
      (first_x, delta_x, min_x.to_double(), max_x.to_double()),
      (first_y, delta_y, min_y.to_double(), max_y.to_double()),
    ] {
    if delta == 0.0 {
      if origin < lower || origin > upper {
        return
      }
    } else {
      let a = (lower - origin) / delta
      let b = (upper - origin) / delta
      let lower_t = if a < b { a } else { b }
      let upper_t = if a > b { a } else { b }
      first = if first > lower_t { first } else { lower_t }
      last = if last < upper_t { last } else { upper_t }
      if first > last {
        return
      }
    }
  }
  let length = (delta_x * delta_x + delta_y * delta_y).sqrt()
  let count = @double.ceil((last - first) * length).to_int()
  let steps = if count > 64 { 64 } else { count }
  for step in 0..<=steps {
    let t = first + (last - first) * step.to_double() / steps.to_double()
    points.push(
      (
        @double.round(first_x + delta_x * t).to_int64(),
        @double.round(first_y + delta_y * t).to_int64(),
        source,
      ),
    )
  }
}

///|
fn paths_intersection_area2(
  first : @moonclip.Paths64,
  second : @moonclip.Paths64,
  config : GeometryConfig,
) -> Int64 raise NestError {
  if first.is_empty() || second.is_empty() {
    return 0L
  }
  let intersection = match
    @moonclip.boolean_op(
      first,
      second,
      @moonclip.Intersection,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  material_area2(intersection)
}

///|
fn quality_violation(
  part : Int32,
  material : @moonclip.Paths64,
  engine : Engine,
) -> Bool raise NestError {
  for region in engine.quality {
    match region.kind {
      QualityKind::Forbidden =>
        if paths_overlap(material, region.contours, engine.config) {
          return true
        }
      QualityKind::PartRestricted =>
        if !region.parts.contains(part) &&
          paths_overlap(material, region.contours, engine.config) {
          return true
        }
      QualityKind::HighValue | QualityKind::Defect => ()
    }
  }
  false
}

///|
fn quality_cost(
  material : @moonclip.Paths64,
  engine : Engine,
) -> Int64 raise NestError {
  let mut cost = 0L
  for region in engine.quality {
    match region.kind {
      QualityKind::HighValue | QualityKind::Defect => {
        let area = paths_intersection_area2(
          material,
          region.contours,
          engine.config,
        )
        let weighted = round_away(area.to_double() * region.weight).to_int64()
        cost = match region.kind {
          QualityKind::HighValue => cost - weighted
          QualityKind::Defect => cost + weighted
          _ => cost
        }
      }
      QualityKind::Forbidden | QualityKind::PartRestricted => ()
    }
  }
  cost
}

///|
fn candidate_score(
  evaluation : CandidateEvaluation,
  strategy : SearchStrategy,
) -> Int64 {
  let base = match strategy.scoring {
    CandidateScoring::Distance => evaluation.distance
    CandidateScoring::BoundsArea => evaluation.bounds_area
    CandidateScoring::Utilization => -evaluation.utilization_gain
    CandidateScoring::FutureSpace => evaluation.future_space
    CandidateScoring::Composite =>
      evaluation.distance +
      evaluation.bounds_area / 10L -
      evaluation.utilization_gain / 10L
  }
  base + evaluation.quality_cost + evaluation.setup_cost
}

///|
fn candidate_evaluation(
  candidate : Candidate,
  sheet : @moonclip.Paths64,
  engine : Engine,
  candidate_cost : Int64,
) -> CandidateEvaluation {
  let oriented = candidate.orientation
  let center_x = oriented.clearance_bounds.0 +
    (oriented.clearance_bounds.2 - oriented.clearance_bounds.0) / 2L +
    candidate.x
  let center_y = oriented.clearance_bounds.1 +
    (oriented.clearance_bounds.3 - oriented.clearance_bounds.1) / 2L +
    candidate.y
  let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds(sheet)
  let gravity_x = match engine.strategy.gravity {
    Gravity::LeftBottom | Gravity::LeftTop => center_x - sheet_min_x
    Gravity::RightBottom | Gravity::RightTop => sheet_max_x - center_x
  }
  let gravity_y = match engine.strategy.gravity {
    Gravity::LeftBottom | Gravity::RightBottom => center_y - sheet_min_y
    Gravity::LeftTop | Gravity::RightTop => sheet_max_y - center_y
  }
  let bounds_width = oriented.clearance_bounds.2 - oriented.clearance_bounds.0
  let bounds_height = oriented.clearance_bounds.3 - oriented.clearance_bounds.1
  let sheet_area = (sheet_max_x - sheet_min_x) * (sheet_max_y - sheet_min_y)
  let bounds_area = bounds_width * bounds_height
  {
    distance: gravity_x * gravity_x + gravity_y * gravity_y,
    bounds_area: bounds_width * bounds_height,
    utilization_gain: oriented.area2,
    future_space: sheet_area - bounds_area,
    quality_cost: candidate_cost,
    setup_cost: (oriented.setup_cost * engine.config.scale.to_double()).to_int64(),
  }
}

///|
fn candidate_compare(
  first : (Candidate, Int64, Int64),
  second : (Candidate, Int64, Int64),
) -> Int32 {
  if first.1 != second.1 {
    if first.1 < second.1 {
      -1
    } else {
      1
    }
  } else if first.2 != second.2 {
    if first.2 < second.2 {
      -1
    } else {
      1
    }
  } else if first.0.x != second.0.x {
    if first.0.x < second.0.x {
      -1
    } else {
      1
    }
  } else if first.0.y != second.0.y {
    if first.0.y < second.0.y {
      -1
    } else {
      1
    }
  } else {
    0
  }
}

///|
fn inflated_obstacles_for(
  occupied : Array[Obstacle],
  part : Int32,
  engine : Engine,
  cache : Array[(Int32, Array[@moonclip.Paths64])],
) -> Array[@moonclip.Paths64] raise NestError {
  for (cached_part, paths) in cache {
    if cached_part == part {
      return paths
    }
  }
  let paths = occupied.map(fn(obstacle) raise NestError {
    inflate_material(
      obstacle.material,
      engine.pair_gap(part, obstacle.part),
      engine.config,
      engine.join,
    )
  })
  cache.push((part, paths))
  paths
}

///|
fn rank_candidates(
  candidates : Array[Candidate],
  occupied : Array[Obstacle],
  sheet : @moonclip.Paths64,
  config : GeometryConfig,
  stats : Stats,
  engine : Engine,
) -> Array[Candidate] raise NestError {
  let scored : Array[(Candidate, Int64, Int64)] = []
  let inflated_cache : Array[(Int32, Array[@moonclip.Paths64])] = []
  for candidate in candidates {
    if engine.time_exhausted() || engine.candidate_budget_exhausted() {
      break
    }
    let oriented = candidate.orientation
    let clearance = match oriented.clearance {
      Some(clearance) => clearance
      None => oriented.material
    }
    let translated_clearance = clearance.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    stats.candidates += 1
    let fits = fits_sheet(translated_clearance, sheet, config) &&
      edge_clearance_ok(
        translated_clearance,
        sheet,
        oriented.edge_clearance,
        config,
      )
    if !fits {
      stats.rejected += 1
      continue
    }
    let translated_material = oriented.material.map(fn(path) {
      translate_paths([path], candidate.x, candidate.y)[0]
    })
    let mut collided = false
    let stationary_paths = inflated_obstacles_for(
      occupied,
      oriented.index,
      engine,
      inflated_cache,
    )
    for stationary in stationary_paths {
      if paths_overlap(translated_material, stationary, config) {
        collided = true
        break
      }
    }
    if collided {
      stats.rejected += 1
      continue
    }
    let violates = quality_violation(
      oriented.index,
      translated_material,
      engine,
    )
    if violates {
      stats.rejected += 1
      continue
    }
    let candidate_cost = quality_cost(translated_material, engine)
    let evaluation = candidate_evaluation(
      candidate, sheet, engine, candidate_cost,
    )
    let scored_candidate : Candidate = {
      orientation: oriented,
      x: candidate.x,
      y: candidate.y,
      origin: candidate.origin,
      quality_cost: candidate_cost,
      source: candidate.source,
    }
    scored.push(
      (
        scored_candidate,
        candidate_score(evaluation, engine.strategy),
        evaluation.distance,
      ),
    )
  }
  scored.sort_by(candidate_compare)
  scored.map(fn(item) { item.0 })
}

///|
fn try_candidates(
  candidates : Array[Candidate],
  occupied : Array[Obstacle],
  sheet : @moonclip.Paths64,
  config : GeometryConfig,
  stats : Stats,
  engine : Engine,
) -> Candidate? raise NestError {
  let ranked = rank_candidates(
    candidates, occupied, sheet, config, stats, engine,
  )
  if ranked.is_empty() {
    None
  } else {
    Some(ranked[0])
  }
}

///|
fn edge_clearance_ok(
  material : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  clearance : Double,
  config : GeometryConfig,
) -> Bool {
  if clearance <= 0.0 {
    return true
  }
  let required = round_away(clearance * config.scale.to_double()).to_int64()
  let (material_min_x, material_min_y, material_max_x, material_max_y) = paths_bounds(
    material,
  )
  let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds(sheet)
  material_min_x >= sheet_min_x + required &&
  material_min_y >= sheet_min_y + required &&
  material_max_x <= sheet_max_x - required &&
  material_max_y <= sheet_max_y - required
}

///|
fn fits_sheet(
  material : @moonclip.Paths64,
  sheet : @moonclip.Paths64,
  config : GeometryConfig,
) -> Bool raise NestError {
  if paths_are_orthogonal(material) && paths_are_orthogonal(sheet) {
    return orthogonal_contains(sheet, material)
  }
  let containment = match
    @moonclip.boolean_op(
      material,
      sheet,
      @moonclip.Intersection,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  material_area2(containment) == material_area2(material)
}

///|
fn join_options(join : GapJoin) -> @moonclip.OffsetOptions {
  let moonclip_join = match join {
    GapJoin::Round => @moonclip.JoinType::Round
    GapJoin::Bevel => @moonclip.JoinType::Bevel
    GapJoin::Miter => @moonclip.JoinType::Miter
    GapJoin::Square => @moonclip.JoinType::Square
  }
  @moonclip.OffsetOptions::new(join=moonclip_join)
}

///|
fn prepare_sheet(
  contour : @moonclip.Path64,
  holes : @moonclip.Paths64,
  margin : Int64,
  sheet_margin : SheetMargin?,
  hole_clearance : Int64,
  config : GeometryConfig,
  join : GapJoin,
) -> @moonclip.Paths64 raise NestError {
  let inset = match sheet_margin {
    Some(edges) => {
      let top = round_away(edges.top * config.scale.to_double()).to_int64()
      let right = round_away(edges.right * config.scale.to_double()).to_int64()
      let bottom = round_away(edges.bottom * config.scale.to_double()).to_int64()
      let left = round_away(edges.left * config.scale.to_double()).to_int64()
      let (min_x, min_y, max_x, max_y) = paths_bounds([contour])
      if min_x + left > max_x - right || min_y + bottom > max_y - top {
        return []
      }
      let clip : @moonclip.Path64 = [
        @moonclip.Point64::new(min_x + left, min_y + bottom),
        @moonclip.Point64::new(max_x - right, min_y + bottom),
        @moonclip.Point64::new(max_x - right, max_y - top),
        @moonclip.Point64::new(min_x + left, max_y - top),
      ]
      match
        @moonclip.boolean_op(
          [contour],
          [clip],
          @moonclip.Intersection,
          fill_rule=@moonclip.NonZero,
          limits=config.limits,
        ) {
        Ok(paths) => paths
        Err(error) => raise JsonError(error.message())
      }
    }
    None =>
      if margin > 0L {
        let path = inset_path(contour, margin, config, join)
        if path.is_empty() {
          []
        } else {
          [path]
        }
      } else {
        [contour]
      }
  }
  if inset.is_empty() {
    return []
  }
  let safe_holes = if hole_clearance > 0L {
    let expanded : @moonclip.Paths64 = []
    for hole in holes {
      let path = inflated_path(hole, hole_clearance, config, join)
      if path.is_empty() {
        raise JsonError("sheet hole clearance removed a hole boundary")
      }
      expanded.push(path)
    }
    expanded
  } else {
    holes
  }
  let usable = normalize_region(inset, safe_holes, config)
  if usable.is_empty() || material_area2(usable) == 0L {
    raise JsonError("sheet hole clearance removes all usable material")
  }
  usable
}

///|
fn inset_path(
  path : @moonclip.Path64,
  distance : Int64,
  config : GeometryConfig,
  join : GapJoin,
) -> @moonclip.Path64 {
  let area = exact_area2(path)
  let delta = if area > 0L { -distance } else { distance }
  match
    @moonclip.offset_polygons(
      [path],
      delta.to_double(),
      options=join_options(join),
      limits=config.limits,
    ) {
    Ok(paths) => {
      let mut best : @moonclip.Path64 = []
      for candidate in paths {
        if exact_area2(candidate).abs() > exact_area2(best).abs() {
          best = candidate
        }
      }
      best
    }
    Err(_) => []
  }
}

///|
fn inflated_path(
  path : @moonclip.Path64,
  gap : Int64,
  config : GeometryConfig,
  join : GapJoin,
) -> @moonclip.Path64 raise NestError {
  let area = exact_area2(path)
  let delta = if area > 0L { gap } else { -gap }
  match
    @moonclip.offset_polygons(
      [path],
      delta.to_double(),
      options=join_options(join),
      limits=config.limits,
    ) {
    Ok(paths) => {
      let mut best : @moonclip.Path64 = []
      for candidate in paths {
        if exact_area2(candidate).abs() > exact_area2(best).abs() {
          best = candidate
        }
      }
      best
    }
    Err(error) => raise JsonError(error.message())
  }
}

///|
fn inflate_material(
  material : @moonclip.Paths64,
  gap : Int64,
  config : GeometryConfig,
  join : GapJoin,
) -> @moonclip.Paths64 raise NestError {
  if gap == 0L {
    return material
  }
  if material.length() == 1 {
    let inflated = match
      @moonclip.offset_polygons(
        material,
        gap.to_double(),
        fill_rule=@moonclip.NonZero,
        options=join_options(join),
        limits=config.limits,
      ) {
      Ok(paths) => paths
      Err(error) => raise JsonError(error.message())
    }
    if inflated.is_empty() || material_area2(inflated) == 0L {
      raise JsonError("clearance expansion removed all material")
    }
    return inflated
  }
  let result : @moonclip.Paths64 = []
  for path in material {
    let inflated = inflated_path(path, gap, config, join)
    if inflated.is_empty() {
      if exact_area2(path) < 0L {
        raise JsonError("clearance expansion closed a part hole")
      }
      continue
    }
    result.push(inflated)
  }
  let inflated = match
    @moonclip.boolean_op(
      result,
      [],
      @moonclip.Union,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  if inflated.is_empty() || material_area2(inflated) == 0L {
    raise JsonError("clearance expansion removed all material")
  }
  inflated
}

///|
fn nfp_pair(
  moving : @moonclip.Paths64,
  stationary : @moonclip.Paths64,
  config : GeometryConfig,
) -> @moonclip.Path64 raise NestError {
  let mut selected : @moonclip.Path64 = []
  for moving_path in moving {
    if exact_area2(moving_path) <= 0L {
      continue
    }
    for stationary_path in stationary {
      if exact_area2(stationary_path) <= 0L {
        continue
      }
      let reflected_moving = moving_path.map(fn(point) {
        @moonclip.Point64::new(-point.x, -point.y)
      })
      let tree = match
        @moonclip.minkowski_sum_tree(
          reversed(stationary_path),
          reversed(reflected_moving),
          true,
          limits=config.limits,
        ) {
        Ok(tree) => tree
        Err(error) => raise JsonError(error.message())
      }
      for root in tree.roots() {
        if !root.is_hole() && root.contour().length() > selected.length() {
          selected = root.contour()
        }
      }
    }
  }
  selected
}

///|
fn no_fit_region_data(
  moving : @moonclip.Paths64,
  stationary : @moonclip.Paths64,
  _config : GeometryConfig,
) -> (@moonclip.Paths64, DoublePaths) raise NestError {
  if paths_are_orthogonal(moving) && paths_are_orthogonal(stationary) {
    return (orthogonal_no_fit_region(moving, stationary), [])
  }
  let moving_pieces = double_vertical_decompose_region(moving)
  let stationary_pieces = double_vertical_decompose_region(stationary)
  let sums : DoublePaths = []
  for moving_piece in moving_pieces {
    for stationary_piece in stationary_pieces {
      let sums_for_pair : DoublePath = []
      for moving_point in moving_piece {
        for stationary_point in stationary_piece {
          sums_for_pair.push(
            (
              stationary_point.0 - moving_point.0,
              stationary_point.1 - moving_point.1,
            ),
          )
        }
      }
      let contour = double_convex_hull(sums_for_pair)
      if contour.length() >= 3 && double_area2(contour) > 0.000000001 {
        sums.push(contour)
      }
    }
  }
  if sums.is_empty() {
    return ([], [])
  }
  let normalized = normalize_double_convex_union_data(sums)
  (normalized.contours, normalized.exact_contours)
}

///|
fn no_fit_region_paths(
  moving : @moonclip.Paths64,
  stationary : @moonclip.Paths64,
  config : GeometryConfig,
) -> @moonclip.Paths64 raise NestError {
  no_fit_region_data(moving, stationary, config).0
}

///|
fn checked_add(a : Int64, b : Int64) -> Int64 {
  let result = a + b
  if (b > 0L && result < a) || (b < 0L && result > a) {
    abort("layout area exceeds Int64")
  }
  result
}

///|
fn min64(a : Int64, b : Int64) -> Int64 {
  if a < b {
    a
  } else {
    b
  }
}

///|
fn max64(a : Int64, b : Int64) -> Int64 {
  if a > b {
    a
  } else {
    b
  }
}