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