# encoding: UTF-8
# rdop — 측면 개구부 실측: 양 끝단 평면에서 x 별 주황판 하면 / 흰판 상면 (읽기 전용)
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]
    when Sketchup::Group, Sketchup::ComponentInstance
      collect(e, tr * e.transformation, faces)
    end
  end
end
def hitz(faces, x, y, downward)
  res = []
  faces.each do |pts, n|
    next if n.z.abs < 0.05
    next if downward && n.z > -0.05
    next if !downward && n.z < 0.05
    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)
  end
  res
end
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
s04 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_04_t9_240x1046" }
won = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
f4 = []; collect(s04, g2.transformation * s04.transformation, f4)
fw = []; collect(won, won.transformation, fw)
out = []
[["A끝단", 10885.0], ["B끝단", 11867.0]].each do |lb, ymm|
  out << "=== #{lb} (y=#{ymm}) ==="
  out << "   x      주황하면   흰판상면   개구높이"
  (8780..9290).step(20) do |xmm|
    z4 = hitz(f4, xmm / MM, ymm / MM, true)
    zw = hitz(fw, xmm / MM, ymm / MM, false)
    next if z4.empty? && zw.empty?
    t = z4.empty? ? nil : z4.min * 25.4
    w = zw.empty? ? nil : zw.max * 25.4
    out << "  #{xmm}   #{t ? t.round(2) : '-'}   #{w ? w.round(2) : '-'}   #{(t && w) ? (t - w).round(2) : '-'}"
  end
end
# 격판 x 위치
g2.entities.grep(Sketchup::Group).each do |g|
  next unless g.name.to_s.include?("jog")
  bb = Geom::BoundingBox.new
  [g.bounds.min, g.bounds.max].each { |p| bb.add(p.transform(g2.transformation)) }
  out << "참고 #{g.name} hidden=#{g.hidden?} world x #{(bb.min.x*25.4).round(1)}..#{(bb.max.x*25.4).round(1)}"
end
m.entities.grep(Sketchup::Group).each do |g|
  next unless g.name.to_s.include?("_6T_20260919") || g.name.to_s.include?("사이드막음판")
  b = g.bounds
  out << "참고 #{g.name} world x #{(b.min.x*25.4).round(1)}..#{(b.max.x*25.4).round(1)} y #{(b.min.y*25.4).round(1)}..#{(b.max.y*25.4).round(1)} z #{(b.min.z*25.4).round(1)}..#{(b.max.z*25.4).round(1)}"
end
puts out.join("\n")
"RDOP"
