1// The device rectangles a frame redraws: those changed since the last2// one, kept few as they come, then snapped to whole pixels and merged3// into at most a few that do not overlap, since a pixel drawn twice4// would blend twice.56import std::vector;7import std::option;8import std::math;9import pkg::alloy::gpu;10import pkg::alloy::window;1112import draw;1314const KEPT: u64 = 16; // rectangles kept as they come15pub const MAX_RECTS: u64 = 4; // a frame's1617pub fn add_damage(self canvas: &var Canvas, r: Rect) {18 if (r.is_empty()) {19 return;20 }21 canvas.pending = true;22 if (canvas.everything) {23 return;24 }25 // into the rectangle it grows least, once there are enough26 var best: f32 = 0.0;27 var into: Option<u64> = ::None;28 for (canvas.damage.view(), [..canvas.damage.length()]) |&d, k| {29 const growth = d.union(&r).area() - d.area();30 if (growth <= 0.0) {31 return;32 }33 if (into is ::None || growth < best) {34 best = growth;35 into = ::Some(k);36 }37 }38 if (canvas.damage.length() < KEPT) {39 canvas.damage.push(r);40 } else if (into is ::Some |k|) {41 const merged = canvas.damage.get(k).union(&r);42 canvas.damage.get_var(k) = merged;43 }44}4546// Merges the two rectangles whose union adds the least area.47fn merge_cheapest(rects: &var Vector<Rect>) {48 var best: f32 = 0.0;49 var pair: [u64 : 2] = [0, 1];50 var found = false;51 const r = &rects.view();52 for ([..r.length()]) |i| {53 for ([i + 1..r.length()]) |j| {54 const growth = r[i].union(&r[j]).area() - r[i].area() - r[j].area();55 if (!found || growth < best) {56 best = growth;57 pair = [i, j];58 found = true;59 }60 }61 }62 const merged = r[pair[0]].union(&r[pair[1]]);63 rects.get_var(pair[0]) = merged;64 rects.swap_remove(pair[1]);65}6667// The rectangles snapped out to whole pixels inside the target, merged68// until none overlap and at most MAX_RECTS remain.69pub fn merged(rects: &[Rect], size: Size) -> Vector<Rect> {70 const bounds = Rect::sized(size.width to f32, size.height to f32);71 var out = Vector<Rect>::empty();72 for (rects) |&r| {73 const inside = r.intersection(&bounds);74 if (inside.is_empty()) {75 continue;76 }77 const x0 = floor(inside.x);78 const y0 = floor(inside.y);79 out.push(Rect::at(x0, y0, ceil(inside.right()) - x0, ceil(inside.bottom()) - y0));80 }81 while (true) {82 if (merge_overlapping(&var out)) {83 continue;84 }85 if (out.length() <= MAX_RECTS) {86 break;87 }88 merge_cheapest(&var out);89 }90 return move out;91}9293fn merge_overlapping(rects: &var Vector<Rect>) -> bool {94 const r = &rects.view();95 for ([..r.length()]) |i| {96 for ([i + 1..r.length()]) |j| {97 if (r[i].intersects(&r[j])) {98 const merged = r[i].union(&r[j]);99 rects.get_var(i) = merged;100 rects.swap_remove(j);101 return true;102 }103 }104 }105 return false;106}