# encoding: UTF-8
# vf5 — 6TB 필러 상/하 틈 실측 (x 를 1mm 간격으로 훑어 필러가 실제 존재하는 지점에서만 비교)
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" }
s04 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_04_t9_240x1046" }
f4 = []; collect(s04, s04.transformation, f4)
out = []
g2.entities.grep(Sketchup::Group).select { |g| g.name.to_s.include?("_6TB_") }.each do |g|
  ff = []; collect(g, g.transformation, ff)
  b = g.bounds
  x0 = b.min.x * 25.4; x1 = b.max.x * 25.4
  y0 = b.min.y * 25.4; y1 = b.max.y * 25.4
  tg = []; bg = []
  10.times do |k|
    ymm = y0 + (y1 - y0) * (k + 0.5) / 10.0
    xx = x0
    hit = nil
    while xx <= x1
      zf = zs_at(ff, xx / MM, ymm / MM)
      if zf.length >= 2
        hit = [xx, zf.max * 25.4, zf.min * 25.4]
        break
      end
      xx += 0.5
    end
    next if hit.nil?
    z4 = zs_at(f4, hit[0] / MM, ymm / MM)
    tg << (z4.min * 25.4 - hit[1]) unless z4.empty?
    bg << (hit[2] - 106.5)
  end
  out << "#{g.name}: 상틈 #{tg.empty? ? '측정불가' : "최대 #{tg.map(&:abs).max.round(3)}mm"} (n=#{tg.length}), 하면오차 #{bg.empty? ? '-' : "최대 #{bg.map(&:abs).max.round(3)}mm"}, bbox z #{(b.min.z * 25.4).round(2)}..#{(b.max.z * 25.4).round(2)}, 평면폭 #{[x1 - x0, y1 - y0].min.round(2)}mm"
end
puts out.join("\n")
"VF5"
