Voronoi diagram: Difference between revisions

Content added Content deleted
Line 2,517: Line 2,517:
{{libheader|JRubyArt}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby
JRubyArt is a port of processing to ruby
<lang ruby>
<lang ruby># frozen_string_literal: true
# frozen_string_literal: true


Tile = Struct.new(:x, :y, :color) do
attr_reader :colors, :positions
def sq_dist(a, b)
(x - a)**2 + (y - b)**2
end
end

attr_reader :tiles


def settings
def settings
Line 2,529: Line 2,534:
sketch_title 'Voronoi Diagram'
sketch_title 'Voronoi Diagram'
load_pixels
load_pixels
color_mode(HSB, 360, 1, 1)
color_mode(HSB, 1.0)
@colors = generate_colors(30)
@tiles = generate_tiles(30)
@positions = generate_positions(30)
draw_voronoi
draw_voronoi
update_pixels
update_pixels
Line 2,537: Line 2,541:
end
end


def generate_colors(num)
def generate_tiles(num)
(0..num).map { color(rand(360), 1.0, 1.0) }
(0..num).map { Tile.new(rand(width), rand(height), color(rand, 1.0, 1.0)) }
end

def generate_positions(num)
(0..num).map { Vec2D.new(rand(width), rand(height)) }
end
end


def draw_voronoi
def draw_voronoi
grid(width, height) do |x, y|
grid(width, height) do |x, y|
pos = Vec2D.new(x, y)
closest = tiles.min_by { |tile| tile.sq_dist(x, y) }
pixels[x + y * width] = closest.color
closest = positions.min_by { |posn| posn.dist(pos) }
index = positions.index closest
pixels[x + y * width] = colors[index]
end
end
end
end


def draw_voronoi_centers
def draw_voronoi_centers
positions.each do |pos|
tiles.each do |center|
no_stroke
no_stroke
fill 0
fill 0
ellipse(pos.x, pos.y, 4, 4)
ellipse(center.x, center.y, 4, 4)
end
end
end
end



</lang>
</lang>