# encoding: UTF-8
# rd22 — 각도 정정 후 갭 실측: 흰판(경사 6.445) 상면 ~ 주황판(SWD_04, 수평) 하면 (읽기 전용)
MM = 25.4
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
      inside = !inside if ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
      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" }
j30 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_02_t6_1000_jog30" }
j20 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_03_t6_1000_jog20" }
f4 = []; collect(s04, g2.transformation * s04.transformation, f4)
fw = []; collect(won, won.transformation, fw)
out = []
[[j30, "jog30"], [j20, "jog20"]].each do |g, lb|
  b = g.bounds
  wb = Geom::BoundingBox.new
  [b.min, b.max].each { |p| wb.add(p.transform(g2.transformation)) }
  xm = (wb.min.x + wb.max.x) / 2.0 * 25.4
  out << "=== #{lb} 위치 월드 x #{(wb.min.x*25.4).round(1)}..#{(wb.max.x*25.4).round(1)}, y #{(wb.min.y*25.4).round(1)}..#{(wb.max.y*25.4).round(1)} (샘플 x=#{xm.round(1)}) ==="
  out << "   y      흰판상면   주황하면   갭"
  (10900..11900).step(50) do |ymm|
    zw = zs_at(fw, xm / MM, ymm / MM)
    z4 = zs_at(f4, xm / MM, ymm / MM)
    next if zw.empty? && z4.empty?
    wt = zw.empty? ? nil : zw.max * 25.4
    b4 = z4.empty? ? nil : z4.min * 25.4
    out << "  #{ymm}   #{wt ? wt.round(2) : '-'}   #{b4 ? b4.round(2) : '-'}   #{(wt && b4) ? (b4 - wt).round(2) : '-'}"
  end
end
puts out.join("\n")
"RD22"
