# encoding: UTF-8
# rd21 — 수평 정렬 후 간극 재실측: 주황판 상면(z=?) ~ SWD_04 하면, y 구간별 (읽기 전용)
def r1(v); (v * 25.4).round(1); end
m = Sketchup.active_model
def ents_of(e); e.is_a?(Sketchup::ComponentInstance) ? e.definition.entities : e.entities; end
def collect(ent, tr, faces)
  ents_of(ent).each do |e|
    case e
    when Sketchup::Face
      pts = e.vertices.map { |v| v.position.transform(tr) }
      n = e.normal.transform(tr); n.normalize!
      faces << [pts, n] if n.z.abs > 0.05
    when Sketchup::Group, Sketchup::ComponentInstance
      collect(e, tr * e.transformation, faces)
    end
  end
end
def zs_at(faces, x, y)
  res = []
  faces.each do |pts, n|
    inside = false
    j = pts.length - 1
    (0...pts.length).each do |i|
      xi = pts[i].x; yi = pts[i].y; xj = pts[j].x; yj = pts[j].y
      if ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
        inside = !inside
      end
      j = i
    end
    next unless inside
    p0 = pts[0]
    d = n.x * (x - p0.x) + n.y * (y - p0.y)
    res << (p0.z - d / n.z) if n.z.abs > 1e-9
  end
  res
end
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
won = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
s04 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_04_t9_240x1046" }
fw = []; collect(won, won.transformation, fw)
f4 = []; collect(s04, g2.transformation * s04.transformation, f4)
out = []
wb = won.bounds
out << "주황판 bbox z #{r1(wb.min.z)}..#{r1(wb.max.z)} (수평)"
[9200.0, 8853.0].each do |xmm|
  out << "=== x=#{xmm} ==="
  out << "   y      주황판상면  SWD04하면   간극"
  (10850..11900).step(25) do |ymm|
    x = xmm / 25.4; y = ymm / 25.4
    zw = zs_at(fw, x, y); z4 = zs_at(f4, x, y)
    next if zw.empty? && z4.empty?
    wt = zw.empty? ? nil : zw.max
    b4 = z4.empty? ? nil : z4.min
    gap = (wt && b4) ? r1(b4 - wt) : nil
    out << "  #{ymm}   #{wt ? r1(wt) : '-'}      #{b4 ? r1(b4) : '-'}      #{gap || '-'}"
  end
end
puts out.join("\n")
"RD21"
