# skp_apply_steel.rb - 열려있는 모델의 모든 컴포넌트 정의 안 면(앞/뒷면)에 회색 스틸 재질 일괄 적용 후 저장.
# MODE=apply : 재질 적용 + 저장 / MODE=verify : 재질 적용된 면 수만 집계
# Plugins 폴더에 두고 SketchUp 을 대상 .skp 인자와 함께 실행하면 동작.

# 윈도우 환경변수는 CP949 로 들어온다. 파일 안의 한글 리터럴(UTF-8)과 그대로 이으면
# Encoding::CompatibilityError 가 난다. 그래서 읽는 즉시 UTF-8 로 태그를 맞춘다.
def env_u(k, d)
  v = ENV[k]
  return d unless v
  # force_encoding 은 '꼬리표만' 바꾼다. 바이트는 그대로 CP949 라서 한글 경로가 안 열린다.
  # 실제로 UTF-8 바이트로 변환(transcode)해야 파일 접근까지 된다.
  begin
    v.dup.force_encoding('CP949').encode('UTF-8')
  rescue
    v.dup.force_encoding('UTF-8')
  end
end

D    = env_u('SKP_DIR',  'E:/도진팩토리/3D스캔및티칭시스템/fab_models/sketchup/')
OUT  = D + env_u('SKP_NAME', '500PRO_전체부재') + '_메탈.skp'
LOG  = D + '_steel.log'
MODE = ENV['STEEL_MODE'] || 'apply'
RGB  = [160, 162, 165]

def lg(m); File.open(LOG, 'a') { |f| f.puts("#{Time.now} [#{MODE}] #{m}") }; end

def walk(ents, mat, apply)
  total = 0; painted = 0
  ents.each do |e|
    if e.is_a?(Sketchup::Face)
      total += 1
      if apply
        e.material = mat
        e.back_material = mat
      end
      painted += 1 if e.material && e.material.name == 'Steel'
    elsif e.is_a?(Sketchup::Group)
      t, p = walk(e.entities, mat, apply); total += t; painted += p
    end
  end
  [total, painted]
end

begin
  m = Sketchup.active_model
  apply = (MODE == 'apply')
  mat = m.materials['Steel']
  if mat.nil?
    if apply
      mat = m.materials.add('Steel')
      mat.color = Sketchup::Color.new(*RGB)
      mat.alpha = 1.0
    end
  end
  m.start_operation('Steel', true) if apply
  total = 0; painted = 0
  m.definitions.each do |d|
    next if d.image?
    t, p = walk(d.entities, mat, apply); total += t; painted += p
  end
  t, p = walk(m.entities, mat, apply); total += t; painted += p
  m.commit_operation if apply
  lg("defs=#{m.definitions.length} faces_total=#{total} faces_steel=#{painted}")
  if apply
    m.save(OUT)
    lg("saved=#{File.exist?(OUT)} size=#{File.size(OUT)}")
  end
  lg('DONE')
rescue => e
  lg("ERROR #{e.class}: #{e.message}")
end
