Add SVG visualization and stub out packing algorithm

This commit is contained in:
heyarne 2021-12-30 16:34:31 +01:00
commit 5e524664e2
2 changed files with 65 additions and 4 deletions

View file

@ -1,14 +1,60 @@
(ns heyarne.rect-packing.core
(:require [reagent.core :as r]
[reagent.dom :as dom]))
[reagent.dom :as dom]
[thi.ng.geom.core :as geom]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.vector :as v]))
(defonce state (r/atom {:rects []
:frame (rect/rect 500 500)}))
(comment
(swap! state update :rects empty)
(swap! state update :rects conj (rect/rect 200 200))
;; fill with random rectangles
(swap! state assoc :rects
(repeatedly 20 #(rect/rect (+ 50 (rand-int 50)) (+ 50 (rand-int 50)))))
)
(defn pack-rects-naive
"Sorts all rectangles by height and places them next to each other into frame,
starting at the top left."
[frame rects]
(let [rects (sort-by (comp - geom/height) rects)]
(reduce (fn [result rect]
(let [last-placed (last result)]
(conj result (geom/translate rect [(if last-placed
(rect/right last-placed)
0)
0]))))
[] rects)))
#_(pack-rects-naive (:frame @state) (:rects @state))
(defn main []
[:main
[:h1 "Hello world"]
[:p "This is a starting point"]])
(let [{:keys [frame rects]} @state
sorted (pack-rects-naive frame rects)]
[:main
[:h1 "Visualization"]
[:svg {:viewBox "-1 -1 501 501" :xmlns "http://www.w3.org/2000/svg"}
[:rect {:width (geom/width frame)
:height (geom/height frame)}]
(for [rect sorted]
[:rect {:width (geom/width rect) :height (geom/height rect)
:x (-> rect :p :x)
:y (-> rect :p :y)}])]
[:h2 "Rectangles"]
[:ul
(for [rect sorted]
[:li [:pre (pr-str rect)]])]]))
(defn ^:dev/after-load init []
(println "Initializing…")
(dom/render [main] (.querySelector js/document "#app")))
(defonce app (init))
(+ 1 2)