Skip to content

Instantly share code, notes, and snippets.

@kohyama
Created November 15, 2015 17:23
Show Gist options
  • Save kohyama/98a11e9048748cf0e0cf to your computer and use it in GitHub Desktop.
Save kohyama/98a11e9048748cf0e0cf to your computer and use it in GitHub Desktop.
(ns barnsleys-fern)
(defn- affine [a b]
(fn [x] (map #(apply + (conj (map * %1 x) %2)) a b)))
(defn- move [x]
(let [afs (mapv (partial apply affine)
[[[[ 0.0 0.0 ] [ 0.0 0.16]] [0.0 0.0 ]]
[[[ 0.85 0.04] [-0.04 0.85]] [0.0 1.6 ]]
[[[ 0.2 -0.26] [ 0.23 0.22]] [0.0 1.6 ]]
[[[-0.15 0.28] [ 0.26 0.24]] [0.0 0.44]]])
p (rand-int 100)]
(condp > p
1 ((afs 0) x)
86 ((afs 1) x)
93 ((afs 2) x)
((afs 3) x))))
(def points (iterate move [0.0 0.0]))
(comment
;; example of use with minimal-canvas
(require '[minimal-canvas :refer (open! close! clear! gdo)])
(require 'barnsleys-fern)
(open! "Barnsley's fern" 480 480)
(defn draw-fern [n color]
(gdo (.setColor color))
(doseq [[x y] (take n barnsleys-fern/points)]
(let [ex (+ 240 (* 40 x))
ey (- 440 (* 40 y))]
(gdo (.drawLine ex ey ex ey)))))
(draw-fern 10000 java.awt.Color/black)
(clear!)
(draw-fern 100000 java.awt.Color/black)
(clear!)
(draw-fern 200000 (java.awt.Color. 0 128 0))
(close!)
)
(ns minimal-canvas)
(def ^:private fpg (atom nil))
(defn open! [title width height]
(let [f (javax.swing.JFrame. title)
p (.getContentPane f)]
(.setPreferredSize p (java.awt.Dimension. width height))
(.setBackground p java.awt.Color/white)
(.pack f)
(.setVisible f true)
(reset! fpg {:frame f :panel p :graphics (.getGraphics p)})))
(defmacro gdo [& body]
`(if @@#'minimal-canvas/fpg
(doto (:graphics @@#'minimal-canvas/fpg) ~@body)))
(defn clear! []
(if-let [p (:panel @fpg)]
(gdo (.setBackground (.getBackground p))
(.clearRect 0 0 (.getWidth p) (.getHeight p)))))
(defn close! []
(when-let [f (:frame @fpg)]
(.setVisible f false)
(.dispose f)
(reset! fpg nil)))
(comment
;; example of use
(require '[minimal-canvas :refer (open! gdo clear! close!)])
(open! "foo" 640 480)
(gdo (.drawLine 0 0 640 480))
(clear!)
(gdo (.setColor java.awt.Color/RED)
(.fillOval 176 96 288 288))
(close!)
)
@kohyama
Copy link
Author

kohyama commented Nov 15, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment