Skip to main content

euv_core/render/buffer/
impl.rs

1use super::*;
2
3/// Pixel access, blitting, BGRA conversion, and deterministic hashing for `Framebuffer`.
4impl Framebuffer {
5    /// Allocates a new zero-initialized RGBA8 framebuffer of `(width, height)`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u32` - Physical width in pixels.
10    /// - `u32` - Physical height in pixels.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Allocated framebuffer.
15    #[must_use]
16    pub fn allocate(width: u32, height: u32) -> Self {
17        let width_val: u32 = width.max(1);
18        let height_val: u32 = height.max(1);
19        let byte_len: usize = (width_val as usize)
20            .saturating_mul(height_val as usize)
21            .saturating_mul(4);
22        Self {
23            width: width_val,
24            height: height_val,
25            pixels: vec![0; byte_len],
26        }
27    }
28
29    /// Returns the number of allocated RGBA8 pixel bytes currently resident in this framebuffer.
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Framebuffer reference.
34    ///
35    /// # Returns
36    ///
37    /// - `usize` - Resident RGBA8 pixel byte count (`0` when unallocated).
38    #[must_use]
39    pub fn allocated_bytes(&self) -> usize {
40        self.get_pixels().len()
41    }
42
43    /// Resizes the framebuffer only when dimensions changed, avoiding per-frame reallocation.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Mutable framebuffer.
48    /// - `u32` - Target width.
49    /// - `u32` - Target height.
50    ///
51    /// # Returns
52    ///
53    /// - `bool` - True if dimensions changed and buffer was resized.
54    pub fn resize(&mut self, width: u32, height: u32) -> bool {
55        let width_val: u32 = width.max(1);
56        let height_val: u32 = height.max(1);
57        if self.get_width() == width_val && self.get_height() == height_val {
58            return false;
59        }
60        self.set_width(width_val);
61        self.set_height(height_val);
62        let byte_len: usize = (width_val as usize)
63            .saturating_mul(height_val as usize)
64            .saturating_mul(4);
65        self.get_mut_pixels().resize(byte_len, 0);
66        true
67    }
68
69    /// Fills the entire framebuffer with solid `color` using 32-byte wide auto-vectorized stores.
70    ///
71    /// # Arguments
72    ///
73    /// - `&Self` - Mutable framebuffer.
74    /// - `Color` - Clear color.
75    pub fn clear(&mut self, color: Color) {
76        fill_rgba_span_32(self.get_mut_pixels().as_mut_slice(), color.to_rgba_bytes());
77    }
78
79    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y`.
80    ///
81    /// # Arguments
82    ///
83    /// - `&Self` - Mutable framebuffer.
84    /// - `u32` - Inclusive start X pixel coordinate.
85    /// - `u32` - Exclusive end X pixel coordinate.
86    /// - `u32` - Row Y pixel coordinate.
87    /// - `Color` - Foreground color to write or alpha-blend.
88    pub fn fill_span(&mut self, x0: u32, x1: u32, pos_y: u32, color: Color) {
89        let sa: u8 = color.get_alpha();
90        let width: u32 = self.get_width();
91        let height: u32 = self.get_height();
92        if sa == 0 || pos_y >= height || x0 >= x1 || x0 >= width {
93            return;
94        }
95        let end_x: u32 = x1.min(width);
96        let row_base: usize = (pos_y as usize) * (width as usize);
97        let start_byte: usize = (row_base + (x0 as usize)) * 4;
98        let end_byte: usize = (row_base + (end_x as usize)) * 4;
99        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
100            return;
101        };
102        if sa == 255 {
103            fill_rgba_span_32(
104                span,
105                [color.get_red(), color.get_green(), color.get_blue(), 255],
106            );
107            return;
108        }
109        let sr: u32 = color.get_red() as u32;
110        let sg: u32 = color.get_green() as u32;
111        let sb: u32 = color.get_blue() as u32;
112        let sa_u32: u32 = sa as u32;
113        let inv_a: u32 = 255 - sa_u32;
114        for px in span.as_chunks_mut::<4>().0.iter_mut() {
115            let dr: u32 = px[0] as u32;
116            let dg: u32 = px[1] as u32;
117            let db: u32 = px[2] as u32;
118            let da: u32 = px[3] as u32;
119            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
120            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
121            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
122            let va: u32 = da * inv_a + 128;
123            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
124            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
125            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
126            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
127        }
128    }
129
130    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y` using gamma-correct linear-light blending.
131    ///
132    /// # Arguments
133    ///
134    /// - `&Self` - Mutable framebuffer.
135    /// - `u32` - Inclusive start X pixel coordinate.
136    /// - `u32` - Exclusive end X pixel coordinate.
137    /// - `u32` - Row Y pixel coordinate.
138    /// - `Color` - Foreground color to write or linear-light blend.
139    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, pos_y: u32, color: Color) {
140        let sa: u8 = color.get_alpha();
141        let width: u32 = self.get_width();
142        let height: u32 = self.get_height();
143        if sa == 0 || pos_y >= height || x0 >= x1 || x0 >= width {
144            return;
145        }
146        if sa == 255 {
147            self.fill_span(x0, x1, pos_y, color);
148            return;
149        }
150        let end_x: u32 = x1.min(width);
151        let row_base: usize = (pos_y as usize) * (width as usize);
152        let start_byte: usize = (row_base + (x0 as usize)) * 4;
153        let end_byte: usize = (row_base + (end_x as usize)) * 4;
154        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
155            return;
156        };
157        let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
158        let inv_a: f32 = 1.0 - alpha_val;
159        let sr_a: f32 = SRGB_TO_LIN_LUT[color.get_red() as usize] * alpha_val;
160        let sg_a: f32 = SRGB_TO_LIN_LUT[color.get_green() as usize] * alpha_val;
161        let sb_a: f32 = SRGB_TO_LIN_LUT[color.get_blue() as usize] * alpha_val;
162        let sa_u32: u32 = sa as u32;
163        let inv_a_u32: u32 = 255 - sa_u32;
164        for px in span.as_chunks_mut::<4>().0.iter_mut() {
165            let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
166            let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
167            let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
168            let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
169            let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
170            let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
171            let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
172            px[0] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
173            px[1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
174            px[2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
175            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
176        }
177    }
178
179    /// Blends a contiguous glyph alpha coverage row directly onto framebuffer row `dy` starting at `dx`.
180    ///
181    /// # Arguments
182    ///
183    /// - `&Self` - Mutable framebuffer.
184    /// - `u32` - Destination starting X pixel coordinate.
185    /// - `u32` - Destination Y pixel coordinate.
186    /// - `&[u8]` - Glyph coverage alpha bytes for the clipped horizontal slice.
187    /// - `Color` - Foreground text color.
188    ///
189    /// # Returns
190    ///
191    /// - `usize` - Number of non-zero coverage pixels shaded.
192    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
193        let width: u32 = self.get_width();
194        let height: u32 = self.get_height();
195        if color.get_alpha() == 0 || dy >= height || dx >= width || coverage.is_empty() {
196            return 0;
197        }
198        let max_len: usize = ((width - dx) as usize).min(coverage.len());
199        let start_byte: usize = ((dy as usize) * (width as usize) + (dx as usize)) * 4;
200        let end_byte: usize = start_byte + max_len * 4;
201        let Some(dst_span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
202            return 0;
203        };
204        blend_glyph_row_span(dst_span, &coverage[..max_len], color)
205    }
206
207    /// Reads the RGBA `Color` at pixel coordinates `(x, y)`.
208    ///
209    /// # Arguments
210    ///
211    /// - `&Self` - Framebuffer reference.
212    /// - `u32` - X pixel coordinate.
213    /// - `u32` - Y pixel coordinate.
214    ///
215    /// # Returns
216    ///
217    /// - `Option<Color>` - Pixel color if within bounds.
218    #[must_use]
219    pub fn get_pixel(&self, pos_x: u32, pos_y: u32) -> Option<Color> {
220        if pos_x >= self.get_width() || pos_y >= self.get_height() {
221            return None;
222        }
223        let offset: usize = ((pos_y as usize) * (self.get_width() as usize) + (pos_x as usize)) * 4;
224        let slice: &[u8] = self.get_pixels().get(offset..offset + 4)?;
225        Some(Color::new(slice[0], slice[1], slice[2], slice[3]))
226    }
227
228    /// Blends `color` over the pixel at `(x, y)` using gamma-correct linear-light compositing with optional sub-LSB dithering.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Mutable framebuffer.
233    /// - `u32` - X pixel coordinate.
234    /// - `u32` - Y pixel coordinate.
235    /// - `Color` - Foreground color to composite.
236    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]` to eliminate 8-bit banding.
237    pub fn blend_pixel_linear_dithered(
238        &mut self,
239        pos_x: u32,
240        pos_y: u32,
241        color: Color,
242        dither: f32,
243    ) {
244        let sa: u8 = color.get_alpha();
245        if sa == 0 || pos_x >= self.get_width() || pos_y >= self.get_height() {
246            return;
247        }
248        let offset: usize = ((pos_y as usize) * (self.get_width() as usize) + (pos_x as usize)) * 4;
249        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
250        if offset + 4 > pixels.len() {
251            return;
252        }
253        if sa == 255 {
254            pixels[offset] = color.get_red();
255            pixels[offset + 1] = color.get_green();
256            pixels[offset + 2] = color.get_blue();
257            pixels[offset + 3] = 255;
258            return;
259        }
260        let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
261        let inv_a: f32 = 1.0 - alpha_val;
262        let sr: f32 = SRGB_TO_LIN_LUT[color.get_red() as usize];
263        let sg: f32 = SRGB_TO_LIN_LUT[color.get_green() as usize];
264        let sb: f32 = SRGB_TO_LIN_LUT[color.get_blue() as usize];
265        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
266        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
267        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
268        let ir: usize = ((sr * alpha_val + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
269        let ig: usize = ((sg * alpha_val + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
270        let ib: usize = ((sb * alpha_val + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
271        let dq: i32 = (dither * 16.0) as i32 + 8;
272        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
273        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
274        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
275        let sa_u32: u32 = sa as u32;
276        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
277        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
278    }
279
280    /// Blends a foreground RGBA color with continuous floating-point alpha `alpha_f` in `[0.0, 1.0]` using linear-light compositing and IGN dithering.
281    ///
282    /// # Arguments
283    ///
284    /// - `&Self` - Mutable framebuffer.
285    /// - `u32` - X pixel coordinate.
286    /// - `u32` - Y pixel coordinate.
287    /// - `Color` - Foreground RGB tint (its own alpha is already folded into `alpha_f`).
288    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
289    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
290    pub fn blend_pixel_f32_dithered(
291        &mut self,
292        pos_x: u32,
293        pos_y: u32,
294        color: Color,
295        alpha_f: f32,
296        dither: f32,
297    ) {
298        if alpha_f <= 0.0002 || pos_x >= self.get_width() || pos_y >= self.get_height() {
299            return;
300        }
301        let offset: usize = ((pos_y as usize) * (self.get_width() as usize) + (pos_x as usize)) * 4;
302        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
303        if offset + 4 > pixels.len() {
304            return;
305        }
306        let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
307        if alpha_val >= 0.9995 {
308            pixels[offset] = color.get_red();
309            pixels[offset + 1] = color.get_green();
310            pixels[offset + 2] = color.get_blue();
311            pixels[offset + 3] = 255;
312            return;
313        }
314        let inv_a: f32 = 1.0 - alpha_val;
315        let sr: f32 = SRGB_TO_LIN_LUT[color.get_red() as usize];
316        let sg: f32 = SRGB_TO_LIN_LUT[color.get_green() as usize];
317        let sb: f32 = SRGB_TO_LIN_LUT[color.get_blue() as usize];
318        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
319        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
320        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
321        let ir: usize = ((sr * alpha_val + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
322        let ig: usize = ((sg * alpha_val + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
323        let ib: usize = ((sb * alpha_val + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
324        let dq: i32 = (dither * 16.0) as i32 + 8;
325        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
326        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
327        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
328        let sa_u32: u32 = (alpha_val * 255.0) as u32;
329        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
330        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
331    }
332
333    /// Blends `color` over the pixel at `(x, y)` using fast integer Porter-Duff source-over.
334    ///
335    /// # Arguments
336    ///
337    /// - `&Self` - Mutable framebuffer.
338    /// - `u32` - X pixel coordinate.
339    /// - `u32` - Y pixel coordinate.
340    /// - `Color` - Foreground color to composite.
341    pub fn blend_pixel(&mut self, pos_x: u32, pos_y: u32, color: Color) {
342        let sa: u8 = color.get_alpha();
343        if sa == 0 || pos_x >= self.get_width() || pos_y >= self.get_height() {
344            return;
345        }
346        let offset: usize = ((pos_y as usize) * (self.get_width() as usize) + (pos_x as usize)) * 4;
347        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
348        if offset + 4 > pixels.len() {
349            return;
350        }
351        if sa == 255 {
352            pixels[offset] = color.get_red();
353            pixels[offset + 1] = color.get_green();
354            pixels[offset + 2] = color.get_blue();
355            pixels[offset + 3] = 255;
356            return;
357        }
358        let dst: Color = Color::new(
359            pixels[offset],
360            pixels[offset + 1],
361            pixels[offset + 2],
362            pixels[offset + 3],
363        );
364        let blended: Color = color.blend_over(dst);
365        pixels[offset] = blended.get_red();
366        pixels[offset + 1] = blended.get_green();
367        pixels[offset + 2] = blended.get_blue();
368        pixels[offset + 3] = blended.get_alpha();
369    }
370
371    /// Converts RGBA8 pixels into BGRA8 byte order required by Win32 GDI, X11, and Cocoa/Metal.
372    ///
373    /// # Arguments
374    ///
375    /// - `&Self` - Source RGBA8 framebuffer.
376    ///
377    /// # Returns
378    ///
379    /// - `Vec<u8>` - Packed BGRA8 pixel buffer.
380    #[must_use]
381    pub fn to_bgra_bytes(&self) -> Vec<u8> {
382        let src: &[u8] = self.get_pixels().as_slice();
383        let len: usize = src.len() & !3usize;
384        let mut out: Vec<u8> = vec![0u8; len];
385        let (src_wide, src_tail): (&[[u8; 16]], &[u8]) = src[..len].as_chunks::<16>();
386        let (dst_wide, dst_tail): (&mut [[u8; 16]], &mut [u8]) = out.as_chunks_mut::<16>();
387        for (source_val, delta_val) in src_wide.iter().zip(dst_wide.iter_mut()) {
388            *delta_val = [
389                source_val[2],
390                source_val[1],
391                source_val[0],
392                source_val[3],
393                source_val[6],
394                source_val[5],
395                source_val[4],
396                source_val[7],
397                source_val[10],
398                source_val[9],
399                source_val[8],
400                source_val[11],
401                source_val[14],
402                source_val[13],
403                source_val[12],
404                source_val[15],
405            ];
406        }
407        for (scale_val, distance_val) in src_tail
408            .as_chunks::<4>()
409            .0
410            .iter()
411            .zip(dst_tail.as_chunks_mut::<4>().0.iter_mut())
412        {
413            *distance_val = [scale_val[2], scale_val[1], scale_val[0], scale_val[3]];
414        }
415        out
416    }
417
418    /// Computes a deterministic 64-bit 4-lane word-folded FNV-1a hash of one `128x16` pixel tile `(tx, ty)`.
419    ///
420    /// # Arguments
421    ///
422    /// - `&Self` - Framebuffer reference.
423    /// - `u32` - Tile column index (`0..width.div_ceil(128)`).
424    /// - `u32` - Tile row index (`0..height.div_ceil(16)`).
425    ///
426    /// # Returns
427    ///
428    /// - `u64` - Deterministic endian-independent hash for tile `(tx, ty)`.
429    #[must_use]
430    pub(crate) fn hash_tile_fnv1a(&self, tx: u32, ty: u32) -> u64 {
431        let width_val: u32 = self.get_width();
432        let height_val: u32 = self.get_height();
433        let x0: usize = (tx.saturating_mul(FB_HASH_TILE_W) as usize).min(width_val as usize);
434        let x1: usize = (x0.saturating_add(FB_HASH_TILE_W as usize)).min(width_val as usize);
435        let y0: usize = (ty.saturating_mul(FB_HASH_TILE_H) as usize).min(height_val as usize);
436        let y1: usize = (y0.saturating_add(FB_HASH_TILE_H as usize)).min(height_val as usize);
437        let bytes: &[u8] = self.get_pixels().as_slice();
438        let row_stride: usize = (width_val as usize).saturating_mul(4);
439        let mut lanes: [u64; 8] = [
440            FNV1A_OFFSET_BASIS,
441            FNV1A_OFFSET_BASIS ^ 0x9E37_79B9_7F4A_7C15,
442            FNV1A_OFFSET_BASIS ^ 0xBF58_476D_1CE4_E5B9,
443            FNV1A_OFFSET_BASIS ^ 0x94D0_49BB_1331_11EB,
444            FNV1A_OFFSET_BASIS ^ 0xD6E8_FEB8_6659_FD93,
445            FNV1A_OFFSET_BASIS ^ 0xA076_1D64_78BD_642F,
446            FNV1A_OFFSET_BASIS ^ 0xE703_7ED1_A0B4_28DB,
447            FNV1A_OFFSET_BASIS ^ 0x8EBC_6AF0_9C88_C6E3,
448        ];
449        let mut tail_hash: u64 = FNV1A_OFFSET_BASIS;
450        let x0_b: usize = x0.saturating_mul(4);
451        let x1_b: usize = x1.saturating_mul(4);
452        for pos_y in y0..y1 {
453            let base: usize = pos_y.saturating_mul(row_stride);
454            let start: usize = base.saturating_add(x0_b);
455            let end: usize = base.saturating_add(x1_b);
456            if end > bytes.len() {
457                break;
458            }
459            let row_slice: &[u8] = &bytes[start..end];
460            let (blocks64, rem): (&[[u8; 64]], &[u8]) = row_slice.as_chunks::<64>();
461            for blk in blocks64.iter() {
462                fold_fnv1a_64(&mut lanes, blk);
463            }
464            if !rem.is_empty() {
465                let (words8, tail): (&[[u8; 8]], &[u8]) = rem.as_chunks::<8>();
466                for word in words8.iter() {
467                    tail_hash = (tail_hash ^ u64::from_le_bytes(*word)).wrapping_mul(FNV1A_PRIME);
468                }
469                for byte in tail.iter().copied() {
470                    tail_hash = (tail_hash ^ (byte as u64)).wrapping_mul(FNV1A_PRIME);
471                }
472            }
473        }
474        let lo: u64 = lanes[0]
475            ^ lanes[1].rotate_left(13)
476            ^ lanes[2].rotate_left(29)
477            ^ lanes[3].rotate_left(47);
478        let hi: u64 = lanes[4]
479            ^ lanes[5].rotate_left(17)
480            ^ lanes[6].rotate_left(31)
481            ^ lanes[7].rotate_left(53);
482        let mut hash: u64 = lo ^ hi.rotate_left(7) ^ tail_hash.rotate_left(11);
483        hash = hash.wrapping_mul(FNV1A_PRIME);
484        hash
485    }
486
487    /// Combines per-tile hashes in canonical row-major order into the exact framebuffer digest.
488    ///
489    /// # Arguments
490    ///
491    /// - `u32` - Framebuffer width in pixels.
492    /// - `u32` - Framebuffer height in pixels.
493    /// - `&[u64]` - Row-major slice of `128x16` tile hashes.
494    ///
495    /// # Returns
496    ///
497    /// - `u64` - Deterministic framebuffer hash identical to `Framebuffer::fnv1a_hash`.
498    #[inline]
499    #[must_use]
500    pub(crate) fn fold_tile_hashes(width: u32, height: u32, tile_hashes: &[u64]) -> u64 {
501        let mut acc: u64 = FNV1A_OFFSET_BASIS;
502        acc = (acc ^ (width as u64)).wrapping_mul(FNV1A_PRIME);
503        acc = (acc ^ (height as u64)).wrapping_mul(FNV1A_PRIME);
504        for &tile_h in tile_hashes.iter() {
505            acc = (acc ^ tile_h).wrapping_mul(FNV1A_PRIME);
506        }
507        acc
508    }
509
510    /// Computes a deterministic 64-bit tile-folded FNV-1a hash of the framebuffer pixels.
511    ///
512    /// # Arguments
513    ///
514    /// - `&Self` - Framebuffer to hash.
515    ///
516    /// # Returns
517    ///
518    /// - `u64` - Deterministic endian-independent pixel hash.
519    #[must_use]
520    pub fn fnv1a_hash(&self) -> u64 {
521        let width_val: u32 = self.get_width();
522        let height_val: u32 = self.get_height();
523        let mut acc: u64 = FNV1A_OFFSET_BASIS;
524        acc = (acc ^ (width_val as u64)).wrapping_mul(FNV1A_PRIME);
525        acc = (acc ^ (height_val as u64)).wrapping_mul(FNV1A_PRIME);
526        if width_val == 0 || height_val == 0 || self.get_pixels().is_empty() {
527            return acc;
528        }
529        let tiles_x: u32 = width_val.div_ceil(FB_HASH_TILE_W);
530        let tiles_y: u32 = height_val.div_ceil(FB_HASH_TILE_H);
531        for ty in 0..tiles_y {
532            for tx in 0..tiles_x {
533                let tile_h: u64 = self.hash_tile_fnv1a(tx, ty);
534                acc = (acc ^ tile_h).wrapping_mul(FNV1A_PRIME);
535            }
536        }
537        acc
538    }
539
540    /// Borrows the entire framebuffer as a single zero-copy mutable `PixelBand`.
541    ///
542    /// # Arguments
543    ///
544    /// - `&Self` - Mutable framebuffer.
545    ///
546    /// # Returns
547    ///
548    /// - `PixelBand<'_>` - Full-surface mutable pixel band.
549    pub fn as_band_mut(&mut self) -> PixelBand<'_> {
550        let Self {
551            width,
552            height,
553            pixels,
554        } = self;
555        PixelBand {
556            width: *width,
557            y_offset: 0,
558            height: *height,
559            pixels: pixels.as_mut_slice(),
560        }
561    }
562
563    /// Splits rows `[y0, y1)` of this framebuffer into `band_count` disjoint mutable `PixelBand` slices for safe parallel rasterization.
564    ///
565    /// # Arguments
566    ///
567    /// - `&Self` - Mutable framebuffer.
568    /// - `u32` - Inclusive starting physical Y row.
569    /// - `u32` - Exclusive ending physical Y row.
570    /// - `usize` - Requested number of parallel bands.
571    ///
572    /// # Returns
573    ///
574    /// - `Vec<PixelBand<'_>>` - Non-overlapping mutable horizontal bands covering `[y0, y1)`.
575    pub fn split_bands_mut(&mut self, y0: u32, y1: u32, band_count: usize) -> Vec<PixelBand<'_>> {
576        let Self {
577            width,
578            height,
579            pixels,
580        } = self;
581        let fb_w: u32 = *width;
582        let fb_h: u32 = *height;
583        let start_y: u32 = y0.min(fb_h);
584        let end_y: u32 = y1.clamp(start_y, fb_h);
585        let total_rows: u32 = end_y - start_y;
586        if total_rows == 0 || fb_w == 0 {
587            return Vec::new();
588        }
589        let count: usize = band_count.max(1).min(total_rows as usize);
590        let rows_per: usize = (total_rows as usize).div_ceil(count);
591        let row_stride: usize = (fb_w as usize) * 4;
592        let start_byte: usize = (start_y as usize) * row_stride;
593        let end_byte: usize = (end_y as usize) * row_stride;
594        let Some(slice) = pixels.get_mut(start_byte..end_byte) else {
595            return Vec::new();
596        };
597        let mut bands: Vec<PixelBand<'_>> = Vec::with_capacity(count);
598        let mut cur_y: u32 = start_y;
599        for chunk in slice.chunks_mut(rows_per * row_stride) {
600            let chunk_rows: u32 = (chunk.len() / row_stride) as u32;
601            bands.push(PixelBand {
602                width: fb_w,
603                y_offset: cur_y,
604                height: chunk_rows,
605                pixels: chunk,
606            });
607            cur_y += chunk_rows;
608        }
609        bands
610    }
611}
612
613/// Zero-copy band rasterization primitives for `PixelBand`.
614impl<'a> PixelBand<'a> {
615    /// Returns the full framebuffer width in physical pixels.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - Pixel band reference.
620    ///
621    /// # Returns
622    ///
623    /// - `u32` - Width in physical pixels.
624    #[must_use]
625    pub fn width(&self) -> u32 {
626        let Self { width, .. } = self;
627        *width
628    }
629
630    /// Returns the inclusive top physical Y row owned by this band.
631    ///
632    /// # Arguments
633    ///
634    /// - `&Self` - Pixel band reference.
635    ///
636    /// # Returns
637    ///
638    /// - `u32` - Starting physical Y row.
639    #[must_use]
640    pub fn y_offset(&self) -> u32 {
641        let Self { y_offset, .. } = self;
642        *y_offset
643    }
644
645    /// Returns the exclusive bottom physical Y row owned by this band.
646    ///
647    /// # Arguments
648    ///
649    /// - `&Self` - Pixel band reference.
650    ///
651    /// # Returns
652    ///
653    /// - `u32` - Ending physical Y row.
654    #[must_use]
655    pub fn y_end(&self) -> u32 {
656        let Self {
657            y_offset, height, ..
658        } = self;
659        *y_offset + *height
660    }
661
662    /// Returns the mutable byte slice for global physical row `y` if owned by this band.
663    ///
664    /// # Arguments
665    ///
666    /// - `&Self` - Mutable pixel band.
667    /// - `u32` - Global physical Y row coordinate.
668    ///
669    /// # Returns
670    ///
671    /// - `Option<&mut [u8]>` - Mutable row byte slice (`width * 4` bytes).
672    pub fn row_slice_mut(&mut self, pos_y: u32) -> Option<&mut [u8]> {
673        let Self {
674            width,
675            y_offset,
676            height,
677            pixels,
678        } = self;
679        if pos_y < *y_offset || pos_y >= *y_offset + *height {
680            return None;
681        }
682        let local_y: usize = (pos_y - *y_offset) as usize;
683        let stride: usize = (*width as usize) * 4;
684        let start: usize = local_y * stride;
685        pixels.get_mut(start..start + stride)
686    }
687
688    /// Returns two disjoint mutable row slices for global physical rows `y_a < y_b` owned by this band.
689    ///
690    /// # Arguments
691    ///
692    /// - `&Self` - Mutable pixel band.
693    /// - `u32` - Upper global physical Y row coordinate (`y_a < y_b`).
694    /// - `u32` - Lower global physical Y row coordinate (`y_b > y_a`).
695    ///
696    /// # Returns
697    ///
698    /// - `Option<(&mut [u8], &mut [u8])>` - Pair of disjoint mutable row slices `(row_a, row_b)`.
699    pub fn two_row_slices_mut(&mut self, y_a: u32, y_b: u32) -> Option<(&mut [u8], &mut [u8])> {
700        let Self {
701            width,
702            y_offset,
703            height,
704            pixels,
705        } = self;
706        let y_end: u32 = *y_offset + *height;
707        if y_a >= y_b || y_a < *y_offset || y_b >= y_end {
708            return None;
709        }
710        let stride: usize = (*width as usize) * 4;
711        let start_a: usize = ((y_a - *y_offset) as usize) * stride;
712        let start_b: usize = ((y_b - *y_offset) as usize) * stride;
713        if start_b + stride > pixels.len() {
714            return None;
715        }
716        let (head, tail): (&mut [u8], &mut [u8]) = pixels.split_at_mut(start_b);
717        Some((&mut head[start_a..start_a + stride], &mut tail[..stride]))
718    }
719
720    /// Returns a contiguous mutable byte slice for global physical rows `[y0, y1)` along with the row byte stride.
721    ///
722    /// # Arguments
723    ///
724    /// - `&Self` - Mutable pixel band.
725    /// - `u32` - Inclusive starting global physical Y row.
726    /// - `u32` - Exclusive ending global physical Y row.
727    ///
728    /// # Returns
729    ///
730    /// - `Option<(&mut [u8], usize)>` - Contiguous byte slice covering rows `[y0, y1)` and byte stride `width * 4`.
731    #[inline(always)]
732    pub(crate) fn rows_slice_mut(&mut self, y0: u32, y1: u32) -> Option<(&mut [u8], usize)> {
733        let Self {
734            width,
735            y_offset,
736            height,
737            pixels,
738        } = self;
739        let y_end: u32 = *y_offset + *height;
740        if y0 >= y1 || y0 < *y_offset || y1 > y_end {
741            return None;
742        }
743        let stride: usize = (*width as usize) * 4;
744        let start: usize = ((y0 - *y_offset) as usize) * stride;
745        let end: usize = ((y1 - *y_offset) as usize) * stride;
746        pixels
747            .get_mut(start..end)
748            .map(|source_val: &mut [u8]| (source_val, stride))
749    }
750
751    /// Fills a pre-clipped opaque rectangle `[x0, x1) x [y0, y1)` using 32-byte wide stores with zero per-row bounds checks.
752    ///
753    /// # Arguments
754    ///
755    /// - `&Self` - Mutable pixel band.
756    /// - `u32` - Pre-clipped inclusive start X coordinate.
757    /// - `u32` - Pre-clipped exclusive end X coordinate.
758    /// - `u32` - Pre-clipped inclusive start global Y coordinate.
759    /// - `u32` - Pre-clipped exclusive end global Y coordinate.
760    /// - `[u8; 4]` - Solid opaque RGBA8 pixel bytes.
761    #[inline(always)]
762    pub(crate) fn fill_rect_opaque_preclipped(
763        &mut self,
764        x0: u32,
765        x1: u32,
766        y0: u32,
767        y1: u32,
768        rgba: [u8; 4],
769    ) {
770        let Self {
771            width,
772            y_offset,
773            height,
774            pixels,
775        } = self;
776        let fb_w: u32 = *width;
777        let y_end: u32 = *y_offset + *height;
778        let valid_x: bool = x0 < x1 && x1 <= fb_w;
779        let valid_y: bool = y0 < y1 && y0 >= *y_offset && y1 <= y_end;
780        if !valid_x || !valid_y {
781            return;
782        }
783        let stride: usize = (fb_w as usize) * 4;
784        let start: usize = ((y0 - *y_offset) as usize) * stride;
785        let end: usize = ((y1 - *y_offset) as usize) * stride;
786        let Some(rows_buf) = pixels.get_mut(start..end) else {
787            return;
788        };
789        if x0 == 0 && x1 == fb_w {
790            fill_rgba_span_32(rows_buf, rgba);
791            return;
792        }
793        let bx0: usize = (x0 as usize) * 4;
794        let bx1: usize = (x1 as usize) * 4;
795        for row in rows_buf.chunks_exact_mut(stride) {
796            fill_rgba_span_32(&mut row[bx0..bx1], rgba);
797        }
798    }
799
800    /// Fills the entire band with solid `color` using 32-byte wide auto-vectorized stores.
801    ///
802    /// # Arguments
803    ///
804    /// - `&Self` - Mutable pixel band.
805    /// - `Color` - Clear color.
806    pub fn clear(&mut self, color: Color) {
807        let Self { pixels, .. } = self;
808        fill_rgba_span_32(pixels, color.to_rgba_bytes());
809    }
810
811    /// Fills or Porter-Duff blends horizontal span `[x0, x1)` on global row `y`.
812    ///
813    /// # Arguments
814    ///
815    /// - `&Self` - Mutable pixel band.
816    /// - `u32` - Inclusive start X coordinate.
817    /// - `u32` - Exclusive end X coordinate.
818    /// - `u32` - Global physical Y coordinate.
819    /// - `Color` - Foreground RGBA color.
820    pub fn fill_span(&mut self, x0: u32, x1: u32, pos_y: u32, color: Color) {
821        let sa: u8 = color.get_alpha();
822        let Self {
823            width,
824            y_offset,
825            height,
826            pixels,
827        } = self;
828        if sa == 0 || pos_y < *y_offset || pos_y >= *y_offset + *height || x0 >= x1 || x0 >= *width
829        {
830            return;
831        }
832        let end_x: u32 = x1.min(*width);
833        let row_base: usize = ((pos_y - *y_offset) as usize) * (*width as usize);
834        let start_byte: usize = (row_base + (x0 as usize)) * 4;
835        let end_byte: usize = (row_base + (end_x as usize)) * 4;
836        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
837            return;
838        };
839        if sa == 255 {
840            fill_rgba_span_32(
841                span,
842                [color.get_red(), color.get_green(), color.get_blue(), 255],
843            );
844            return;
845        }
846        let sr: u32 = color.get_red() as u32;
847        let sg: u32 = color.get_green() as u32;
848        let sb: u32 = color.get_blue() as u32;
849        let sa_u32: u32 = sa as u32;
850        let inv_a: u32 = 255 - sa_u32;
851        for px in span.as_chunks_mut::<4>().0.iter_mut() {
852            let dr: u32 = px[0] as u32;
853            let dg: u32 = px[1] as u32;
854            let db: u32 = px[2] as u32;
855            let da: u32 = px[3] as u32;
856            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
857            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
858            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
859            let va: u32 = da * inv_a + 128;
860            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
861            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
862            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
863            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
864        }
865    }
866
867    /// Fills or LUT linear-light blends horizontal span `[x0, x1)` on global row `y`.
868    ///
869    /// # Arguments
870    ///
871    /// - `&Self` - Mutable pixel band.
872    /// - `u32` - Inclusive start X coordinate.
873    /// - `u32` - Exclusive end X coordinate.
874    /// - `u32` - Global physical Y coordinate.
875    /// - `Color` - Foreground RGBA color.
876    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, pos_y: u32, color: Color) {
877        let sa: u8 = color.get_alpha();
878        if sa == 255 {
879            self.fill_span(x0, x1, pos_y, color);
880            return;
881        }
882        let Self {
883            width,
884            y_offset,
885            height,
886            pixels,
887        } = self;
888        if sa == 0 || pos_y < *y_offset || pos_y >= *y_offset + *height || x0 >= x1 || x0 >= *width
889        {
890            return;
891        }
892        let end_x: u32 = x1.min(*width);
893        let row_base: usize = ((pos_y - *y_offset) as usize) * (*width as usize);
894        let start_byte: usize = (row_base + (x0 as usize)) * 4;
895        let end_byte: usize = (row_base + (end_x as usize)) * 4;
896        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
897            return;
898        };
899        fill_span_linear_slice(span, color);
900    }
901
902    /// Composites horizontal span `[x0, x1)` on global row `y` using precomputed bit-exact 256-entry linear-light channel LUTs.
903    ///
904    /// # Arguments
905    ///
906    /// - `&Self` - Mutable pixel band.
907    /// - `u32` - Inclusive start X coordinate.
908    /// - `u32` - Exclusive end X coordinate.
909    /// - `u32` - Global physical Y coordinate.
910    /// - `&[[u8; 256]; 4]` - Precomputed per-channel lookup tables.
911    pub fn fill_span_linear_luts(&mut self, x0: u32, x1: u32, pos_y: u32, luts: &[[u8; 256]; 4]) {
912        let Self {
913            width,
914            y_offset,
915            height,
916            pixels,
917        } = self;
918        if pos_y < *y_offset || pos_y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
919            return;
920        }
921        let end_x: u32 = x1.min(*width);
922        let row_base: usize = ((pos_y - *y_offset) as usize) * (*width as usize);
923        let start_byte: usize = (row_base + (x0 as usize)) * 4;
924        let end_byte: usize = (row_base + (end_x as usize)) * 4;
925        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
926            return;
927        };
928        fill_span_linear_luts_slice(span, luts);
929    }
930
931    /// Composites a constant-opacity horizontal shadow span `[x0, x1)` on global row `y` with L1 LUT linear light and IGN dithering.
932    ///
933    /// # Arguments
934    ///
935    /// - `&Self` - Mutable pixel band.
936    /// - `u32` - Inclusive start X coordinate.
937    /// - `u32` - Exclusive end X coordinate.
938    /// - `u32` - Global physical Y coordinate.
939    /// - `Color` - Shadow tint RGB.
940    /// - `f32` - Continuous shadow opacity in `[0.0, 1.0]`.
941    pub fn blend_shadow_span_const_alpha(
942        &mut self,
943        x0: u32,
944        x1: u32,
945        pos_y: u32,
946        color: Color,
947        alpha_f: f32,
948    ) {
949        if alpha_f <= 0.0005 {
950            return;
951        }
952        let Self {
953            width,
954            y_offset,
955            height,
956            pixels,
957        } = self;
958        if pos_y < *y_offset || pos_y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
959            return;
960        }
961        let end_x: u32 = x1.min(*width);
962        let row_base: usize = ((pos_y - *y_offset) as usize) * (*width as usize);
963        let start_byte: usize = (row_base + (x0 as usize)) * 4;
964        let end_byte: usize = (row_base + (end_x as usize)) * 4;
965        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
966            return;
967        };
968        let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
969        let cr: u8 = color.get_red();
970        let cg: u8 = color.get_green();
971        let callback_fn: u8 = color.get_blue();
972        let (chunks, _): (&mut [[u8; 4]], &mut [u8]) = span.as_chunks_mut::<4>();
973        if alpha_val >= 0.9995 {
974            let opaque: [u8; 4] = [cr, cg, callback_fn, 255];
975            for px in chunks.iter_mut() {
976                *px = opaque;
977            }
978            return;
979        }
980        let Some(first_px) = chunks.first().copied() else {
981            return;
982        };
983        let inv_a: f32 = 1.0 - alpha_val;
984        let sr_a: f32 = SRGB_TO_LIN_LUT[cr as usize] * alpha_val;
985        let sg_a: f32 = SRGB_TO_LIN_LUT[cg as usize] * alpha_val;
986        let sb_a: f32 = SRGB_TO_LIN_LUT[callback_fn as usize] * alpha_val;
987        let sa_u32: u32 = (alpha_val * 255.0) as u32;
988        let inv_a_u32: u32 = 255 - sa_u32;
989        let mut phase_u32: u32 = x0
990            .wrapping_mul(IGN_X_STEP_U32)
991            .wrapping_add(pos_y.wrapping_mul(IGN_Y_STEP_U32));
992        let mut prev_px: [u8; 4] = first_px;
993        let dr0: f32 = SRGB_TO_LIN_LUT[first_px[0] as usize];
994        let dg0: f32 = SRGB_TO_LIN_LUT[first_px[1] as usize];
995        let db0: f32 = SRGB_TO_LIN_LUT[first_px[2] as usize];
996        let ir0: usize = ((sr_a + dr0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
997        let ig0: usize = ((sg_a + dg0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
998        let ib0: usize = ((sb_a + db0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
999        let mut q4_r: u16 = LIN_TO_SRGB_Q4_LUT[ir0];
1000        let mut q4_g: u16 = LIN_TO_SRGB_Q4_LUT[ig0];
1001        let mut q4_b: u16 = LIN_TO_SRGB_Q4_LUT[ib0];
1002        let va0: u32 = (first_px[3] as u32) * inv_a_u32 + 128;
1003        let mut out_a: u8 = (sa_u32 + ((va0 + (va0 >> 8)) >> 8)).min(255) as u8;
1004        let total_len: usize = chunks.len();
1005        let mut miss_count: u32 = 0;
1006        let mut split_idx: usize = total_len;
1007        for (idx, px) in chunks.iter_mut().enumerate() {
1008            if *px != prev_px {
1009                miss_count += 1;
1010                if miss_count >= 10 && total_len.saturating_sub(idx) >= 64 {
1011                    split_idx = idx;
1012                    break;
1013                }
1014                prev_px = *px;
1015                let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
1016                let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
1017                let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
1018                let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1019                let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1020                let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1021                q4_r = LIN_TO_SRGB_Q4_LUT[ir];
1022                q4_g = LIN_TO_SRGB_Q4_LUT[ig];
1023                q4_b = LIN_TO_SRGB_Q4_LUT[ib];
1024                if px[3] == 255 {
1025                    out_a = 255;
1026                } else {
1027                    let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
1028                    out_a = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1029                }
1030            }
1031            let dq: u16 = (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
1032            phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
1033            px[0] = ((q4_r + dq) >> 4) as u8;
1034            px[1] = ((q4_g + dq) >> 4) as u8;
1035            px[2] = ((q4_b + dq) >> 4) as u8;
1036            px[3] = out_a;
1037        }
1038        if split_idx < total_len {
1039            let tail: &mut [[u8; 4]] = &mut chunks[split_idx..];
1040            let same_rg: bool = cr == cg;
1041            let same_rb: bool = cr == callback_fn;
1042            let lut_r: [u16; 256] = build_shadow_q4_lut_channel(cr, alpha_val);
1043            if same_rg && same_rb {
1044                for px in tail.iter_mut() {
1045                    let dq: u16 =
1046                        (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
1047                    phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
1048                    px[0] = ((lut_r[px[0] as usize] + dq) >> 4) as u8;
1049                    px[1] = ((lut_r[px[1] as usize] + dq) >> 4) as u8;
1050                    px[2] = ((lut_r[px[2] as usize] + dq) >> 4) as u8;
1051                    if px[3] != 255 {
1052                        let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
1053                        px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1054                    }
1055                }
1056            } else {
1057                let lut_g: [u16; 256] = if same_rg {
1058                    lut_r
1059                } else {
1060                    build_shadow_q4_lut_channel(cg, alpha_val)
1061                };
1062                let lut_b: [u16; 256] = if same_rb {
1063                    lut_r
1064                } else {
1065                    build_shadow_q4_lut_channel(callback_fn, alpha_val)
1066                };
1067                for px in tail.iter_mut() {
1068                    let dq: u16 =
1069                        (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
1070                    phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
1071                    px[0] = ((lut_r[px[0] as usize] + dq) >> 4) as u8;
1072                    px[1] = ((lut_g[px[1] as usize] + dq) >> 4) as u8;
1073                    px[2] = ((lut_b[px[2] as usize] + dq) >> 4) as u8;
1074                    if px[3] != 255 {
1075                        let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
1076                        px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1077                    }
1078                }
1079            }
1080        }
1081    }
1082
1083    /// Blends a contiguous glyph alpha coverage row onto global row `dy` starting at `dx`.
1084    ///
1085    /// # Arguments
1086    ///
1087    /// - `&Self` - Mutable pixel band.
1088    /// - `u32` - Destination starting X coordinate.
1089    /// - `u32` - Global destination Y coordinate.
1090    /// - `&[u8]` - Glyph alpha coverage slice.
1091    /// - `Color` - Foreground text color.
1092    ///
1093    /// # Returns
1094    ///
1095    /// - `usize` - Number of non-zero coverage pixels shaded.
1096    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
1097        let Self {
1098            width,
1099            y_offset,
1100            height,
1101            pixels,
1102        } = self;
1103        if color.get_alpha() == 0
1104            || dy < *y_offset
1105            || dy >= *y_offset + *height
1106            || dx >= *width
1107            || coverage.is_empty()
1108        {
1109            return 0;
1110        }
1111        let max_len: usize = ((*width - dx) as usize).min(coverage.len());
1112        let start_byte: usize =
1113            (((dy - *y_offset) as usize) * (*width as usize) + (dx as usize)) * 4;
1114        let end_byte: usize = start_byte + max_len * 4;
1115        let Some(dst_span) = pixels.get_mut(start_byte..end_byte) else {
1116            return 0;
1117        };
1118        blend_glyph_row_span(dst_span, &coverage[..max_len], color)
1119    }
1120
1121    /// Blends `color` over global pixel `(x, y)` using fast integer Porter-Duff source-over.
1122    ///
1123    /// # Arguments
1124    ///
1125    /// - `&Self` - Mutable pixel band.
1126    /// - `u32` - X pixel coordinate.
1127    /// - `u32` - Global Y pixel coordinate.
1128    /// - `Color` - Foreground color.
1129    pub fn blend_pixel(&mut self, pos_x: u32, pos_y: u32, color: Color) {
1130        let sa: u8 = color.get_alpha();
1131        let Self {
1132            width,
1133            y_offset,
1134            height,
1135            pixels,
1136        } = self;
1137        if sa == 0 || pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height {
1138            return;
1139        }
1140        let offset: usize =
1141            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1142        if offset + 4 > pixels.len() {
1143            return;
1144        }
1145        if sa == 255 {
1146            pixels[offset] = color.get_red();
1147            pixels[offset + 1] = color.get_green();
1148            pixels[offset + 2] = color.get_blue();
1149            pixels[offset + 3] = 255;
1150            return;
1151        }
1152        let dst: Color = Color::new(
1153            pixels[offset],
1154            pixels[offset + 1],
1155            pixels[offset + 2],
1156            pixels[offset + 3],
1157        );
1158        let blended: Color = color.blend_over(dst);
1159        pixels[offset] = blended.get_red();
1160        pixels[offset + 1] = blended.get_green();
1161        pixels[offset + 2] = blended.get_blue();
1162        pixels[offset + 3] = blended.get_alpha();
1163    }
1164
1165    /// Blends `color` over global pixel `(x, y)` using L1 LUT linear-light compositing with optional sub-LSB dithering.
1166    ///
1167    /// # Arguments
1168    ///
1169    /// - `&Self` - Mutable pixel band.
1170    /// - `u32` - X pixel coordinate.
1171    /// - `u32` - Global Y pixel coordinate.
1172    /// - `Color` - Foreground color.
1173    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
1174    pub fn blend_pixel_linear_dithered(
1175        &mut self,
1176        pos_x: u32,
1177        pos_y: u32,
1178        color: Color,
1179        dither: f32,
1180    ) {
1181        let sa: u8 = color.get_alpha();
1182        let Self {
1183            width,
1184            y_offset,
1185            height,
1186            pixels,
1187        } = self;
1188        if sa == 0 || pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height {
1189            return;
1190        }
1191        let offset: usize =
1192            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1193        if offset + 4 > pixels.len() {
1194            return;
1195        }
1196        if sa == 255 {
1197            pixels[offset] = color.get_red();
1198            pixels[offset + 1] = color.get_green();
1199            pixels[offset + 2] = color.get_blue();
1200            pixels[offset + 3] = 255;
1201            return;
1202        }
1203        let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
1204        let inv_a: f32 = 1.0 - alpha_val;
1205        let sr: f32 = SRGB_TO_LIN_LUT[color.get_red() as usize];
1206        let sg: f32 = SRGB_TO_LIN_LUT[color.get_green() as usize];
1207        let sb: f32 = SRGB_TO_LIN_LUT[color.get_blue() as usize];
1208        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1209        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1210        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1211        let ir: usize = ((sr * alpha_val + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1212        let ig: usize = ((sg * alpha_val + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1213        let ib: usize = ((sb * alpha_val + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1214        let dq: i32 = (dither * 16.0) as i32 + 8;
1215        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1216        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1217        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1218        let sa_u32: u32 = sa as u32;
1219        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1220        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1221    }
1222
1223    /// Blends a foreground RGB color with continuous floating-point opacity `alpha_f` onto global pixel `(x, y)` via L1 LUT linear light.
1224    ///
1225    /// # Arguments
1226    ///
1227    /// - `&Self` - Mutable pixel band.
1228    /// - `u32` - X pixel coordinate.
1229    /// - `u32` - Global Y pixel coordinate.
1230    /// - `Color` - Foreground RGB tint.
1231    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
1232    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
1233    pub fn blend_pixel_f32_dithered(
1234        &mut self,
1235        pos_x: u32,
1236        pos_y: u32,
1237        color: Color,
1238        alpha_f: f32,
1239        dither: f32,
1240    ) {
1241        let Self {
1242            width,
1243            y_offset,
1244            height,
1245            pixels,
1246        } = self;
1247        if alpha_f <= 0.0002 || pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height
1248        {
1249            return;
1250        }
1251        let offset: usize =
1252            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1253        if offset + 4 > pixels.len() {
1254            return;
1255        }
1256        let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
1257        if alpha_val >= 0.9995 {
1258            pixels[offset] = color.get_red();
1259            pixels[offset + 1] = color.get_green();
1260            pixels[offset + 2] = color.get_blue();
1261            pixels[offset + 3] = 255;
1262            return;
1263        }
1264        let inv_a: f32 = 1.0 - alpha_val;
1265        let sr: f32 = SRGB_TO_LIN_LUT[color.get_red() as usize];
1266        let sg: f32 = SRGB_TO_LIN_LUT[color.get_green() as usize];
1267        let sb: f32 = SRGB_TO_LIN_LUT[color.get_blue() as usize];
1268        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1269        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1270        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1271        let ir: usize = ((sr * alpha_val + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1272        let ig: usize = ((sg * alpha_val + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1273        let ib: usize = ((sb * alpha_val + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1274        let dq: i32 = (dither * 16.0) as i32 + 8;
1275        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1276        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1277        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1278        let sa_u32: u32 = (alpha_val * 255.0) as u32;
1279        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1280        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1281    }
1282
1283    /// Reads the raw RGBA8 bytes at global pixel `(x, y)` if owned by this band.
1284    ///
1285    /// # Arguments
1286    ///
1287    /// - `&Self` - Pixel band reference.
1288    /// - `u32` - X pixel coordinate.
1289    /// - `u32` - Global Y pixel coordinate.
1290    ///
1291    /// # Returns
1292    ///
1293    /// - `[u8; 4]` - Pixel RGBA8 bytes (`[0, 0, 0, 0]` when out of bounds).
1294    #[must_use]
1295    pub fn get_pixel_rgba(&self, pos_x: u32, pos_y: u32) -> [u8; 4] {
1296        let Self {
1297            width,
1298            y_offset,
1299            height,
1300            pixels,
1301        } = self;
1302        if pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height {
1303            return [0, 0, 0, 0];
1304        }
1305        let offset: usize =
1306            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1307        if offset + 4 > pixels.len() {
1308            return [0, 0, 0, 0];
1309        }
1310        [
1311            pixels[offset],
1312            pixels[offset + 1],
1313            pixels[offset + 2],
1314            pixels[offset + 3],
1315        ]
1316    }
1317
1318    /// Writes raw RGBA8 bytes directly to global pixel `(x, y)` when owned by this band.
1319    ///
1320    /// # Arguments
1321    ///
1322    /// - `&Self` - Mutable pixel band.
1323    /// - `u32` - X pixel coordinate.
1324    /// - `u32` - Global Y pixel coordinate.
1325    /// - `[u8; 4]` - Target RGBA8 pixel bytes.
1326    pub fn set_pixel_rgba(&mut self, pos_x: u32, pos_y: u32, rgba: [u8; 4]) {
1327        let Self {
1328            width,
1329            y_offset,
1330            height,
1331            pixels,
1332        } = self;
1333        if pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height {
1334            return;
1335        }
1336        let offset: usize =
1337            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1338        if offset + 4 > pixels.len() {
1339            return;
1340        }
1341        pixels[offset] = rgba[0];
1342        pixels[offset + 1] = rgba[1];
1343        pixels[offset + 2] = rgba[2];
1344        pixels[offset + 3] = rgba[3];
1345    }
1346
1347    /// Blends the current rasterized pixel at `(x, y)` back toward `saved_rgba` using linear-light clip coverage `cov`.
1348    ///
1349    /// # Arguments
1350    ///
1351    /// - `&Self` - Mutable pixel band.
1352    /// - `u32` - X pixel coordinate.
1353    /// - `u32` - Global Y pixel coordinate.
1354    /// - `[u8; 4]` - Pre-command saved RGBA8 pixel bytes.
1355    /// - `f32` - Clip mask coverage in `[0.0, 1.0]` (`1.0` keeps current pixel, `0.0` restores `saved_rgba`).
1356    pub fn lerp_pixel_from_saved_linear(
1357        &mut self,
1358        pos_x: u32,
1359        pos_y: u32,
1360        saved_rgba: [u8; 4],
1361        cov: f32,
1362    ) {
1363        let Self {
1364            width,
1365            y_offset,
1366            height,
1367            pixels,
1368        } = self;
1369        if pos_x >= *width || pos_y < *y_offset || pos_y >= *y_offset + *height {
1370            return;
1371        }
1372        let offset: usize =
1373            (((pos_y - *y_offset) as usize) * (*width as usize) + (pos_x as usize)) * 4;
1374        if offset + 4 > pixels.len() {
1375            return;
1376        }
1377        let cur: [u8; 4] = [
1378            pixels[offset],
1379            pixels[offset + 1],
1380            pixels[offset + 2],
1381            pixels[offset + 3],
1382        ];
1383        if cur == saved_rgba {
1384            return;
1385        }
1386        let char_item: f32 = cov.clamp(0.0, 1.0);
1387        let inv_c: f32 = 1.0 - char_item;
1388        let nr: f32 = SRGB_TO_LIN_LUT[cur[0] as usize];
1389        let ng: f32 = SRGB_TO_LIN_LUT[cur[1] as usize];
1390        let nb: f32 = SRGB_TO_LIN_LUT[cur[2] as usize];
1391        let or: f32 = SRGB_TO_LIN_LUT[saved_rgba[0] as usize];
1392        let og: f32 = SRGB_TO_LIN_LUT[saved_rgba[1] as usize];
1393        let ob: f32 = SRGB_TO_LIN_LUT[saved_rgba[2] as usize];
1394        let ir: usize = ((nr * char_item + or * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1395        let ig: usize = ((ng * char_item + og * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1396        let ib: usize = ((nb * char_item + ob * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1397        pixels[offset] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
1398        pixels[offset + 1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
1399        pixels[offset + 2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
1400        let na: f32 = (cur[3] as f32) * char_item + (saved_rgba[3] as f32) * inv_c;
1401        pixels[offset + 3] = na.round().clamp(0.0, 255.0) as u8;
1402    }
1403}
1404
1405/// Damage accumulation helpers for `DamageRegion`.
1406impl DamageRegion {
1407    /// Marks the entire surface damaged.
1408    ///
1409    /// # Returns
1410    ///
1411    /// - `Self` - Full-surface damage region.
1412    #[must_use]
1413    pub fn full() -> Self {
1414        Self {
1415            full_damage: true,
1416            rect: None,
1417            rects: [Rect::default(); 8],
1418            rect_count: 0,
1419        }
1420    }
1421
1422    /// Expands the damaged region to include `rect`, normalizing disjoint regions inline on the stack.
1423    ///
1424    /// # Arguments
1425    ///
1426    /// - `&Self` - Mutable damage region.
1427    /// - `Rect` - Newly damaged rectangle.
1428    pub fn add_rect(&mut self, rect: Rect) {
1429        let Self {
1430            full_damage,
1431            rect: bounds,
1432            rects,
1433            rect_count,
1434        } = self;
1435        if *full_damage {
1436            return;
1437        }
1438        let next_bounds: Rect = match *bounds {
1439            Some(existing) => existing.union(rect),
1440            None => rect,
1441        };
1442        *bounds = Some(next_bounds);
1443        if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
1444            return;
1445        }
1446        let mut merged: Rect = rect;
1447        let mut count: usize = (*rect_count as usize).min(rects.len());
1448        let mut changed: bool = true;
1449        while changed {
1450            changed = false;
1451            let mut item_index: usize = 0;
1452            while item_index < count {
1453                let cur: Rect = rects[item_index];
1454                let touches: bool = merged.get_x() - 2.0 <= cur.right()
1455                    && cur.get_x() - 2.0 <= merged.right()
1456                    && merged.get_y() - 2.0 <= cur.bottom()
1457                    && cur.get_y() - 2.0 <= merged.bottom();
1458                let stacked_column: bool = !touches
1459                    && (merged.get_x() - cur.get_x()).abs() <= 4.0
1460                    && (merged.right() - cur.right()).abs() <= 4.0
1461                    && merged.get_y() - 14.0 <= cur.bottom()
1462                    && cur.get_y() - 14.0 <= merged.bottom();
1463                if touches || stacked_column {
1464                    merged = merged.union(cur);
1465                    count -= 1;
1466                    let mut inner_index: usize = item_index;
1467                    while inner_index < count {
1468                        rects[inner_index] = rects[inner_index + 1];
1469                        inner_index += 1;
1470                    }
1471                    rects[count] = Rect::default();
1472                    changed = true;
1473                } else {
1474                    item_index += 1;
1475                }
1476            }
1477        }
1478        if count < rects.len() {
1479            let mut insert_at: usize = count;
1480            while insert_at > 0 {
1481                let prev: Rect = rects[insert_at - 1];
1482                let goes_before: bool = merged.get_y() < prev.get_y()
1483                    || (merged.get_y() == prev.get_y() && merged.get_x() < prev.get_x());
1484                if goes_before {
1485                    rects[insert_at] = prev;
1486                    insert_at -= 1;
1487                } else {
1488                    break;
1489                }
1490            }
1491            rects[insert_at] = merged;
1492            *rect_count = (count + 1) as u8;
1493        } else {
1494            let mut candidates: [Rect; 9] = [Rect::default(); 9];
1495            candidates[..8].copy_from_slice(rects);
1496            candidates[8] = merged;
1497            let mut best_a: usize = 0;
1498            let mut best_b: usize = 1;
1499            let mut best_waste: f32 = f32::INFINITY;
1500            for alpha_val in 0..9usize {
1501                let area_a: f32 =
1502                    candidates[alpha_val].get_width() * candidates[alpha_val].get_height();
1503                for blue_val in (alpha_val + 1)..9usize {
1504                    let area_b: f32 =
1505                        candidates[blue_val].get_width() * candidates[blue_val].get_height();
1506                    let rect_bounds: Rect = candidates[alpha_val].union(candidates[blue_val]);
1507                    let waste: f32 =
1508                        (rect_bounds.get_width() * rect_bounds.get_height()) - area_a - area_b;
1509                    if waste < best_waste {
1510                        best_waste = waste;
1511                        best_a = alpha_val;
1512                        best_b = blue_val;
1513                    }
1514                }
1515            }
1516            candidates[best_a] = candidates[best_a].union(candidates[best_b]);
1517            let mut out_len: usize = 0;
1518            for (idx, item) in candidates.iter().copied().enumerate() {
1519                if idx == best_b {
1520                    continue;
1521                }
1522                let mut pos: usize = out_len;
1523                while pos > 0 {
1524                    let prev: Rect = rects[pos - 1];
1525                    let goes_before: bool = item.get_y() < prev.get_y()
1526                        || (item.get_y() == prev.get_y() && item.get_x() < prev.get_x());
1527                    if goes_before {
1528                        rects[pos] = prev;
1529                        pos -= 1;
1530                    } else {
1531                        break;
1532                    }
1533                }
1534                rects[pos] = item;
1535                out_len += 1;
1536            }
1537            *rect_count = out_len as u8;
1538        }
1539    }
1540
1541    /// Returns viewport-clamped non-overlapping damage rectangles normalized into a stack array without heap allocation.
1542    ///
1543    /// # Arguments
1544    ///
1545    /// - `&Self` - Damage region.
1546    /// - `u32` - Surface physical width.
1547    /// - `u32` - Surface physical height.
1548    ///
1549    /// # Returns
1550    ///
1551    /// - `([Rect; 8], usize)` - Stack array of clamped disjoint damage rectangles and active count `0..=8`.
1552    #[must_use]
1553    pub(crate) fn normalized_rects(&self, width: u32, height: u32) -> ([Rect; 8], usize) {
1554        let Self {
1555            full_damage,
1556            rect: bounds,
1557            rects,
1558            rect_count,
1559        } = *self;
1560        let mut out: [Rect; 8] = [Rect::default(); 8];
1561        if width == 0 || height == 0 {
1562            return (out, 0);
1563        }
1564        let viewport: Rect = Rect::new(0.0, 0.0, width as f32, height as f32);
1565        if full_damage {
1566            out[0] = viewport;
1567            return (out, 1);
1568        }
1569        let Some(bound_rect) = bounds else {
1570            return (out, 0);
1571        };
1572        let active: usize = (rect_count as usize).min(out.len());
1573        if active == 0 {
1574            if let Some(clamped) = bound_rect.intersect(viewport)
1575                && clamped.get_width() > 0.0
1576                && clamped.get_height() > 0.0
1577            {
1578                out[0] = clamped;
1579                return (out, 1);
1580            }
1581            return (out, 0);
1582        }
1583        let mut out_len: usize = 0;
1584        for item in rects.iter().take(active) {
1585            if let Some(clamped) = item.intersect(viewport)
1586                && clamped.get_width() > 0.0
1587                && clamped.get_height() > 0.0
1588            {
1589                out[out_len] = clamped;
1590                out_len += 1;
1591            }
1592        }
1593        (out, out_len)
1594    }
1595
1596    /// Returns the damaged bounding rectangle, or full viewport when `full_damage` is true.
1597    ///
1598    /// # Arguments
1599    ///
1600    /// - `&Self` - Damage region.
1601    /// - `u32` - Surface width.
1602    /// - `u32` - Surface height.
1603    ///
1604    /// # Returns
1605    ///
1606    /// - `Option<Rect>` - Effective clip rect to rasterize, or `None` if undamaged.
1607    #[must_use]
1608    pub fn resolve(&self, width: u32, height: u32) -> Option<Rect> {
1609        if self.get_full_damage() {
1610            return Some(Rect::new(0.0, 0.0, width as f32, height as f32));
1611        }
1612        self.bounds_rect()
1613    }
1614
1615    /// Returns the optional accumulated damage rectangle.
1616    ///
1617    /// # Arguments
1618    ///
1619    /// - `&Self` - Damage region.
1620    ///
1621    /// # Returns
1622    ///
1623    /// - `Option<Rect>` - Accumulated rectangle if any.
1624    #[must_use]
1625    pub fn bounds_rect(&self) -> Option<Rect> {
1626        let Self { rect, .. } = *self;
1627        rect
1628    }
1629
1630    /// Optimizes multi-rect damage by merging low-waste adjacent pairs and promoting to full-viewport damage when covered area exceeds `full_fallback_ratio`.
1631    ///
1632    /// # Arguments
1633    ///
1634    /// - `&Self` - Mutable damage region.
1635    /// - `u32` - Surface physical width in pixels.
1636    /// - `u32` - Surface physical height in pixels.
1637    /// - `f32` - Area coverage threshold in `(0.1..=1.0]` above which full-frame fallback triggers.
1638    ///
1639    /// # Returns
1640    ///
1641    /// - `bool` - `true` if the damage region was promoted to `full_damage`.
1642    pub fn optimize_for_viewport(
1643        &mut self,
1644        width: u32,
1645        height: u32,
1646        full_fallback_ratio: f32,
1647    ) -> bool {
1648        if self.get_full_damage() {
1649            return true;
1650        }
1651        let total_area: f32 = (width as f32) * (height as f32);
1652        if total_area <= 0.0 {
1653            return false;
1654        }
1655        let threshold: f32 = full_fallback_ratio.clamp(0.1, 1.0);
1656        let (mut list, mut count): ([Rect; 8], usize) = self.normalized_rects(width, height);
1657        if count == 0 {
1658            return false;
1659        }
1660        let mut dirty_area: f32 = 0.0;
1661        for item in list.iter().take(count) {
1662            dirty_area += item.get_width().max(0.0) * item.get_height().max(0.0);
1663        }
1664        if dirty_area / total_area >= threshold {
1665            *self = Self::full();
1666            return true;
1667        }
1668        let mut merged_any: bool = true;
1669        while merged_any && count > 1 {
1670            merged_any = false;
1671            let mut best_pair: Option<(usize, usize, Rect, f32)> = None;
1672            for item_index in 0..count {
1673                let area_i: f32 =
1674                    list[item_index].get_width().max(0.0) * list[item_index].get_height().max(0.0);
1675                for inner_index in (item_index + 1)..count {
1676                    let area_j: f32 = list[inner_index].get_width().max(0.0)
1677                        * list[inner_index].get_height().max(0.0);
1678                    let rect_bounds: Rect = list[item_index].union(list[inner_index]);
1679                    let union_area: f32 =
1680                        rect_bounds.get_width().max(0.0) * rect_bounds.get_height().max(0.0);
1681                    let waste: f32 = (union_area - (area_i + area_j)).max(0.0);
1682                    let acceptable: bool = waste <= (area_i + area_j) * 0.25 || count > 4;
1683                    if acceptable {
1684                        let better: bool = match best_pair {
1685                            Some((_, _, _, best_w)) => waste < best_w,
1686                            None => true,
1687                        };
1688                        if better {
1689                            best_pair = Some((item_index, inner_index, rect_bounds, waste));
1690                        }
1691                    }
1692                }
1693            }
1694            if let Some((outer_index, col_index, tex_u, _)) = best_pair {
1695                list[outer_index] = tex_u;
1696                let mut entry_index: usize = col_index;
1697                while entry_index + 1 < count {
1698                    list[entry_index] = list[entry_index + 1];
1699                    entry_index += 1;
1700                }
1701                list[count - 1] = Rect::default();
1702                count -= 1;
1703                merged_any = true;
1704            }
1705        }
1706        let mut post_area: f32 = 0.0;
1707        let mut union_all: Rect = list[0];
1708        for item in list.iter().take(count) {
1709            post_area += item.get_width().max(0.0) * item.get_height().max(0.0);
1710            union_all = union_all.union(*item);
1711        }
1712        if post_area / total_area >= threshold {
1713            *self = Self::full();
1714            return true;
1715        }
1716        let Self {
1717            rect,
1718            rects,
1719            rect_count,
1720            ..
1721        } = self;
1722        *rect = Some(union_all);
1723        *rects = list;
1724        *rect_count = count as u8;
1725        false
1726    }
1727
1728    /// Returns the number of active normalized disjoint damage rectangles.
1729    ///
1730    /// # Arguments
1731    ///
1732    /// - `&Self` - Damage region reference.
1733    ///
1734    /// # Returns
1735    ///
1736    /// - `usize` - Count of disjoint damage rectangles (`1` when `full_damage` is set).
1737    #[must_use]
1738    pub fn active_rect_count(&self) -> usize {
1739        if self.get_full_damage() {
1740            1
1741        } else {
1742            let Self { rect_count, .. } = *self;
1743            rect_count as usize
1744        }
1745    }
1746
1747    /// Resets the damage region to clean.
1748    ///
1749    /// # Arguments
1750    ///
1751    /// - `&Self` - Mutable damage region.
1752    pub fn clear(&mut self) {
1753        let Self {
1754            full_damage,
1755            rect,
1756            rects,
1757            rect_count,
1758        } = self;
1759        *full_damage = false;
1760        *rect = None;
1761        *rects = [Rect::default(); 8];
1762        *rect_count = 0;
1763    }
1764}