# encoding: UTF-8
# dbg3 — 조립구역 판재 식별: 재질 색상 + 기울기 + Z범위 + 그룹#2 변환 (읽기 전용)
MM = 25.4
def deg(a); (a * 180.0 / Math::PI); end
m = Sketchup.active_model
out = []
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!
      mat = e.material || e.back_material
      faces << [pts, n, e.area * 645.16, mat]
    when Sketchup::Group, Sketchup::ComponentInstance
      collect(e, tr * e.transformation, faces)
    end
  end
end
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
out << "그룹#2 tr=#{g2.transformation.to_a.map { |v| v.round(4) }.inspect} identity=#{g2.transformation.identity?}"
gb = g2.bounds
out << "그룹#2 world (#{(gb.min.x*25.4).round(1)},#{(gb.min.y*25.4).round(1)},#{(gb.min.z*25.4).round(1)})..(#{(gb.max.x*25.4).round(1)},#{(gb.max.y*25.4).round(1)},#{(gb.max.z*25.4).round(1)})"

cands = []
m.entities.each do |e|
  next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
  b = e.bounds
  next if b.max.x * 25.4 < 8600 || b.min.x * 25.4 > 9500
  next if b.max.y * 25.4 < 10500 || b.min.y * 25.4 > 12300
  cands << e
end
out << "구역 최상위 개체 #{cands.length}개"
cands.each do |e|
  nm = e.name.to_s.empty? ? e.definition.name : e.name
  fs = []
  collect(e, e.transformation, fs)
  big = fs.sort_by { |f| -f[2] }[0, 4]
  b = e.bounds
  gmat = (e.material ? "#{e.material.name} rgb#{e.material.color.to_a[0, 3].inspect}" : "없음")
  out << "=== #{nm} (#{e.class}) hidden=#{e.hidden?} 그룹재질=#{gmat}"
  out << "    world z #{(b.min.z*25.4).round(1)}..#{(b.max.z*25.4).round(1)}"
  big.each do |pts, n, a, mat|
    tl = deg(Math.acos([[n.z.abs, 1.0].min, -1.0].max)).round(4)
    mm2 = mat ? "#{mat.name} rgb#{mat.color.to_a[0, 3].inspect}" : "없음"
    out << "    면 A=#{a.round(0)} 기울기=#{tl}도 z #{(pts.map { |p| p.z }.min*25.4).round(1)}..#{(pts.map { |p| p.z }.max*25.4).round(1)} 재질=#{mm2}"
  end
end
# 그룹#2 내부도
out << "=== 그룹#2 내부 ==="
g2.entities.grep(Sketchup::Group).each do |g|
  fs = []
  collect(g, g2.transformation * g.transformation, fs)
  big = fs.sort_by { |f| -f[2] }[0, 2]
  gmat = (g.material ? "#{g.material.name} rgb#{g.material.color.to_a[0, 3].inspect}" : "없음")
  out << "  #{g.name.inspect} hidden=#{g.hidden?} 재질=#{gmat}"
  big.each do |pts, n, a, mat|
    tl = deg(Math.acos([[n.z.abs, 1.0].min, -1.0].max)).round(4)
    mm2 = mat ? "#{mat.name} rgb#{mat.color.to_a[0, 3].inspect}" : "없음"
    out << "     면 A=#{a.round(0)} 기울기=#{tl}도 z #{(pts.map { |p| p.z }.min*25.4).round(1)}..#{(pts.map { |p| p.z }.max*25.4).round(1)} 재질=#{mm2}"
  end
end
puts out.join("\n")
"DBG3"
