Skip to content

Instantly share code, notes, and snippets.

@fffej
Created August 1, 2009 20:34
Show Gist options
  • Save fffej/159803 to your computer and use it in GitHub Desktop.
Save fffej/159803 to your computer and use it in GitHub Desktop.
(ns uk.co.fatvat.ifs
(:import [javax.swing JFrame JPanel])
(:import [java.awt Color Polygon])
(:import [java.awt.image BufferedImage])
(:import [javax.swing.event MouseInputAdapter])
(:use clojure.contrib.def))
(defvar width 512 "Width of the rendering plane")
(defvar height 512 "Height of the rendering plane")
(defvar running (atom false) "Are we going?")
(defvar source (BufferedImage. (inc width) (inc height) BufferedImage/TYPE_INT_RGB)
"The current state of the image")
(defvar animator (agent [0 0])
"The agent responsible for animation, value is the point")
(defn get-bounds
[transform]
(let [points (take 10000 (iterate (partial calculate-point transform) [0 0]))
minx (apply min (map first points))
miny (apply min (map second points))
maxx (apply max (map first points))
maxy (apply max (map second points))]
[minx maxx miny maxy]))
(defn scale
"Scale x and y to be within the given bounds"
[[x y] [minx maxx miny maxy]]
(let [xscale (/ width (- maxx minx))
yscale (/ height (- maxy miny))]
[(Math/abs (dec (Math/floor (* (- x minx) xscale))))
(Math/abs (dec (Math/floor (* (- y miny) yscale))))]))
(defn draw-ifs
"Draw the IFS, by kicking off an infinite drawing loop"
[[x y] transform panel]
(let [bounds (get-bounds transform)]
(doseq [[px py]
(take-while
(fn [_] @running)
(iterate (partial calculate-point transform) [0 0]))]
(let [[sx sy] (scale [px py] bounds)]
(.setRGB source sx sy (rand Integer/MAX_VALUE))
(.repaint panel)))))
(defn launch-ui
"Start up the UI"
[transform]
(let [frame (JFrame. "Iterated Function Systems (http://www.fatvat.co.uk/")
panel (proxy [JPanel] []
(paintComponent
[g]
(proxy-super paintComponent g)
(.drawImage g source 0 0 nil)))]
(doto frame
(.addMouseListener (proxy [MouseInputAdapter] []
(mouseClicked
[e]
(if @running
(swap! running (constantly false))
(do
(swap! running (constantly true))
(send-off animator draw-ifs transform panel))))))
(.add panel)
(.setSize width height)
(.setVisible true))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment