Last active
March 11, 2023 02:02
-
-
Save mattdesl/f2fe013e973f9adb29b7d383c6386758 to your computer and use it in GitHub Desktop.
quadtree subdivision with ryu (this could probably be written in a more functional style...)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; draws a rectangle on canvas | |
(fn draw-rect (x y w h) (do | |
(canvas/line x y (+ x w) y) | |
(canvas/line (+ x w) y (+ x w) (+ y h)) | |
(canvas/line x (+ y h) (+ x w) (+ y h)) | |
(canvas/line x y x (+ y h)) | |
)) | |
; array utility - for-each | |
(fn each (arr itr) | |
(for (i (length arr)) | |
(itr (array/nth arr i) i arr))) | |
; array utility - for-map | |
(fn map (arr itr) (do | |
(var result []) | |
(each arr (fn (v idx lst) | |
(array/push result (itr v idx lst)))) | |
result)) | |
; draws a cell | |
(fn draw-cell (cell) (do | |
(var x0 (array/nth cell 0)) | |
(var y0 (array/nth cell 1)) | |
(var x1 (array/nth cell 2)) | |
(var y1 (array/nth cell 3)) | |
(draw-rect x0 y0 (- x1 x0) (- y1 y0)) | |
)) | |
; fills a cell | |
(fn fill-cell (cell color) (do | |
(var x0 (array/nth cell 0)) | |
(var y0 (array/nth cell 1)) | |
(var x1 (array/nth cell 2)) | |
(var y1 (array/nth cell 3)) | |
(canvas/rect x0 y0 (- x1 x0) (- y1 y0) color) | |
)) | |
; lerp util | |
(fn lerp (min max t) (+ (* min (- 1 t)) (* max t))) | |
; bsp util | |
(fn bsp (x0 y0 x1 y1 maxDepth) (do | |
(var cells []) | |
(if (<= maxDepth 0) (set maxDepth 1)) | |
(fn bsp-inner (cell depth) (do | |
(if (< depth maxDepth) (do | |
(var x0 (array/nth cell 0)) | |
(var y0 (array/nth cell 1)) | |
(var x1 (array/nth cell 2)) | |
(var y1 (array/nth cell 3)) | |
(var horiz (> (random) 0.5)) | |
(var fract (random)) | |
(var nd (+ 1 depth)) | |
(var split []) | |
(if horiz | |
(set split [ [ | |
x0 y0 | |
(lerp x0 x1 fract) y1 | |
] [ | |
(lerp x0 x1 fract) y0 | |
x1 y1 | |
] ]) | |
(set split [ [ | |
x0 y0 | |
x1 (lerp y0 y1 fract) | |
] [ | |
x0 (lerp y0 y1 fract) | |
x1 y1 | |
] ]) | |
) | |
(each split (fn (cell) (do | |
(array/push cells cell) | |
(bsp-inner cell nd) | |
))) | |
)) | |
)) | |
(bsp-inner [ x0 y0 x1 y1 ] 0) | |
cells | |
)) | |
; color palettes | |
(var colors [ | |
"#E84420" "#F4CD00" "#3E58E2" | |
"#999999" "#F1892A" "#22A722" "#7F3CAC" | |
"#F391C7" "#995F29" "#3DC1A2" "#D5B3E5" | |
]) | |
; set a random seed | |
(random/seed 128) | |
; set canvas style | |
(canvas/fill "#E9E3D5") | |
; padding for canvas | |
(var pad 16) | |
(var depth 8) | |
; run program on whole canvas | |
(var cells (bsp pad pad (- width pad) (- height pad) depth)) | |
; first draw with color fill | |
(each cells (fn (cell) (fill-cell cell (random colors)))) | |
; then with stroke | |
(each cells draw-cell) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment