Flow Fields in Clojure
This is about the generative art technique of using a flow field to generate a cohesive set of curves across an image. Fidenza by Tyler Hobbs is a classic example. The works in the series use flow fields to implement the overall curviness.
For my part, I won't be making anything so nice looking. As we saw last time, all those choices about colors are too much for my unsophisticated brain. No, this article is going to explore how interesting curve fields can be made by some really simple techniques.
Speaking of last time, let's import the namespace we made in the simple images article. See ./deps.edn for how this is referenced. There will be some math (brace yourselves) so we might as well import that too.
(require '[simpleimg :as img])
(require '[clojure.math :as m])
Flow fields
A flow field is essentially a function \(f(y,x) \rightarrow \theta\) that returns an angle for every point
\((y,x)\). We'll start with a constant 45°, which points down-right on the simpleimg canvas.
(def down-right (constantly (/ m/PI 4)))
We will use that to turtle draw on one of the canvases from last post, a tenth of a pixel at a time in whatever direction a flow function gives for the turtle's position, stopping when we've traveled some equivalent pixel distance or hit the edge of the canvas.
(def step-len 0.1)
(defn draw-curve! [{:keys [height width set-pixel!]} get-flow length start-y start-x]
(loop [y start-y
x start-x
steps (/ length step-len)]
(when (> steps 0)
(set-pixel! (long y) (long x))
(let [theta (get-flow y x)
y (+ y (* step-len (m/sin theta)))
x (+ x (* step-len (m/cos theta)))]
(if (or (< y 0)
(< x 0)
(>= y height)
(>= x width))
(recur nil nil 0)
(recur y x (dec steps)))))))
Let's try it out on a 100 pixel square canvas, starting at \((0,0)\) and drawing according to the flow:
(let [size 100
canvas (img/make-canvas size size)]
(draw-curve! canvas down-right (* 2 size) 0 0)
((:save! canvas) "diagonal-flow"))
Success! Instead of going row by row and column by column like in the simple images article, we set the flow to the angle we want, start in the top-left corner, and let the flow bring us to our destination.
"We didn't spin up all this apparatus to draw straight lines!" I hear you shouting, so let's get the field implementation wrapped up and get into our flow state.
Forming the flow
The real flow functions we'll use are function-returning functions \(g(h, w) \rightarrow f(y, x) \rightarrow \theta\). This'll help later on when we want to do scaling and translating, but for now we just need an excuse to get the canvas dimensions involved as arguments so we can copy Tyler Hobbs's first example.
We want a gradual transition from 0° (East) at the top of the canvas to to 180° (West) at the bottom.
(defn make-turn-flow
[height _width]
(fn [row _col]
(* m/PI (/ row height))))
Simple as \(\pi\). Visualize it like we did last time:
(let [size 100
canvas (img/make-canvas size size)
turn-flow (make-turn-flow size size)]
(draw-curve! canvas turn-flow 1000 5 0)
((:save! canvas) "turn"))
Curvaceous, flowy, stunning. Now let's see Paul Allen's flow visualize the whole
field.
Visualizing
We're going to draw curves all over the canvas, so we need some point sampling methods to determine starting points. One way is to start a line every \(n\) cells.
(defn draw-grid
"Returns a fn that draws a curve every `n` cells"
([n]
(fn draw! [canvas flow curve-len]
(dotimes [row (/ (canvas :height) n)]
(dotimes [col (/ (canvas :width) n)]
(draw-curve! canvas flow curve-len (* row n) (* col n))))))
([] (draw-grid 10)))
Another is to draw \(n\) lines whose starting points are totally random.
(defn draw-random
"Returns a fn that draws `n` curves starting at random cells"
([n]
(fn draw! [c f curve-len]
(dotimes [_ n]
(draw-curve! c f curve-len
(rand-int (c :height))
(rand-int (c :width))))))
([] (draw-random 2000)))
From here on, we'll make the canvases bigger to show more detail.
(def default-canvas-size 800)
Now we can make a nice lil function to package all this up and make an image visualizing a flow function.
(require '[clojure.java.io :as io])
(defn canvas-exists? [filename]
(let [filename (str filename ".png")]
(when (.exists (io/file filename))
filename)))
(defn make-flow-img!
[make-flow filename
& {:keys [canvas-size palette
curve-len draw-fn]
:or {palette img/default-palette
curve-len 50
draw-fn (draw-random 2000)}}]
(if-let [filename (canvas-exists? filename)]
filename
(let [canvas (img/make-canvas palette default-canvas-size default-canvas-size)
flow (make-flow default-canvas-size default-canvas-size)]
(draw-fn canvas flow curve-len)
((:save! canvas) filename))))
Let's see what the whole turn field looks like.
(make-flow-img! make-turn-flow "turn-flow")
And there's our basic visualization technique sorted. Let's sample the delicious curves!
Prelude to a flow
I promise there are examples of actual mathematical flow functions in the next section. Real quick tho, let's define some helpers to keep the examples concise.
By default, if we map a function like \(f(x) = x^2\) directly to the canvas, the origin will be in the top left and our window will be from 0 to canvas size in both dimensions. Instead we'll have a wrapper function of a function \(f(y,x)\) to:
- center the origin by default
- make the default window from -0.5 to 0.5 in both dimensions
- allow scaling and offsetting both coordinates and the angle
(defn unit-fn
"Function wrapper that normalizes to canvas size, sets origin to the center of the canvas,
and allows scaling and translating of the sample grid the resulting angle."
[flow ang-off ang-scale y-scale x-scale y-off x-off]
(fn [height width]
(fn [y x]
(let [y (* (- (/ y height) (+ y-off 0.5)) y-scale)
x (* (- (/ x width) (+ x-off 0.5)) x-scale)]
(+ ang-off (* ang-scale (flow y x)))))))
Some fields (like Perlin noise) are more expensive to calculate, and we can trade some resolution for speed by precomputing the flow at a pixel level and storing it in an array.
(defn precompute-flow-field
"Returns a function that precomputes a flow field and stores it in a flat array."
[height width gen-fn]
(let [field (float-array (* width height) 0.0)
cell-fn (gen-fn height width)]
(dotimes [row height]
(let [row-off (* row width)]
(dotimes [col width]
(aset-float field (+ row-off col) (cell-fn row col)))))
(fn [height width]
(fn [y x]
(aget field (+ (* (int y) width) (int x)))))))
Now we can wrap all that up with make-flow-img!, passing arguments where they belong, and
allowing the user to choose a different color palette.
(defn make-visualizer
"Returns a function that creates a visualization image based on a flow function."
[flow-name flow-fn & {:keys [palette precompute?] :or {palette img/default-palette}}]
(fn [& {:keys [ang-off ang-scale
y-scale x-scale
y-off x-off
suffix]
:or {ang-off 0
ang-scale 1
y-scale 1
x-scale 1
y-off 0
x-off 0
suffix ""}
:as args}]
(let [flow-fn (unit-fn flow-fn ang-off ang-scale y-scale x-scale y-off x-off)
filename (str flow-name "-"
y-scale "-" x-scale
"_"
y-off "-" x-off
"x"
ang-scale
(when (not (zero? ang-off)) (str "+" ang-off))
suffix)]
(apply
make-flow-img!
(if (and precompute? (not (canvas-exists? filename)))
(precompute-flow-field default-canvas-size default-canvas-size flow-fn)
flow-fn)
filename
(apply concat (into [] (assoc args :palette palette)))))))
One more time, wrap these tools up. This time we construct a function that holds some parameters constant and allows others to vary, creating a series of images in parallel.
(defn make-series-visualizer
"Returns a function to produce a series of visualizations of the same flow field in
parallel."
[viz & outer-args]
(fn [& inner-args]
(map #(print (str % " "))
(pmap #(apply viz %)
(map #(concat % inner-args) outer-args)))))
tl;dr: This lets us combine a simple (fn [y x] ...) with a list of standard
transformations like [:y-scale 1.5 :x-off 0.5] to create a (fn [& args] ...) that
produces (in parallel) a series of images with optional additional arguments. See the
following sections for usage.
Interesting functions
The simplest flow field is a single continuous \(f(y,x)\). You can wring a lot of interesting formations from a single function by scaling and translating.
Plain arctangent
Specifically, the 2-argument version atan2(y, x), which returns a point's angle from the
x-axis. Moving the origin around shifts the whole scheme.
(def arctan!
(make-series-visualizer
(make-visualizer
"arctan"
(fn [y x]
(m/atan2 y x)))
[]
[:y-off 0 :x-off 0.375]
[:y-off 0.420 :x-off 0.69]
[:x-scale 3]))
(arctan!)
This is the simplest version of calculating the heading of a function's gradient at that point. By plugging in the coords directly we're effectively visualizing the gradient of the function \(f(y,x)=\frac{x^2}{2} + \frac{y^2}{2}\).
If you add 90° (~1.57 radians) to the result, you get concentric ripples, essentially the level set of the function at the point's distance from the origin. Doing this for a 2D function surface draws its contour lines.
(def ripples! (partial arctan! :ang-off 1.57))
(ripples!)
Adding slightly more or less than 90° to the gradient makes spirally swirls.
(arctan! :ang-off 2)
(arctan! :ang-off 1)
Egg Carton
\(f(y,x) = \cos{y}\sin{x}\)
Mix and match sin and cos to change the basic pattern at small scales.
(defn egg [y x]
(* (m/cos y) (m/sin x)))
(def eggs!
(make-series-visualizer
(make-visualizer "egg" egg)
[]
[:y-scale 2 :x-scale 2]
[:y-scale 5 :x-scale 5]
[:y-scale 10 :x-scale 10]
[:y-scale 25 :x-scale 25
:draw-fn (draw-random 4000)]))
(eggs!)
(eggs! :ang-scale 3)
(eggs! :ang-scale 7)
Bell curve
\(f(y,x) = e^{-(x^2 + y^2)}\)
(def bells!
(make-series-visualizer
(make-visualizer
"bell"
(fn [y x]
(m/pow m/E (- (+ (* x x) (* y y))))))
[:draw-fn (draw-grid 30) :curve-len 500]
[:y-scale 2 :x-scale 2]
[:y-scale 1 :x-scale 3]
[:y-scale 5 :x-scale 2]))
(bells!)
(bells! :ang-scale 2)
(bells! :ang-scale 2 :y-off 0.5 :x-off 0.7)
Heart
(def hearts!
(make-series-visualizer
(make-visualizer
"heart"
(fn [y x]
(+ (* x x)
(m/pow
(- y (m/sqrt (abs x)))
2)))
:palette (img/make-palette img/default-bg [0xE0 0x25 0x30]))
[:y-scale -1]
[:y-scale -5 :x-scale 5]
[:y-scale -10 :x-scale 10]))
(hearts!)
Saddle
\(f(y,x) = x^2 - y^2\)
(def saddle!
(make-series-visualizer
(make-visualizer
"saddle"
(fn [y x]
(- (* x x)
(* y y))))
[]
[:y-scale 2.5]
[:x-scale 2.5]
[:y-off 0.5 :x-off 0.5]
[:y-off 0.5 :x-off 0.5 :y-scale 2]
[:y-off 0.5 :x-off 0.5 :x-scale 2]))
(saddle!)
(def saddle-grad!
(make-series-visualizer
(make-visualizer
"saddle-grad"
(fn [y x]
(m/atan2 (- y) x)))
[]
[:y-off 0.5 :x-off 0.5]))
(saddle-grad!)
Monkey Saddle
\(f(y,x) = x^3 - 3xy^2\)
(def monke!
(make-series-visualizer
(make-visualizer
"monke"
(fn [y x]
(- (* x x x)
(* 3 x y y))))
[]
[:y-scale 2.5]
[:x-scale 2.5]
[:y-off 0.5 :x-off 0.5]
[:y-off 0.5 :x-off 0.5 :y-scale 2 :ang-scale 0.5]
[:y-off 0.5 :x-off 0.5 :x-scale 2 :ang-scale 0.5]))
(monke!)
Banana
\(f(y,x) = (a-x)^2+b(y-x^2)^2\)
i.e. the Rosenbrock function
(defn banana-flow [a b]
(fn [y x]
(+ (m/pow (- a x) 2)
(* b (m/pow (- y (* x x)) 2)))))
(defn banana-plant [a b]
(make-visualizer
(str "banana(" a "," b ")")
(banana-flow a b)
:palette (img/make-palette img/default-bg [0xFF 0xB8 0x00])))
(defn plantation [a b]
(make-series-visualizer
(banana-plant a b)
[:ang-scale 0.5 :y-scale 0.1 :x-scale 0.1]
[:ang-scale 0.5 :x-scale 0.5 :y-scale 1.0]
[:ang-scale 0.5 :y-scale 0.5 :x-scale 1.0]
[:ang-scale 0.5 :y-scale 1.5 :x-scale 1.5]))
((plantation 1 10))
((plantation 5 10))
((plantation 10 10))
((plantation 1 100))
((plantation 10 100))
((plantation 50 100))
I really like how the later ones in this series look like some kind of abstract representation of a banana farm where bananas grow in rows like corn, one bunch per stalk.
((plantation 100 10) :draw-fn (draw-grid 20))
Himmelblau's function
\(f(y,x) = (x^2+y-11)^2 + (x+y^2-7)^2\)
Wacky polynomials with multiple extrema in view are fun. Again, we'll want to visualize the gradient of this one:
\(\frac{\partial f}{\partial y} = 2(x^2+2y(x+y^2-7)+y-11)\)
\(\frac{\partial f}{\partial x} = 2(2x(x^2+y-11)+x+y^2-7)\)
(def himmelblau!
(make-series-visualizer
(make-visualizer
"blau"
(fn [y x]
(m/atan2
(* 2 (+ (* x x)
(* 2 y (+ x (* y 2) -7))
y
-11))
(* 2 (+ (* 2 x (+ (* x x) y -11))
x
(* y y)
-7))))
:precompute? true)
[:y-scale 2 :x-scale 3]
[:y-scale 5 :x-scale 5]
[:y-scale 10 :x-scale 10]
[:y-scale 25 :x-scale 25]))
(himmelblau!)
Contours:
(himmelblau! :ang-off 1.57)
Swirly contours:
(himmelblau! :ang-off 2)
Perlin noise
We've warmed up, done our homework, and eaten our vegetables – now, can I please stop thinking about math and let a noise algorithm design an endless set of interesting flows for me?
15 minute no-bake, one-pot Perlin noise
No, actually. Since I'm not using Quil, we'll have to whip up a homemade noise function
using the just the math in our cupboards. Luckily the recipe from the box Wikipedia tastes
just fine.
So: what is Perlin noise? For our purposes, it's a function of two variables returning a scalar value just like the regular flow function. Really, it can have as many dimensions as you need. It has these characteristics:
- at integer coordinates (grid intersections), the value is 0
- between the grid intersections the values vary smoothly between \(\pm1/\sqrt{2}\) (we will normalize ours to \(\pm1\))
- consistently multiplying the input coordinates by some factor gives a higher frequency variation that retains smoothness
- you can overlay noise at varying frequencies to create more jagged curves (for a significant performance cost)
How does it work? Consider a single tile on a grid. For each of the four corners at the integer coordinates, we choose a random cardinal direction to be the gradient at that point. Then, to sample the field at point \(P=(x,y)\), we:
calculate the offset from \(P\) to each corner
(defn get-corners "Returns the four integer ordered pairs that form the corners of the grid tile containing `x` and `y`." [x y] (let [x1 (int (m/floor x)) x2 (inc x1) y1 (int (m/floor y)) y2 (inc y1)] [[x1 y1] [x1 y2] [x2 y1] [x2 y2]])) (defn get-offset "Returns the vector displacement from point 1 to point 2" [[x1 y1] [x2 y2]] [(- x1 x2) (- y1 y2)])calculate the dot product between \(P\)'s offset from each corner and the vector components of that corner's gradient
(defn dot-product [v1 v2] (apply + (map * v1 v2)))perform a bilinear interpolation between the corners at \(P\), applying the Smooth(er)step function to the offset vector components to keep things nice and chill near the grid intersections
(defn smootherstep [t] (* t t t (+ (* t (- (* t 6) 15)) 10))) (defn interpolate [x y s t u v] (let [x (smootherstep x) y (smootherstep y)] (+ (* (- 1 x) (- 1 y) s) (* (- 1 x) y t) (* x (- 1 y) u) (* x y v))))
The dot product is what gives the characteristic 0 values at grid intersections, because at or near the grid intersection, the magnitude of the offset of \(P\) is at or near zero. Using smoothstep on the coordinates eases the transitions between tiles, which can be jagged due to the abrupt swapping of the far gradients as you cross the line.
OK, we've done our mise en place. It's time to heat up the pan and get cooking.
(defn make-noise-field
([tile-size]
(let [tile-nodes (* tile-size tile-size)
gradients (->> #(shuffle [[1 1] [1 -1] [-1 1] [-1 -1]])
(repeatedly (/ tile-nodes 4))
(apply concat)
(into []))
get-gradient (fn [x y]
(let [x (mod (int x) tile-size)
y (mod (int y) tile-size)]
(get gradients (+ (* y tile-size) x))))]
(fn noise [x y]
(let [corners (get-corners x y)
offsets (map #(get-offset [x y] %) corners)
gradients (map #(apply get-gradient %) corners)
dots (map dot-product offsets gradients)]
(* (m/sqrt 2) ;; natural range is ±1/√2, so this normalizes to ±1
(apply interpolate (- x (m/floor x)) (- y (m/floor y)) dots)))))))
(def noise (make-noise-field 256))
Back to flowing
Bon appetit!
(def perlin-params
[[]
[:y-scale 2 :x-scale 2]
[:y-scale 5 :x-scale 5]
[:y-scale 10]
[:x-scale 10]
[:y-scale 11 :x-scale 7 :draw-fn (draw-grid 20)]
[:y-scale 64 :x-scale 64 :draw-fn (draw-grid 20)]])
(def perlin!
(apply make-series-visualizer
(make-visualizer "perlin" noise :precompute? true)
perlin-params))
(perlin!)
(perlin! :ang-scale 3.14)
Because Perlin noise is 0 at integer coordinates, treating it as an angle causes a broadly left-to-right bias which can be redirected by offsetting.
(perlin! :ang-off 1.57)
That's smoove af but it could use a little more character. We can enhance the turbulence by sampling multiple times with successively higher frequency and less strength. Each layer costs as much as the previous one to calculate, so more layers increase runtime linearly – we'll stick to one additional layer.
(defn layered-noise [frequency strength]
(fn [y x]
(+ (noise y x) (* (noise (* frequency y) (* frequency x)) strength))))
(def layered-perlin!
(fn [frequency strength]
(apply make-series-visualizer
(make-visualizer
(str "layered-perlin" frequency "x" strength)
(layered-noise frequency strength)
:precompute? true)
perlin-params)))
((layered-perlin! 6 0.4))
((layered-perlin! 10 0.7))
Other ideas
For performance reasons, we should go no further. All that noise seriously grows the build time of this article (have I mentioned this is an an org-babel literate source file?) and it's gotta stop somewhere.
But even tho this whole thing is confined to a single, agressively simple technique, we've only scratched the surface of variations. Some further ideas to try, if you're so inclined:
- generate curve starting points by other methods, like random circle packing
- round angles to nearest 15°/30°/45°/etc to create increasingly blocky shapes
- when visualizing the gradient of a 2D function, use the magnitude (ignored thusfar; we only used the heading) to control step length and show steepness
- combine multiple functions by various means
- simple masking creates hard transitions at the boundary
- masking with smooth interpolation as a function of distance from the boundary
- use Perlin noise as the degree of interpolation to vary smoothly across the whole canvas
- use real-world data, like GIS topography or color values in an image file
- use arbitrary algorithms, like cellular automata, rather than continuous functions to initialize the field
































































-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)
-0.1-0.1_0-0x0.5.png)
-1.0-0.5_0-0x0.5.png)
-0.5-1.0_0-0x0.5.png)
-1.5-1.5_0-0x0.5.png)














































