From 081809d4cd8600a77607d2949ff8f16f8d633e77 Mon Sep 17 00:00:00 2001 From: heyarne Date: Thu, 30 Dec 2021 16:55:14 +0100 Subject: [PATCH] Implement naive rect packing :) --- src/heyarne/rect_packing/core.cljs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/heyarne/rect_packing/core.cljs b/src/heyarne/rect_packing/core.cljs index a9fe044..13d3342 100644 --- a/src/heyarne/rect_packing/core.cljs +++ b/src/heyarne/rect_packing/core.cljs @@ -24,13 +24,27 @@ 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))) + (-> (reduce (fn [acc rect] + ;; a word on "top" vs "bottom": the thi.ng coordinate system + ;; works like the ones you know from scool, i.e. [0 1] is + ;; above [0 0]. the svg coordinate system uses screen + ;; coordinates, where [0 0] is at the top left. if you see + ;; rect/bottom we're actually looking at the top edge that is + ;; drawn in the svg. + (let [last-placed (or (last (:result acc)) (rect/rect 0 0)) + moved-right (geom/translate rect [(rect/right last-placed) (rect/bottom (:row-start acc))])] + ;; do we still have enough space to the right? + (if (<= (rect/right moved-right) (rect/right frame)) + ;; if yes, everything is bon + (update acc :result conj moved-right) + ;; if no, move to the bottom + (let [moved-bottom (geom/translate rect [0 (rect/top (:row-start acc))])] + (-> (assoc acc :row-start moved-bottom) + (update :result conj moved-bottom)))))) + {:row-start (first rects) + :result []} + rects) + :result))) #_(pack-rects-naive (:frame @state) (:rects @state))