#encoding:gbk

# Max管家SketchUp模型工具
# Http://maxgj.net
# Version: 1.0
# 2018.10.08
#WARN "DL is deprecated, please use Fiddle"

SKETCHUP_CONSOLE.hide

SKETCHUP_CONSOLE.clear

require 'open3'
require 'Win32API'
require 'pathname'
require 'sketchup'

def GetPrivateProfileString(section, key,inifile)
    val = "\0"*2560
    gps = Win32API.new('kernel32', 'GetPrivateProfileString',%w(p p p p l p), 'l')
    gps.call(section, key, "", val, 2560, inifile)
    val.delete!("\0")
    return val
  end

def WritePrivateProfileString(section, key,val,inifile)
   gps = Win32API.new('kernel32', 'WritePrivateProfileString',%w(p p p p), 'l')
   gps.call(section, key, val, inifile)
   return val
end

def addmodel
   model = Sketchup.active_model
   entities  = model.active_entities
   selection = model.selection
   view = model.active_view

   if selection.count == 0
      UI.messagebox('没选择物体！'.encode!( 'utf-8','gbk'))
      return
   end

   begin
      model = selection.first.definition
   rescue
      UI.messagebox('所选对像不是组件!'.encode!( 'utf-8','gbk'))
      return
   end

   rbpath = File.dirname(__FILE__)

   temppath="#{rbpath}/~temp"

   tempname=Time.new.to_f.to_s.gsub(".",'')
   picpath = temppath+"/"+tempname+".jpg"
   filepath= temppath+"/"+tempname+".skp"
   inipath = temppath+"/"+tempname+".ini"
   tempinipath="#{rbpath}/~temp.ini"

   nosel = Array.new
   entities.each { |obj|
      if !selection.include? obj
         nosel.push(obj)
         obj.hidden = true
      end
   }

   temp_camera = Sketchup::Camera.new
   temp_camera.set(view.camera.eye,  view.camera.target, view.camera.up)

   view.zoom selection
   view.zoom 0.95

   Sketchup.send_action(10602)

   view.write_image picpath
   group=Sketchup.active_model.entities.add_group(selection.to_a)
   definition = group.definition
   definition.save_as filepath

   Sketchup.send_action(10602)

   view.camera = temp_camera
   nosel.each { |obj|
      obj.hidden = false
   }

   str ="模型|SU||"+filepath.encode!( 'gbk','utf-8')+"|"+picpath.encode!( 'gbk','utf-8')+"|||"
   inipath=inipath.encode!( 'gbk','utf-8')

   WritePrivateProfileString("set", "in",str,inipath)

   tempinipath=tempinipath.encode!( 'gbk','utf-8')
   filexe=GetPrivateProfileString("SET","file_exe", tempinipath)

   cmdstr=filexe.gsub("\\", '/') +" \"#{inipath}\""

   Open3.popen3(cmdstr)

   puts "ok"

end


	icon = (File.dirname(__FILE__) +"/suico.jpg")

	maxgjtoolbar = UI::Toolbar.new ("Max管家".encode!( 'utf-8','gbk'))

	cmd = UI::Command.new("Max管家素材添加工具".encode!( 'utf-8','gbk')) {
		#encoding:gbk
		addmodel 
	}
	cmd.tooltip = "Max管家素材添加工具".encode!( 'utf-8','gbk')
	cmd.small_icon = icon
	cmd.large_icon = icon

if(maxgjtoolbar.count<1)
	maxgjtoolbar = maxgjtoolbar.add_item cmd
end
	maxgjtoolbar.show


