# Название:      Круг от края
# Сайт:            http://stroyka.in 
# Дата:           16.05.2011  
# Автор:         Sahi (г.Рязань)
# Дата обновления:    16.02.2016 
# Описание:  Скрипт рисует окружность от края.
#=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=#
module Sahi
                 
module Krug
                 
class Risuem_krug_otkraya
                                          
   def initialize
     @vverh = true
     @krug = false
     @folofme = false
     @erase = false
     @vector = false if not defined? @vector
     @@Krug_segment = 24 if not defined? @@Krug_segment
     mydir = File.dirname(__FILE__)
     cursor = mydir + "/images/cursor.png"
     cursor = cursor.tr("\\","/")
		 @@cursor = UI::create_cursor(cursor, 1, 24)
  end
 # -------             # -------               # -------
 def onSetCursor
	 UI::set_cursor(@@cursor)
end
# -------             # -------               # -------
  def create_krug_otkraya(pts)
     @krug = true
     model=Sketchup.active_model
     model.start_operation("Circle >", false,false,false) rescue model.start_operation("Circle >", true) rescue model.start_operation("Circle >")
     entities=model.active_entities
     group = entities.add_group
     ents = group.entities
     base = ents.add_circle(@pt0, @vector, @radius, @@Krug_segment)
     ents.add_face(base)

     group.explode
     model.commit_operation
     #Sketchup.active_model.select_tool(nil)
     self.reset
  end
# -------             # -------               # -------
def increment_state
   begin
    case @state
    when 1
      @krug = false
      @ip1.copy! @ip
      Sketchup::set_status_text "Specify the end point of the circle ©" #  
      @vlevo = @vpravo = @vniz = true
    when 2
      @radius = @length/2
      @pt0 = @pts[0].offset(@yvec, @radius)
      @ptt = Array.new
      @ptt[0] = @pts[0]
      @xvec = @ptt[0] - @pt0
       @cvec = @xvec.cross @zvec
      trans  = Geom::Transformation.rotation(@pt0,@zvec,@angle.degrees)
      1.upto(@@Krug_segment.to_i){@ptt.push @ptt.last.transform(trans)}
      @vector = @zvec
      self.create_krug_otkraya(@pt0)
    end
    rescue
    self.reset
    end
  end
 # -------             # -------               # ------- 
def getExtents
   bbox = Geom::BoundingBox.new
   bbox.add(@ip.position)if @ip and @ip.valid?
   bbox.add(@pts) if @pts[1] != nil
   return bbox
 end
 # -------             # -------               # -------
  def reset
     @ip = Sketchup::InputPoint.new
     @ip1 = Sketchup::InputPoint.new
     @drawn = false
     @pts = Array.new
     @state = 0
     @length = 0
     @angle = nil
     @color = "DarkViolet"
     @vector = false if @vverh
      Sketchup::set_status_text "Sides ", SB_VCB_LABEL  # "Сегментов "
      Sketchup::set_status_text @@Krug_segment.to_s, SB_VCB_VALUE
     Sketchup::set_status_text("Set the parameters of the circle (the number of segments) ©", SB_PROMPT)   # "Set the parameters of the circle (the number of segments) ©"
    end
# ========================================= #                                               
  def activate
    self.reset
  end
# ========================================= #
# ========================================= #                                                 
  def deactivate(view)
    view.invalidate if @drawn
    Sketchup.active_model.commit_operation
    Sketchup.active_model.select_tool(nil)
  end
# ========================================= #
def set_current_point(view)
    view.tooltip = @ip.tooltip
    need_draw = true
  case @state
  when 0
  @pth = Array.new
  @pth[0] = @pts[0] = @ip.position
  #@zvec = Geom::Vector3d.new(0,0,1)
  @sel.each{|plan|@zvec = plan.normal if plan.is_a?(Sketchup::Face)} rescue @zvec = Geom::Vector3d.new(0,0,1)
      @sel.clear if @sel != nil
      
      @zvec = @vector if @vector
      vectr = @zvec.axes
      xvec = vectr.x
     @angle = 360.0/@@Krug_segment.to_i
     
     size = view.pixels_to_model(20, @pth[0])
     @pt = @pth[0].offset(xvec, size)
      @ptg = @pth[0].offset(@zvec, size)
      
     trans  = Geom::Transformation.rotation(@pt,@zvec,@angle.degrees)
     1.upto(@@Krug_segment.to_i){@pth.push @pth.last.transform(trans)}
     @planes = Geom.fit_plane_to_points @pth
  when 1
       @ptt = Array.new
       pt = @ip.position
       @pts[1] = pt.project_to_plane @planes 
       @yvec =  @pts[1] - @pts[0]

      @length = @pts[0].distance @pts[1] #if @shift0
      
    if(@length != 0)
       @pt0 = @pts[0].offset(@yvec, @length/2) if(@yvec.length > 0)
         
      @ptt[0] = @pts[0]
      trans  = Geom::Transformation.rotation(@pt0,@zvec.reverse,@angle.degrees)
      0.upto(@@Krug_segment.to_i){@ptt.push @ptt.last.transform(trans)}

      Sketchup::set_status_text "Diameter:   ", SB_VCB_LABEL  # " Diameter:"
      Sketchup::set_status_text @length.to_s, SB_VCB_VALUE
      end
    end
    view.invalidate if need_draw
  end
# -------             # -------               # -------  
  def draw(view)
    @drawn = false
    if( @ip.valid?)#&& @ip.display? )
      @ip.draw(view)
      @color = "DarkGray"
      @color = "Blue" if @vector == Z_AXIS
      @color = "Red" if @vector == X_AXIS
      @color = "LimeGreen" if @vector == Y_AXIS
   case @state
    when 0
     view.line_width = 2
       view.set_color_from_line(@ptg,@pth[0])
        view.draw(GL_LINE_STRIP, @pth)
         view.draw_points @pth[0], 6, 2, @color
          @drawn = true
          
   when 1
    if(@length != 0)
      view.line_width=2
     view.set_color_from_line(@pt0,@pth[0])
      view.draw(GL_LINE_STRIP, @pts)
      view.draw_points @pts[1], 6, 2, "DarkViolet"
        view.line_width = 2
         view.drawing_color =  @color
          view.draw(GL_LINE_STRIP, @ptt)
          
      @drawn = true
    end
  end
  end
  end 
# -------             # -------               # -------
  def onMouseMove(flags, x, y, view)
    if( !@ip.pick(view, x, y, @ip1) )
      return false
    end
    view.tooltip = @ip.tooltip
    ph=view.pick_helper
    ph.do_pick x,y
    @sel = ph.path_at(0)
    self.set_current_point(view)
  end
  # -------             # -------               # -------     
 def onLButtonDoubleClick(flags, x, y, view)
   Sketchup.active_model.select_tool(nil)
   end
# -------             # -------               # -------
def onLButtonDown(flags, x, y, view)
   @state += 1
    self.set_current_point(view)
    self.increment_state
    view.lock_inference
  end
# -------             # -------               # -------     
def onLButtonUp(flags, x, y, view)

  end
# -------             # -------               # -------  
def onCancel(flag, view)
    view.invalidate if @drawn
   # self.reset
  end
 # -------             # -------               # -------
  def onUserText(text, view)
    begin
      value = text.to_l
    rescue
      UI.beep
      value = nil
      Sketchup::set_status_text "", SB_VCB_VALUE
    end
    return if !value

  case @state
    when 0
      @@Krug_segment = text.to_i if(text.to_i > 2)
       self.set_current_point(view)
    when 1
      @state += 1
      @length = text.to_l
      self.increment_state
    end
  end
# -------             # -------               # -------
def onKeyDown(key, repeat, flags, view)
   
  case flags
    when 42  #  SHIFT  left
     if @vverh
       @vverh = false
        @vector = @zvec if @state < 1
       else
       @vector = false if @state < 1
       @vverh = true 
       end
    self.set_current_point(view)
    
    when 331 # <---
      @vector = Y_AXIS if @state < 1
      @vverh = false
      self.set_current_point(view)
      
    when 333  # -->
      @vector = X_AXIS if @state < 1
      @vverh = false
      self.set_current_point(view)
      
    when 328 # ^
      @vector = Z_AXIS if @state < 1
      @vverh = false
      self.set_current_point(view)
      
    when 336 #
      @vector = @zvec if @state < 1
      @vverh = false
      self.set_current_point(view)
  end
end
# -------             # -------               # -------
 def onKeyUp(key, rpt, flags, view)
     view.invalidate if @drawn
     #@vector = false
    if( key == CONSTRAIN_MODIFIER_KEY && view.inference_locked? )
      view.lock_inference
    end
    #self.set_current_point(view)
   end
end # class
	if( not file_loaded?(File.basename(__FILE__)))  
	#UI.menu("Plugins").add_item("Круг от грани"){ Sketchup.active_model.select_tool Sahi::Krug::Risuem_krug_otkraya.new }
	UI.menu("Draw").add_item("Circle from edge"){ Sketchup.active_model.select_tool Sahi::Krug::Risuem_krug_otkraya.new }
#----------------------------------------------------------------------------- 
  sahi_toolbar_tools = UI::Toolbar.new("Circle from edge")
#----------------------------------------------------------------------------- 
	cmd = UI::Command.new("krug_otkraya"){ Sketchup.active_model.select_tool Sahi::Krug::Risuem_krug_otkraya.new }
	cmd.small_icon = "./images/CircleByDiameter_16.png"
	cmd.large_icon = "./images/CircleByDiameter_24.png"
	cmd.tooltip = "Circle by Diameter (2 Points)"
	cmd.status_bar_text =  "Draw a Circle by its Diameter through the Designation of 2 Points"
	sahi_toolbar_tools.add_item(cmd)
  sahi_toolbar_tools.show

end
# ------------------------ # 
end # Krug
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= #
end # Sahi
