1use clairlune_render::PixelRect;
16
17pub const TILE_W: u32 = 32;
19pub const TILE_H: u32 = 16;
20
21#[derive(Clone, Debug)]
23pub struct DirtyGrid {
24 width: u32,
25 height: u32,
26 tile_cols: usize,
27 tile_rows: usize,
28 words_per_row: usize,
29 bits: Vec<u64>,
30 any: bool,
31}
32
33impl DirtyGrid {
34 pub fn new_full(width: u32, height: u32) -> Self {
37 let tile_cols = width.div_ceil(TILE_W) as usize;
38 let tile_rows = height.div_ceil(TILE_H) as usize;
39 let words_per_row = tile_cols.div_ceil(64);
40 let mut grid = Self {
41 width,
42 height,
43 tile_cols,
44 tile_rows,
45 words_per_row,
46 bits: vec![0u64; words_per_row * tile_rows],
47 any: false,
48 };
49 grid.mark_all();
50 grid
51 }
52
53 pub fn is_empty(&self) -> bool {
54 !self.any
55 }
56
57 pub fn clear(&mut self) {
58 if self.any {
59 self.bits.fill(0);
60 self.any = false;
61 }
62 }
63
64 pub fn mark_all(&mut self) {
66 if self.width == 0 || self.height == 0 {
67 return;
68 }
69 let tail_bits = self.tile_cols % 64;
70 let tail_mask = if tail_bits == 0 {
71 u64::MAX
72 } else {
73 (1u64 << tail_bits) - 1
74 };
75 for ty in 0..self.tile_rows {
76 let row = &mut self.bits[ty * self.words_per_row..(ty + 1) * self.words_per_row];
77 if let Some((last, rest)) = row.split_last_mut() {
78 rest.fill(u64::MAX);
79 *last = tail_mask;
80 }
81 }
82 self.any = true;
83 }
84
85 pub fn mark(&mut self, r: PixelRect) {
87 let x0 = r.x.min(self.width);
88 let y0 = r.y.min(self.height);
89 let x1 = r.x.saturating_add(r.w).min(self.width);
90 let y1 = r.y.saturating_add(r.h).min(self.height);
91 if x0 >= x1 || y0 >= y1 {
92 return;
93 }
94 let tx0 = (x0 / TILE_W) as usize;
95 let tx1 = x1.div_ceil(TILE_W) as usize;
96 let ty0 = (y0 / TILE_H) as usize;
97 let ty1 = y1.div_ceil(TILE_H) as usize;
98 let (w0, b0) = (tx0 / 64, tx0 % 64);
99 let (w1, b1) = ((tx1 - 1) / 64, (tx1 - 1) % 64);
100 let first_mask = u64::MAX << b0;
101 let last_mask = if b1 == 63 {
102 u64::MAX
103 } else {
104 (1u64 << (b1 + 1)) - 1
105 };
106 let wpr = self.words_per_row;
107 for ty in ty0..ty1 {
108 let row = &mut self.bits[ty * wpr..(ty + 1) * wpr];
109 if w0 == w1 {
110 row[w0] |= first_mask & last_mask;
111 } else {
112 row[w0] |= first_mask;
113 for word in &mut row[w0 + 1..w1] {
114 *word = u64::MAX;
115 }
116 row[w1] |= last_mask;
117 }
118 }
119 self.any = true;
120 }
121
122 pub fn mark_slice(&mut self, rects: &[PixelRect]) {
123 for &r in rects {
124 self.mark(r);
125 }
126 }
127
128 pub fn for_each_rect(&self, mut f: impl FnMut(PixelRect)) {
131 if !self.any {
132 return;
133 }
134 let wpr = self.words_per_row;
135 let mut ty = 0;
136 while ty < self.tile_rows {
137 let row = &self.bits[ty * wpr..(ty + 1) * wpr];
138 if row.iter().all(|&w| w == 0) {
139 ty += 1;
140 continue;
141 }
142 let mut ty_end = ty + 1;
143 while ty_end < self.tile_rows && self.bits[ty_end * wpr..(ty_end + 1) * wpr] == *row {
144 ty_end += 1;
145 }
146 let y0 = (ty as u32 * TILE_H).min(self.height);
147 let y1 = (ty_end as u32 * TILE_H).min(self.height);
148 let h = y1 - y0;
149 let mut tx = 0;
150 while tx < self.tile_cols {
151 let (wi, bi) = (tx / 64, tx % 64);
152 let shifted = row[wi] >> bi;
153 if shifted == 0 {
154 tx = (wi + 1) * 64;
155 continue;
156 }
157 tx += shifted.trailing_zeros() as usize;
158 if tx >= self.tile_cols {
159 break;
160 }
161 let start = tx;
162 loop {
163 let (w_idx, b_idx) = (tx / 64, tx % 64);
164 if w_idx >= wpr {
165 break;
166 }
167 let ones = (row[w_idx] >> b_idx).trailing_ones() as usize;
168 tx += ones;
169 if b_idx + ones < 64 || tx >= self.tile_cols {
170 break;
171 }
172 }
173 let end = tx.min(self.tile_cols);
174 let x0 = (start as u32 * TILE_W).min(self.width);
175 let x1 = (end as u32 * TILE_W).min(self.width);
176 if x1 > x0 && h > 0 {
177 f(PixelRect {
178 x: x0,
179 y: y0,
180 w: x1 - x0,
181 h,
182 });
183 }
184 }
185 ty = ty_end;
186 }
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::Player;
194 use clairlune_render::{ScenePackage, clock::Clock};
195 use clairlune_scene::{Aspect, ContentContext, compose};
196 use std::sync::Arc;
197
198 #[test]
199 fn scattered_weather_stays_sparse_instead_of_collapsing_to_the_whole_screen() {
200 let (w, h) = (3024, 1964);
201 let mut grid = DirtyGrid::new_full(w, h);
202 let mut init = Vec::new();
204 grid.for_each_rect(|r| init.push(r));
205 assert_eq!(init, [PixelRect { x: 0, y: 0, w, h }]);
206 grid.clear();
207 assert!(grid.is_empty());
208
209 for i in 0..240u32 {
212 let x = (i * 7919) % (w - 10);
213 let y = (i * 6151) % (h - 18);
214 grid.mark(PixelRect { x, y, w: 10, h: 18 });
215 }
216 grid.mark(PixelRect {
218 x: 0,
219 y: 0,
220 w: 8,
221 h: 8,
222 });
223 grid.mark(PixelRect {
224 x: w - 8,
225 y: h - 8,
226 w: 8,
227 h: 8,
228 });
229 let mut pixels = 0u64;
230 grid.for_each_rect(|r| {
231 assert!(r.x + r.w <= w && r.y + r.h <= h);
232 pixels += u64::from(r.w * r.h);
233 });
234 let whole = u64::from(w) * u64::from(h);
235 assert!(
236 pixels < whole / 15,
237 "expected sparse tiles (<7% of screen), got {pixels} of {whole}"
238 );
239 }
240
241 #[test]
242 fn double_buffered_dirty_grids_keep_both_surfaces_exact() {
243 let (w, h) = (320, 180);
244 let ctx = ContentContext {
245 enabled_weather: vec!["sandstorm".into()],
246 ..ContentContext::default()
247 };
248 let r = compose(19, Aspect::from_size(w, h), &ctx);
249 let pkg = Arc::new(ScenePackage::capture(&r, w, h).unwrap());
250 let theme = pkg.themes()[0];
251 let mut player = Player::new(pkg.clone(), theme, true).unwrap();
252 player.set_smooth(true);
253 let mut bufs = [vec![0u32; (w * h) as usize], vec![0u32; (w * h) as usize]];
254 let mut grids = [DirtyGrid::new_full(w, h), DirtyGrid::new_full(w, h)];
255 let t0 = pkg.hero_ms(theme).unwrap();
256
257 for step in 0..30u64 {
258 let t = t0 + step * 33;
259 let rects = player.advance(t);
260 for g in &mut grids {
261 g.mark_slice(&rects);
262 }
263 let cur = (step % 2) as usize;
264 let colors = *player.colors();
265 grids[cur].for_each_rect(|rect| {
266 for y in rect.y..rect.y + rect.h {
267 let off = (y * w + rect.x) as usize;
268 for (dst, &idx) in bufs[cur][off..off + rect.w as usize]
269 .iter_mut()
270 .zip(player.index_row(rect.x, y, rect.w))
271 {
272 *dst = colors[usize::from(idx)];
273 }
274 }
275 });
276 grids[cur].clear();
277
278 let (expected, palette) = pkg.frame(theme, true, t, Clock::Smooth).unwrap();
279 let pal: Vec<u32> = palette
280 .colors()
281 .iter()
282 .map(|c| (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b))
283 .collect();
284 let want: Vec<u32> = expected
285 .pixels
286 .iter()
287 .map(|&i| pal[usize::from(i)])
288 .collect();
289 assert_eq!(bufs[cur], want, "frame {step} at {t}");
290 }
291 }
292}