require "sketchup"

module JF; end

def JF::jitter
  m = Sketchup.active_model
  selection = m.selection
  sel = m.selection.to_a
  faces = selection.select {|e| e.typename == "Face"}
  fedges = faces.collect{|e| e.edges}
  edges = sel.select {|e| e.typename == "Edge"}
  edges.concat fedges
  edges.flatten!
  edges.uniq!
  return if edges.empty?
  lengths = edges.collect{|e| e.length}
  min, max = lengths.min, lengths.max
  avg = (min + max) / 100
  lmin = avg * 0.75
  lmax = avg * 1.25
  verts = []
  edges.each {|e| verts.concat e.vertices }
  verts.uniq!
  Sketchup.active_model.start_operation "Jitter"
  verts.each {|v|
    vec = Geom::Vector3d.new( rand - 0.5, rand - 0.5, rand - 0.5 )
    vec.length = ((lmax - lmin) * rand) + lmin
    v.curve_interior? && v.edges[0].explode_curve
    m.entities.transform_entities vec, v
  }
  selection.add edges
  Sketchup.active_model.commit_operation 
end

name = "jitter.rb"
unless file_loaded? name
  UI.menu("Plugins").add_item("Jitter") { JF.jitter }
  file_loaded name
end
