Skip to content

Instantly share code, notes, and snippets.

@dazld
Created June 8, 2016 11:09
Show Gist options
  • Save dazld/27b56e11f8c1fed6f2cb498b66b778b3 to your computer and use it in GitHub Desktop.
Save dazld/27b56e11f8c1fed6f2cb498b66b778b3 to your computer and use it in GitHub Desktop.
(ns tsl.circles
(:require [quil.core :as q]
[tsl.funcs :as f]
[quil.middleware :as m]))
(def WIDTH 512)
(def HEIGHT WIDTH)
(def random-pos
(f/make-randomizer 0 WIDTH))
(def random-size
(f/make-randomizer 1 3))
(def rc
(f/make-randomizer 0 255))
(defn setup []
(q/frame-rate 60)
{:circles [(make-circle)]})
(q/ceil (/ 255 10))
(def size 10)
(q/ceil (* 255 (/ size 255)))
(defn make-circle []
(let [size (random-size)]
{:x (random-pos) :y (random-pos) :size size :color [(rc) 0 0]}))
(defn is-not-overlapping [c1 c2]
(let [sum-radii (/ (+ (:size c1) (:size c2) 2) 2)
distance (f/distance c1 c2)]
(< sum-radii distance)))
(defn make-if-not-overlapping [circles]
(let [new-circle (make-circle)]
(if (every?
(partial is-not-overlapping new-circle) circles)
(conj circles new-circle)
circles)))
(defn update-state [{:keys [circles]}]
(let [next-circs (make-if-not-overlapping circles)]
{:circles next-circs}))
(defn draw-circle [{:keys [x y size color]}]
(apply q/fill color)
(q/ellipse x y size size))
(defn draw-state [{:keys [circles]}]
; (println (count circles))
(q/no-stroke)
(q/background 240)
(q/fill 0 0 0 0)
(doseq [circle circles]
(draw-circle circle)))
(q/defsketch cpack
:title "circle packing"
:size [WIDTH HEIGHT]
; setup function called only once, during sketch initialization.
:setup setup
; update-state is called on each iteration before draw-state.
:update update-state
:draw draw-state
:features [:keep-on-top]
; This sketch uses functional-mode middleware.
; Check quil wiki for more info about middlewares and particularly
; fun-mode.
:renderer :p2d
:middleware [m/fun-mode])
(ns tsl.funcs
(:require [quil.core :as q]))
(defn make-randomizer [min max]
(let [nums (range min max)]
#(rand-nth nums)))
(defn distance [p1 p2]
; return pythagorean distance between two points
(q/sqrt
(+
(q/sq (- (:x p2) (:x p1)))
(q/sq (- (:y p2) (:y p1))))))
(defn make-osc [start min max step]
; return a function that oscillates inputs
(fn [cur dir]
(let [next (+ cur (* dir step))]
(if (> next max)
[(- max step) (* -1 dir)]
(if (< next min)
[(+ min step) (* -1 dir)]
[next dir])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment