Monday, March 2, 2009

Koch Snowflake



What is is?

Wolfram's Koch Snowflake.

The Recipe

  1. Take a line.
  2. Divide into three parts.
  3. Take the middle part and create an equilateral triangle bump from it.
  4. Repeat steps using each of the lines from the new shape.

Visually

To make the Koch snowflake, you start with three lines that make an equilateral triangle.







Ruby Version



# A vector implementation I made
require 'vector.rb'

class Koch
# Creates a Koch line from point p1 to point p2
def initialize(p1,p2)
@points = [p1,p2]
end


# Creates the next step in the fractal
def step
p1 = @points.shift
new_array = [p1]

# For all points in the shape,
# divide the line from next p1
# to next p2.
while(@points.length > 0)
p2 = @points.shift

third = Vector.between(p1,p2)
third.multiply(0.333)
two_third = Vector.between(p1,p2)
two_third.multiply(0.666)

# Adds p1 to the delta between p1 and p2 to
# get the actual 1/3 and 2/3 way points.
third.add_vector(p1)
two_third.add_vector(p1)

# Creates bump roughly equivalent to an equilateral triangle
# This is the key line here: the midpoint is moved along the normal
# (perpendicular line) of the line. If you do Vector.between(two_third,third)
# the normal points the opposite way and the bump will be backwards.
top = Vector.midpoint(third,two_third)
top.add_vector(Vector.between(third,two_third).normal)

# Adds the subdivisions into the point array.
new_array << third << top << two_third << p2

# Moves to the next point
p1 = p2
end

@points = new_array
end


def gl_paint
GL.Begin(GL::LINE_STRIP)
for p in @points
GL.Vertex2f(p.x,p.y)
end
GL.End
end
end

No comments:

Post a Comment