Skip to main content

euv_core/render/software/
impl.rs

1use super::*;
2
3/// Persistent work-stealing multi-core band pool methods for `BandWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5/// Inherent implementation of [`BandWorkerPool`].
6impl BandWorkerPool {
7    /// Creates a persistent worker pool sized to the host CPU count (clamped to `1..=8` total threads including the caller).
8    ///
9    /// # Returns
10    ///
11    /// - `Self` - Initialized worker pool with warm background threads.
12    #[must_use]
13    pub(crate) fn new() -> Self {
14        let total: usize = available_parallelism()
15            .map(usize::from)
16            .unwrap_or(4)
17            .clamp(1, 8);
18        let worker_count: usize = total.saturating_sub(1);
19        let shared: Arc<(Mutex<BandPoolState>, Condvar, Condvar)> = Arc::new((
20            Mutex::new(BandPoolState::default()),
21            Condvar::new(),
22            Condvar::new(),
23        ));
24        for idx in 0..worker_count {
25            let shared_clone: Arc<(Mutex<BandPoolState>, Condvar, Condvar)> = Arc::clone(&shared);
26            let name: String = format!("{BAND_WORKER_THREAD_PREFIX}-{idx}");
27            let _: io::Result<JoinHandle<()>> = Builder::new().name(name).spawn(move || {
28                let mut seen_epoch: u64 = 0;
29                loop {
30                    let job_ptr: usize = {
31                        let (lock, wake_workers, _wake_caller): &(
32                            Mutex<BandPoolState>,
33                            Condvar,
34                            Condvar,
35                        ) = &shared_clone;
36                        let Ok(mut state) = lock.lock() else {
37                            break;
38                        };
39                        while state.get_epoch() == seen_epoch || state.get_active_job() == 0 {
40                            let Ok(next_guard) = wake_workers.wait(state) else {
41                                return;
42                            };
43                            state = next_guard;
44                        }
45                        seen_epoch = state.get_epoch();
46                        state.get_active_job()
47                    };
48                    let job: &BandJob = unsafe { &*(job_ptr as *const BandJob) };
49                    run_band_job_loop(job);
50                    let finished: usize = job.workers_done.fetch_add(1, Ordering::AcqRel) + 1;
51                    if finished >= worker_count {
52                        let (lock, _wake_workers, wake_caller): &(
53                            Mutex<BandPoolState>,
54                            Condvar,
55                            Condvar,
56                        ) = &shared_clone;
57                        let _guard: Result<
58                            MutexGuard<'_, BandPoolState>,
59                            PoisonError<MutexGuard<'_, BandPoolState>>,
60                        > = lock.lock();
61                        wake_caller.notify_one();
62                    }
63                }
64            });
65        }
66        Self {
67            worker_count,
68            dispatch_lock: Mutex::new(()),
69            shared,
70        }
71    }
72
73    /// Executes bands serially on the calling thread with optional cached backdrop restore.
74    ///
75    /// # Arguments
76    ///
77    /// - `&mut [PixelBand<'_>]` - Disjoint horizontal framebuffer strips.
78    /// - `&[DrawCommand]` - Display list commands.
79    /// - `&[PreppedCommand]` - Pre-clipped command table.
80    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
81    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
82    /// - `(f32, AntialiasingMode)` - Tuple of `(scale, antialiasing)`.
83    /// - `Option<&[u8]>` - Optional cached base-scene RGBA8 pixel slice.
84    ///
85    /// # Returns
86    ///
87    /// - `usize` - Total shaded pixel count across all strips.
88    fn execute_serial(
89        bands: &mut [PixelBand<'_>],
90        commands: &[DrawCommand],
91        prepped: &[PreppedCommand],
92        layouts: &[TextLayoutResult],
93        atlas: &GlyphAtlas,
94        render_opts: (f32, AntialiasingMode),
95        base_restore: Option<&[u8]>,
96    ) -> usize {
97        let (scale, aa): (f32, AntialiasingMode) = render_opts;
98        let mut total: usize = 0;
99        for band in bands.iter_mut() {
100            if let Some(src_buf) = base_restore {
101                let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
102                let byte_end: usize = byte_off + band.pixels.len();
103                if let Some(src_slice) = src_buf.get(byte_off..byte_end) {
104                    band.pixels.copy_from_slice(src_slice);
105                }
106            }
107            total +=
108                SoftwareRenderer::render_band(band, commands, prepped, layouts, atlas, scale, aa);
109        }
110        total
111    }
112
113    /// Returns total participating rasterizer threads (background workers plus the calling main thread).
114    ///
115    /// # Returns
116    ///
117    /// - `usize` - Total active thread count in `1..=6`.
118    #[must_use]
119    pub(crate) fn total_threads(&self) -> usize {
120        let Self { worker_count, .. } = self;
121        worker_count.saturating_add(1)
122    }
123
124    /// Dispatches horizontal pixel bands across the persistent worker pool with optional parallel backdrop restore and synchronous completion.
125    ///
126    /// # Arguments
127    ///
128    /// - `&Self` - Worker pool reference.
129    /// - `&mut [PixelBand<'_>]` - Disjoint horizontal framebuffer strips.
130    /// - `&[DrawCommand]` - Display list commands.
131    /// - `&[PreppedCommand]` - Pre-clipped command table.
132    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
133    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
134    /// - `(f32, AntialiasingMode, Option<&[u8]>)` - Tuple of `(scale, antialiasing, optional_base_restore)`.
135    ///
136    /// # Returns
137    ///
138    /// - `usize` - Total shaded pixel count across all strips.
139    pub(crate) fn execute(
140        &self,
141        bands: &mut [PixelBand<'_>],
142        commands: &[DrawCommand],
143        prepped: &[PreppedCommand],
144        layouts: &[TextLayoutResult],
145        atlas: &GlyphAtlas,
146        render_opts: (f32, AntialiasingMode, Option<&[u8]>),
147    ) -> usize {
148        let Self {
149            worker_count,
150            dispatch_lock,
151            shared,
152        } = self;
153        let (scale, aa, base_restore): (f32, AntialiasingMode, Option<&[u8]>) = render_opts;
154        if *worker_count == 0 || bands.len() <= 1 {
155            return Self::execute_serial(
156                bands,
157                commands,
158                prepped,
159                layouts,
160                atlas,
161                (scale, aa),
162                base_restore,
163            );
164        }
165        let Ok(_dispatch_guard) = dispatch_lock.try_lock() else {
166            return Self::execute_serial(
167                bands,
168                commands,
169                prepped,
170                layouts,
171                atlas,
172                (scale, aa),
173                base_restore,
174            );
175        };
176        let mut tasks: Vec<BandTaskSlice> = Vec::with_capacity(bands.len());
177        for band in bands.iter_mut() {
178            let base_ptr: usize = if let Some(src_buf) = base_restore {
179                let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
180                let byte_end: usize = byte_off + band.pixels.len();
181                if byte_end <= src_buf.len() {
182                    unsafe { src_buf.as_ptr().add(byte_off) as usize }
183                } else {
184                    0
185                }
186            } else {
187                0
188            };
189            tasks.push(BandTaskSlice {
190                pixels_ptr: band.pixels.as_mut_ptr() as usize,
191                pixels_len: band.pixels.len(),
192                width: band.width,
193                y_start: band.y_offset,
194                height: band.height,
195                base_src_ptr: base_ptr,
196            });
197        }
198        let job: BandJob = BandJob {
199            tasks_ptr: tasks.as_ptr() as usize,
200            tasks_len: tasks.len(),
201            commands_ptr: commands.as_ptr() as usize,
202            commands_len: commands.len(),
203            prepped_ptr: prepped.as_ptr() as usize,
204            prepped_len: prepped.len(),
205            layouts_ptr: layouts.as_ptr() as usize,
206            layouts_len: layouts.len(),
207            atlas_ptr: (atlas as *const GlyphAtlas) as usize,
208            scale,
209            aa,
210            next_idx: AtomicUsize::new(0),
211            workers_done: AtomicUsize::new(0),
212            total_shaded: AtomicUsize::new(0),
213        };
214        let (lock, wake_workers, wake_caller): &(Mutex<BandPoolState>, Condvar, Condvar) = shared;
215        {
216            if let Ok(mut state) = lock.lock() {
217                let next_epoch: u64 = state.get_epoch().wrapping_add(1);
218                state.set_active_job((&job as *const BandJob) as usize);
219                state.set_epoch(next_epoch);
220                wake_workers.notify_all();
221            } else {
222                run_band_job_loop(&job);
223                return job.total_shaded.load(Ordering::Acquire);
224            }
225        }
226        run_band_job_loop(&job);
227        let mut wait_guard: Option<MutexGuard<'_, BandPoolState>> = lock.lock().ok();
228        while let Some(state) = wait_guard.take() {
229            if job.workers_done.load(Ordering::Acquire) >= *worker_count {
230                let mut done_state: MutexGuard<'_, BandPoolState> = state;
231                done_state.set_active_job(0);
232                break;
233            }
234            wait_guard = wake_caller.wait(state).ok();
235        }
236        job.total_shaded.load(Ordering::Acquire)
237    }
238}
239
240/// Multi-core lossless analytical-SDF and tile-band software rasterizer methods for `SoftwareRenderer`.
241impl SoftwareRenderer {
242    /// Creates a software renderer configured for `width x height` physical pixels.
243    ///
244    /// # Arguments
245    ///
246    /// - `u32` - Physical width.
247    /// - `u32` - Physical height.
248    /// - `RenderConfig` - Rendering configuration.
249    ///
250    /// # Returns
251    ///
252    /// - `Self` - Ready-to-draw software renderer.
253    #[must_use]
254    pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
255        Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
256    }
257
258    /// Creates a software renderer configured with an explicit `NativeSystemFont` provider.
259    ///
260    /// # Arguments
261    ///
262    /// - `u32` - Physical width.
263    /// - `u32` - Physical height.
264    /// - `RenderConfig` - Rendering configuration.
265    /// - `NativeSystemFont` - Native OS or deterministic font provider.
266    ///
267    /// # Returns
268    ///
269    /// - `Self` - Ready-to-draw software renderer.
270    #[must_use]
271    pub fn with_font_provider(
272        width: u32,
273        height: u32,
274        config: RenderConfig,
275        font_provider: NativeSystemFont,
276    ) -> Self {
277        Self {
278            framebuffer: Framebuffer::allocate(width, height),
279            glyph_atlas: GlyphAtlas::default(),
280            font_provider,
281            measurer: DeterministicTextMeasurer,
282            text_layout_cache: HashMap::with_capacity(128),
283            clip_stack: Vec::with_capacity(8),
284            antialiasing: config.get_antialiasing(),
285            tile_size: config.get_tile_size().max(16),
286            base_cache_width: 0,
287            base_cache_height: 0,
288            base_cache_hash: 0,
289            base_cache_pixels: Vec::new(),
290        }
291    }
292
293    /// Rasterizes `display_list` into the internal `Framebuffer` clipped to `damage` using multi-core parallel horizontal bands and lossless portal backdrop caching.
294    ///
295    /// # Arguments
296    ///
297    /// - `&Self` - Mutable software renderer.
298    /// - `&DisplayList` - Backend-agnostic draw command stream.
299    /// - `DamageRegion` - Optional dirty damage region for partial rasterization.
300    ///
301    /// # Returns
302    ///
303    /// - `(usize, usize)` - Tuple of `(tiles_updated, pixels_shaded)`.
304    pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
305        let scale: f32 = display_list.get_scale_factor().max(0.5);
306        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
307        let phys_h: u32 =
308            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
309        let resized: bool = self.get_mut_framebuffer().resize(phys_w, phys_h);
310        if resized {
311            self.set_base_cache_hash(0);
312            self.set_base_cache_width(0);
313            self.set_base_cache_height(0);
314        }
315        let effective_damage: DamageRegion = if resized {
316            DamageRegion::full()
317        } else {
318            damage
319        };
320        let Some(root_clip) = effective_damage.resolve(phys_w, phys_h) else {
321            return (0, 0);
322        };
323        let tile_sz: u32 = self.get_tile_size().max(16);
324        let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
325        let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
326        let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
327        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
328        let split: usize = display_list.get_portal_split_index().min(commands.len());
329        let has_portals: bool = split > 0 && split < commands.len();
330        let is_full_frame: bool = root_clip.get_x() <= 0.0
331            && root_clip.get_y() <= 0.0
332            && root_clip.get_width() >= (phys_w as f32)
333            && root_clip.get_height() >= (phys_h as f32);
334        if has_portals && is_full_frame {
335            let base_hash: u64 = display_list.base_layer_hash();
336            let fb_len: usize = self.get_framebuffer().get_pixels().len();
337            let cache_hit: bool = base_hash != 0
338                && self.get_base_cache_hash() == base_hash
339                && self.get_base_cache_width() == phys_w
340                && self.get_base_cache_height() == phys_h
341                && self.get_base_cache_pixels().len() == fb_len;
342            if cache_hit {
343                let (prepped, text_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) = self
344                    .prepare_frame_range(
345                        display_list,
346                        split,
347                        commands.len(),
348                        root_clip,
349                        scale,
350                        phys_h,
351                    );
352                let pixels_shaded: usize = self.execute_prepared_bands(
353                    commands,
354                    prepped.as_slice(),
355                    text_layouts.as_slice(),
356                    root_clip,
357                    (phys_w, phys_h, scale),
358                    true,
359                );
360                return (tiles_updated, pixels_shaded.max(1));
361            }
362            let (base_prepped, base_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
363                self.prepare_frame_range(display_list, 0, split, root_clip, scale, phys_h);
364            let base_shaded: usize = self.execute_prepared_bands(
365                commands,
366                base_prepped.as_slice(),
367                base_layouts.as_slice(),
368                root_clip,
369                (phys_w, phys_h, scale),
370                false,
371            );
372            {
373                let Self {
374                    framebuffer,
375                    base_cache_pixels,
376                    base_cache_width,
377                    base_cache_height,
378                    base_cache_hash,
379                    ..
380                } = self;
381                let src_pixels: &[u8] = framebuffer.get_pixels().as_slice();
382                if base_cache_pixels.len() != src_pixels.len() {
383                    base_cache_pixels.resize(src_pixels.len(), 0);
384                }
385                base_cache_pixels.copy_from_slice(src_pixels);
386                *base_cache_width = phys_w;
387                *base_cache_height = phys_h;
388                *base_cache_hash = base_hash;
389            }
390            let (portal_prepped, portal_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
391                self.prepare_frame_range(
392                    display_list,
393                    split,
394                    commands.len(),
395                    root_clip,
396                    scale,
397                    phys_h,
398                );
399            let portal_shaded: usize = self.execute_prepared_bands(
400                commands,
401                portal_prepped.as_slice(),
402                portal_layouts.as_slice(),
403                root_clip,
404                (phys_w, phys_h, scale),
405                false,
406            );
407            return (tiles_updated, base_shaded.saturating_add(portal_shaded));
408        }
409        if !has_portals {
410            self.set_base_cache_hash(0);
411        }
412        let (prepped, text_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
413            self.prepare_frame_range(display_list, 0, commands.len(), root_clip, scale, phys_h);
414        let pixels_shaded: usize = self.execute_prepared_bands(
415            commands,
416            prepped.as_slice(),
417            text_layouts.as_slice(),
418            root_clip,
419            (phys_w, phys_h, scale),
420            false,
421        );
422        (tiles_updated, pixels_shaded)
423    }
424
425    /// Executes prepped commands across horizontal bands with optional parallel restore from `base_cache_pixels`.
426    ///
427    /// # Arguments
428    ///
429    /// - `&Self` - Mutable software renderer.
430    /// - `&[DrawCommand]` - Full frame draw command slice.
431    /// - `&[PreppedCommand]` - Pre-clipped command slice.
432    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
433    /// - `Rect` - Root physical damage clip rectangle.
434    /// - `(u32, u32, f32)` - Tuple `(phys_w, phys_h, scale)`.
435    /// - `bool` - Whether to restore `base_cache_pixels` into each strip before rasterizing.
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - Total shaded pixel count.
440    fn execute_prepared_bands(
441        &mut self,
442        commands: &[DrawCommand],
443        prepped_slice: &[PreppedCommand],
444        layouts_slice: &[TextLayoutResult],
445        root_clip: Rect,
446        dims: (u32, u32, f32),
447        restore_base_cache: bool,
448    ) -> usize {
449        let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
450        let aa: AntialiasingMode = self.get_antialiasing();
451        let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
452        let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
453        let clip_w: u32 = (root_clip.get_width().ceil().max(0.0) as u32).min(phys_w);
454        let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
455        let Self {
456            framebuffer,
457            glyph_atlas,
458            base_cache_pixels,
459            ..
460        } = self;
461        let atlas_ref: &GlyphAtlas = glyph_atlas;
462        let base_restore: Option<&[u8]> = if restore_base_cache {
463            Some(base_cache_pixels.as_slice())
464        } else {
465            None
466        };
467        #[cfg(not(target_arch = "wasm32"))]
468        {
469            if (clip_w as usize).saturating_mul(clip_h as usize) >= 65_536 && clip_h >= 64 {
470                let pool: &BandWorkerPool = global_band_worker_pool();
471                let strip_count: usize = (pool.total_threads().saturating_mul(2))
472                    .min((clip_h / 24) as usize)
473                    .max(1);
474                if strip_count > 1 && pool.total_threads() > 1 {
475                    let mut bands: Vec<PixelBand<'_>> =
476                        framebuffer.split_bands_mut(clip_y0, clip_y1, strip_count);
477                    return pool.execute(
478                        bands.as_mut_slice(),
479                        commands,
480                        prepped_slice,
481                        layouts_slice,
482                        atlas_ref,
483                        (scale, aa, base_restore),
484                    );
485                }
486            }
487            if let Some(src_buf) = base_restore
488                && src_buf.len() == framebuffer.get_pixels().len()
489            {
490                framebuffer.get_mut_pixels().copy_from_slice(src_buf);
491            }
492            let mut band: PixelBand<'_> = framebuffer.as_band_mut();
493            Self::render_band(
494                &mut band,
495                commands,
496                prepped_slice,
497                layouts_slice,
498                atlas_ref,
499                scale,
500                aa,
501            )
502        }
503        #[cfg(target_arch = "wasm32")]
504        {
505            let _: (u32, u32) = (clip_w, clip_h);
506            if let Some(src_buf) = base_restore
507                && src_buf.len() == framebuffer.get_pixels().len()
508            {
509                framebuffer.get_mut_pixels().copy_from_slice(src_buf);
510            }
511            let mut band: PixelBand<'_> = framebuffer.as_band_mut();
512            Self::render_band(
513                &mut band,
514                commands,
515                prepped_slice,
516                layouts_slice,
517                atlas_ref,
518                scale,
519                aa,
520            )
521        }
522    }
523
524    /// Runs a lightweight main-thread pre-pass over `commands[start_idx..end_idx]` to resolve clips, opaque shadow cutouts, cached text layouts, and warm `GlyphAtlas`.
525    ///
526    /// # Arguments
527    ///
528    /// - `&Self` - Mutable software renderer.
529    /// - `&DisplayList` - Incoming command stream.
530    /// - `usize` - Inclusive start index into `display_list.get_commands()`.
531    /// - `usize` - Exclusive end index into `display_list.get_commands()`.
532    /// - `Rect` - Root physical damage clip rectangle.
533    /// - `f32` - Active DPI scale factor.
534    /// - `u32` - Framebuffer physical height.
535    ///
536    /// # Returns
537    ///
538    /// - `(Vec<PreppedCommand>, Vec<TextLayoutResult>)` - Band-ready commands and pre-measured text layouts.
539    fn prepare_frame_range(
540        &mut self,
541        display_list: &DisplayList,
542        start_idx: usize,
543        end_idx: usize,
544        root_clip: Rect,
545        scale: f32,
546        phys_h: u32,
547    ) -> (Vec<PreppedCommand>, Vec<TextLayoutResult>) {
548        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
549        let clamped_end: usize = end_idx.min(commands.len());
550        let clamped_start: usize = start_idx.min(clamped_end);
551        let mut prepped: Vec<PreppedCommand> = Vec::with_capacity(clamped_end - clamped_start);
552        let mut text_layouts: Vec<TextLayoutResult> = Vec::new();
553        let Self {
554            glyph_atlas,
555            font_provider,
556            measurer,
557            text_layout_cache,
558            clip_stack,
559            ..
560        } = self;
561        clip_stack.clear();
562        clip_stack.push(root_clip);
563        if text_layout_cache.len() > TEXT_LAYOUT_CACHE_LIMIT {
564            text_layout_cache.clear();
565        }
566        for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
567            let cmd_index: usize = clamped_start + offset;
568            let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
569            match cmd {
570                DrawCommand::PushClip(rect) => {
571                    let phys: Rect = snap_physical_rect(*rect, scale);
572                    let next: Rect = active_clip.intersect(phys).unwrap_or_default();
573                    clip_stack.push(next);
574                }
575                DrawCommand::PopClip => {
576                    if clip_stack.len() > 1 {
577                        clip_stack.pop();
578                    }
579                }
580                DrawCommand::Clear(_) => {
581                    let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
582                    let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
583                    if y0 < y1 {
584                        prepped.push(PreppedCommand {
585                            cmd_index,
586                            active_clip,
587                            y0,
588                            y1,
589                            opaque_cutout_h: Rect::default(),
590                            opaque_cutout_v: Rect::default(),
591                            text_layout_idx: u32::MAX,
592                        });
593                    }
594                }
595                DrawCommand::FillRoundedRect { rect, .. }
596                | DrawCommand::LinearGradientRect { rect, .. }
597                | DrawCommand::Image { rect, .. }
598                | DrawCommand::SpriteRegion { rect, .. } => {
599                    let phys: Rect = snap_physical_rect(*rect, scale);
600                    if let Some(vis) = phys.intersect(active_clip) {
601                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
602                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
603                        if y0 < y1 {
604                            prepped.push(PreppedCommand {
605                                cmd_index,
606                                active_clip,
607                                y0,
608                                y1,
609                                opaque_cutout_h: Rect::default(),
610                                opaque_cutout_v: Rect::default(),
611                                text_layout_idx: u32::MAX,
612                            });
613                        }
614                    }
615                }
616                DrawCommand::BoxShadow { rect, shadow, .. } => {
617                    if shadow.get_color().get_a() == 0 {
618                        continue;
619                    }
620                    let spread: f32 = shadow.get_spread_radius() * scale;
621                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
622                    let sigma: f32 = (blur * 0.5).max(0.75);
623                    let pad: f32 = (sigma * 3.0).ceil();
624                    let base_rect: Rect = snap_physical_rect(*rect, scale);
625                    let caster_rect: Rect = Rect::new(
626                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
627                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
628                        (base_rect.get_width() + spread * 2.0).max(1.0),
629                        (base_rect.get_height() + spread * 2.0).max(1.0),
630                    );
631                    let shadow_rect: Rect = Rect::new(
632                        caster_rect.get_x() - pad,
633                        caster_rect.get_y() - pad,
634                        caster_rect.get_width() + pad * 2.0,
635                        caster_rect.get_height() + pad * 2.0,
636                    );
637                    if let Some(vis) = shadow_rect.intersect(active_clip) {
638                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
639                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
640                        if y0 < y1 {
641                            let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
642                                commands.get(cmd_index + 1),
643                                scale,
644                            );
645                            prepped.push(PreppedCommand {
646                                cmd_index,
647                                active_clip,
648                                y0,
649                                y1,
650                                opaque_cutout_h: cut_h,
651                                opaque_cutout_v: cut_v,
652                                text_layout_idx: u32::MAX,
653                            });
654                        }
655                    }
656                }
657                DrawCommand::TextRun { rect, text, style } => {
658                    if text.is_empty() || style.get_color().get_a() == 0 {
659                        continue;
660                    }
661                    let phys_rect: Rect = Self::scale_rect(*rect, scale);
662                    let pad: f32 = style.get_font_size() * scale * 0.5;
663                    let expanded: Rect = Rect::new(
664                        phys_rect.get_x() - pad,
665                        phys_rect.get_y() - pad,
666                        phys_rect.get_width() + pad * 2.0,
667                        phys_rect.get_height() + pad * 2.0,
668                    );
669                    let Some(vis) = expanded.intersect(active_clip) else {
670                        continue;
671                    };
672                    let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
673                    let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
674                    if y0 >= y1 {
675                        continue;
676                    }
677                    let max_w: f32 = rect.get_width().max(1.0);
678                    let cache_key: (u64, u32) = (
679                        hash_text_layout_key(text, *style),
680                        (max_w * 10.0).round() as u32,
681                    );
682                    let layout: TextLayoutResult =
683                        if let Some(cached) = text_layout_cache.get(&cache_key) {
684                            cached.clone()
685                        } else {
686                            let measured: TextLayoutResult =
687                                measurer.measure(text, *style, Some(max_w));
688                            text_layout_cache.insert(cache_key, measured.clone());
689                            measured
690                        };
691                    let phys_font_size: f32 = style.get_font_size() * scale;
692                    for line in layout.get_lines().iter() {
693                        for ch in line.get_text().chars() {
694                            if ch != ' ' {
695                                let key: GlyphKey =
696                                    GlyphKey::from_text_style(ch, phys_font_size, *style);
697                                let _: &RasterizedGlyph =
698                                    glyph_atlas.get_or_rasterize_with(key, font_provider);
699                            }
700                        }
701                    }
702                    let layout_idx: u32 = text_layouts.len() as u32;
703                    text_layouts.push(layout);
704                    prepped.push(PreppedCommand {
705                        cmd_index,
706                        active_clip,
707                        y0,
708                        y1,
709                        opaque_cutout_h: Rect::default(),
710                        opaque_cutout_v: Rect::default(),
711                        text_layout_idx: layout_idx,
712                    });
713                }
714                DrawCommand::TextCaret {
715                    content_rect,
716                    text,
717                    style,
718                    color,
719                    multiline,
720                    ..
721                } => {
722                    if color.get_a() == 0 {
723                        continue;
724                    }
725                    let phys_content: Rect = Self::scale_rect(*content_rect, scale);
726                    let Some(vis) = phys_content.intersect(active_clip) else {
727                        continue;
728                    };
729                    let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
730                    let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
731                    if y0 >= y1 {
732                        continue;
733                    }
734                    let max_w: Option<f32> = if *multiline {
735                        Some(content_rect.get_width().max(1.0))
736                    } else {
737                        None
738                    };
739                    let layout: TextLayoutResult = measurer.measure(text, *style, max_w);
740                    let phys_font_size: f32 = style.get_font_size() * scale;
741                    for line in layout.get_lines().iter() {
742                        for ch in line.get_text().chars() {
743                            if ch != ' ' {
744                                let key: GlyphKey =
745                                    GlyphKey::from_text_style(ch, phys_font_size, *style);
746                                let _: &RasterizedGlyph =
747                                    glyph_atlas.get_or_rasterize_with(key, font_provider);
748                            }
749                        }
750                    }
751                    let layout_idx: u32 = text_layouts.len() as u32;
752                    text_layouts.push(layout);
753                    prepped.push(PreppedCommand {
754                        cmd_index,
755                        active_clip,
756                        y0,
757                        y1,
758                        opaque_cutout_h: Rect::default(),
759                        opaque_cutout_v: Rect::default(),
760                        text_layout_idx: layout_idx,
761                    });
762                }
763                DrawCommand::Line {
764                    from, to, width, ..
765                } => {
766                    let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
767                    let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
768                    let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
769                    let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
770                    let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
771                    if let Some(vis) =
772                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
773                    {
774                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
775                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
776                        if y0 < y1 {
777                            prepped.push(PreppedCommand {
778                                cmd_index,
779                                active_clip,
780                                y0,
781                                y1,
782                                opaque_cutout_h: Rect::default(),
783                                opaque_cutout_v: Rect::default(),
784                                text_layout_idx: u32::MAX,
785                            });
786                        }
787                    }
788                }
789                DrawCommand::Circle { center, radius, .. } => {
790                    let r: f32 = radius * scale + 1.0;
791                    let bounds: Rect = Rect::new(
792                        center.get_x() * scale - r,
793                        center.get_y() * scale - r,
794                        r * 2.0,
795                        r * 2.0,
796                    );
797                    if let Some(vis) = bounds.intersect(active_clip) {
798                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
799                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
800                        if y0 < y1 {
801                            prepped.push(PreppedCommand {
802                                cmd_index,
803                                active_clip,
804                                y0,
805                                y1,
806                                opaque_cutout_h: Rect::default(),
807                                opaque_cutout_v: Rect::default(),
808                                text_layout_idx: u32::MAX,
809                            });
810                        }
811                    }
812                }
813                DrawCommand::Triangle { p0, p1, p2, .. } => {
814                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
815                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
816                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
817                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
818                    if let Some(vis) =
819                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
820                    {
821                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
822                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
823                        if y0 < y1 {
824                            prepped.push(PreppedCommand {
825                                cmd_index,
826                                active_clip,
827                                y0,
828                                y1,
829                                opaque_cutout_h: Rect::default(),
830                                opaque_cutout_v: Rect::default(),
831                                text_layout_idx: u32::MAX,
832                            });
833                        }
834                    }
835                }
836            }
837        }
838        (prepped, text_layouts)
839    }
840
841    /// Computes two strictly-interior opaque cutout rectangles `(horizontal_bar, vertical_bar)` if the next command is an opaque `FillRoundedRect`.
842    ///
843    /// # Arguments
844    ///
845    /// - `Option<&DrawCommand>` - Immediately following command in the display list.
846    /// - `f32` - Active DPI scale factor.
847    ///
848    /// # Returns
849    ///
850    /// - `(Rect, Rect)` - Opaque inner rectangles safely skipped by `raster_shadow` with zero visual change.
851    #[must_use]
852    fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
853        let Some(DrawCommand::FillRoundedRect {
854            rect,
855            color,
856            radius,
857            ..
858        }) = next_cmd
859        else {
860            return (Rect::default(), Rect::default());
861        };
862        if color.get_a() != 255 {
863            return (Rect::default(), Rect::default());
864        }
865        let phys: Rect = snap_physical_rect(*rect, scale);
866        let r_max: f32 = Self::scale_radius(*radius, scale)
867            .max_radius()
868            .min(phys.get_width() * 0.5)
869            .min(phys.get_height() * 0.5);
870        let pad: f32 = 1.5;
871        let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
872        let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
873        let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
874            Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
875        } else {
876            Rect::default()
877        };
878        let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
879        let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
880        let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
881            Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
882        } else {
883            Rect::default()
884        };
885        (cut_h, cut_v)
886    }
887
888    /// Executes all prepped commands overlapping `band`'s vertical slice `[y_offset, y_end)` completely lock-free.
889    ///
890    /// # Arguments
891    ///
892    /// - `&mut PixelBand<'_>` - Disjoint mutable horizontal pixel band.
893    /// - `&[DrawCommand]` - Full frame draw command slice.
894    /// - `&[PreppedCommand]` - Pre-clipped command list.
895    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
896    /// - `&GlyphAtlas` - Immutable pre-warmed glyph atlas.
897    /// - `f32` - Active DPI scale factor.
898    /// - `AntialiasingMode` - Active anti-aliasing policy.
899    ///
900    /// # Returns
901    ///
902    /// - `usize` - Total shaded pixels in this band.
903    pub(crate) fn render_band(
904        band: &mut PixelBand<'_>,
905        commands: &[DrawCommand],
906        prepped: &[PreppedCommand],
907        text_layouts: &[TextLayoutResult],
908        glyph_atlas: &GlyphAtlas,
909        scale: f32,
910        aa: AntialiasingMode,
911    ) -> usize {
912        let band_y0: u32 = band.y_offset();
913        let band_y1: u32 = band.y_end();
914        let band_rect: Rect = Rect::new(
915            0.0,
916            band_y0 as f32,
917            band.width() as f32,
918            (band_y1 - band_y0) as f32,
919        );
920        let mut shaded: usize = 0;
921        for item in prepped.iter() {
922            if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
923                continue;
924            }
925            let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
926                continue;
927            };
928            let cmd: &DrawCommand = &commands[item.get_cmd_index()];
929            shaded += match cmd {
930                DrawCommand::Clear(color) => {
931                    if active_clip.get_x() <= 0.0
932                        && active_clip.get_width() >= (band.width() as f32)
933                        && active_clip.get_y() <= (band_y0 as f32)
934                        && active_clip.bottom() >= (band_y1 as f32)
935                    {
936                        band.clear(*color);
937                        (band.width() as usize) * ((band_y1 - band_y0) as usize)
938                    } else {
939                        Self::fill_rect_clipped(band, active_clip, *color, active_clip)
940                    }
941                }
942                DrawCommand::FillRoundedRect {
943                    rect,
944                    color,
945                    radius,
946                    border,
947                } => {
948                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
949                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
950                    let bw: f32 = if border.get_width() > 0.0 {
951                        (border.get_width() * scale).max(1.0)
952                    } else {
953                        0.0
954                    };
955                    let phys_border: Border = Border::new(bw, border.get_color());
956                    Self::raster_rounded_rect(
957                        band,
958                        phys_rect,
959                        *color,
960                        phys_radius,
961                        phys_border,
962                        active_clip,
963                        aa,
964                    )
965                }
966                DrawCommand::LinearGradientRect {
967                    rect,
968                    gradient,
969                    radius,
970                } => {
971                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
972                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
973                    Self::raster_gradient_rect(
974                        band,
975                        phys_rect,
976                        *gradient,
977                        phys_radius,
978                        active_clip,
979                        aa,
980                    )
981                }
982                DrawCommand::BoxShadow {
983                    rect,
984                    radius,
985                    shadow,
986                } => {
987                    let spread: f32 = shadow.get_spread_radius() * scale;
988                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
989                    let sigma: f32 = (blur * 0.5).max(0.75);
990                    let pad: f32 = (sigma * 3.0).ceil();
991                    let base_rect: Rect = snap_physical_rect(*rect, scale);
992                    let caster_rect: Rect = Rect::new(
993                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
994                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
995                        (base_rect.get_width() + spread * 2.0).max(1.0),
996                        (base_rect.get_height() + spread * 2.0).max(1.0),
997                    );
998                    let shadow_rect: Rect = Rect::new(
999                        caster_rect.get_x() - pad,
1000                        caster_rect.get_y() - pad,
1001                        caster_rect.get_width() + pad * 2.0,
1002                        caster_rect.get_height() + pad * 2.0,
1003                    );
1004                    let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
1005                    let phys_radius: CornerRadius = CornerRadius::new(
1006                        (raw_r.get_top_left() + spread).max(0.0),
1007                        (raw_r.get_top_right() + spread).max(0.0),
1008                        (raw_r.get_bottom_right() + spread).max(0.0),
1009                        (raw_r.get_bottom_left() + spread).max(0.0),
1010                    );
1011                    Self::raster_shadow(
1012                        band,
1013                        (shadow_rect, caster_rect, active_clip),
1014                        phys_radius,
1015                        sigma,
1016                        shadow.get_color(),
1017                        (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
1018                    )
1019                }
1020                DrawCommand::TextRun { rect, style, .. } => {
1021                    let lidx: usize = item.get_text_layout_idx() as usize;
1022                    if let Some(layout) = text_layouts.get(lidx) {
1023                        Self::raster_text_run_band(
1024                            band,
1025                            *rect,
1026                            layout,
1027                            *style,
1028                            scale,
1029                            active_clip,
1030                            glyph_atlas,
1031                        )
1032                    } else {
1033                        0
1034                    }
1035                }
1036                DrawCommand::TextCaret {
1037                    text_rect,
1038                    content_rect,
1039                    style,
1040                    caret_height,
1041                    color,
1042                    multiline,
1043                    ..
1044                } => {
1045                    let lidx: usize = item.get_text_layout_idx() as usize;
1046                    let phys_font_size: f32 = style.get_font_size() * scale;
1047                    let letter_sp: f32 = style.get_letter_spacing() * scale;
1048                    let space_adv: f32 = measure_char_advance(' ', *style) * scale;
1049                    let glyphs: &HashMap<GlyphKey, RasterizedGlyph> = glyph_atlas.get_glyphs();
1050                    let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
1051                        if let Some(layout) = text_layouts.get(lidx) {
1052                            let lh: f32 = layout.get_line_height_px() * scale;
1053                            let idx: usize = layout.get_lines().len().saturating_sub(1);
1054                            let w_phys: f32 = layout
1055                                .get_lines()
1056                                .last()
1057                                .map(|line: &TextLine| {
1058                                    let mut acc: f32 = 0.0;
1059                                    for ch in line.get_text().chars() {
1060                                        if ch == ' ' {
1061                                            acc += space_adv + letter_sp;
1062                                        } else {
1063                                            let key: GlyphKey = GlyphKey::from_text_style(
1064                                                ch,
1065                                                phys_font_size,
1066                                                *style,
1067                                            );
1068                                            let adv: f32 = glyphs
1069                                                .get(&key)
1070                                                .map(|g: &RasterizedGlyph| {
1071                                                    (g.get_advance() as f32).max(1.0)
1072                                                })
1073                                                .unwrap_or(space_adv);
1074                                            acc += adv + letter_sp;
1075                                        }
1076                                    }
1077                                    acc
1078                                })
1079                                .unwrap_or(0.0);
1080                            (w_phys, idx, lh)
1081                        } else {
1082                            (
1083                                0.0,
1084                                0,
1085                                (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
1086                            )
1087                        };
1088                    let caret_h_phys: f32 = (caret_height * scale).max(2.0);
1089                    let caret_w_phys: f32 = (1.5 * scale).max(1.5);
1090                    let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0)
1091                        .max(content_rect.get_x() * scale);
1092                    let caret_x_phys: f32 =
1093                        (text_rect.get_x() * scale + last_w_phys + 1.5 * scale).min(max_x);
1094                    let caret_y_phys: f32 = if *multiline {
1095                        let raw_y: f32 = content_rect.get_y() * scale
1096                            + (line_idx as f32) * line_h_phys
1097                            + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
1098                        raw_y
1099                            .min(content_rect.bottom() * scale - caret_h_phys)
1100                            .max(content_rect.get_y() * scale)
1101                    } else {
1102                        content_rect.get_y() * scale
1103                            + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
1104                    };
1105                    let caret_rect: Rect = Rect::new(
1106                        caret_x_phys.round(),
1107                        caret_y_phys.round(),
1108                        caret_w_phys.round().max(1.0),
1109                        caret_h_phys.round().max(2.0),
1110                    );
1111                    Self::raster_rounded_rect(
1112                        band,
1113                        caret_rect,
1114                        *color,
1115                        CornerRadius::all(0.5 * scale),
1116                        Border::default(),
1117                        active_clip,
1118                        aa,
1119                    )
1120                }
1121                DrawCommand::Image {
1122                    rect,
1123                    buffer,
1124                    radius,
1125                } => {
1126                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
1127                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
1128                    Self::raster_image(band, phys_rect, buffer, phys_radius, active_clip, aa)
1129                }
1130                DrawCommand::Line {
1131                    from,
1132                    to,
1133                    color,
1134                    width,
1135                } => {
1136                    let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
1137                    let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
1138                    Self::raster_line(
1139                        band,
1140                        p0,
1141                        p1,
1142                        *color,
1143                        (width * scale).max(1.0),
1144                        active_clip,
1145                        aa,
1146                    )
1147                }
1148                DrawCommand::Circle {
1149                    center,
1150                    radius,
1151                    color,
1152                } => {
1153                    let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
1154                    Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
1155                }
1156                DrawCommand::Triangle { p0, p1, p2, color } => {
1157                    let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
1158                    let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
1159                    let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
1160                    Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
1161                }
1162                DrawCommand::SpriteRegion {
1163                    rect,
1164                    buffer,
1165                    src_rect,
1166                    tint,
1167                } => {
1168                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
1169                    Self::raster_sprite_region(
1170                        band,
1171                        phys_rect,
1172                        buffer,
1173                        *src_rect,
1174                        *tint,
1175                        active_clip,
1176                        aa,
1177                    )
1178                }
1179                DrawCommand::PushClip(_) | DrawCommand::PopClip => 0,
1180            };
1181        }
1182        shaded
1183    }
1184
1185    /// Scales a logical rectangle into physical pixels.
1186    ///
1187    /// # Arguments
1188    ///
1189    /// - `Rect` - Logical rectangle.
1190    /// - `f32` - Scale factor.
1191    ///
1192    /// # Returns
1193    ///
1194    /// - `Rect` - Physical pixel rectangle.
1195    fn scale_rect(rect: Rect, scale: f32) -> Rect {
1196        Rect::new(
1197            rect.get_x() * scale,
1198            rect.get_y() * scale,
1199            rect.get_width() * scale,
1200            rect.get_height() * scale,
1201        )
1202    }
1203
1204    /// Scales logical corner radii into physical pixel radii.
1205    ///
1206    /// # Arguments
1207    ///
1208    /// - `CornerRadius` - Logical corner radii.
1209    /// - `f32` - Scale factor.
1210    ///
1211    /// # Returns
1212    ///
1213    /// - `CornerRadius` - Physical corner radii.
1214    fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
1215        CornerRadius::new(
1216            radius.get_top_left() * scale,
1217            radius.get_top_right() * scale,
1218            radius.get_bottom_right() * scale,
1219            radius.get_bottom_left() * scale,
1220        )
1221    }
1222
1223    /// Fast axis-aligned solid rectangle fill clipped against `clip`.
1224    ///
1225    /// # Arguments
1226    ///
1227    /// - `&mut PixelBand<'_>` - Target pixel band.
1228    /// - `Rect` - Physical rectangle.
1229    /// - `Color` - Fill color.
1230    /// - `Rect` - Active clip rectangle.
1231    ///
1232    /// # Returns
1233    ///
1234    /// - `usize` - Number of pixels shaded.
1235    fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
1236        if color.get_a() == 0 {
1237            return 0;
1238        }
1239        let Some(vis) = rect.intersect(clip) else {
1240            return 0;
1241        };
1242        let fb_w: u32 = band.width();
1243        let band_y0: u32 = band.y_offset();
1244        let band_y1: u32 = band.y_end();
1245        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1246        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1247        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1248        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1249        if x0 >= x1 || y0 >= y1 {
1250            return 0;
1251        }
1252        let span_len: usize = (x1 - x0) as usize;
1253        let rows: usize = (y1 - y0) as usize;
1254        let sa: u8 = color.get_a();
1255        if sa < 255 && span_len.saturating_mul(rows) >= 512 {
1256            let luts: ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) = build_linear_blend_luts(color);
1257            for y in y0..y1 {
1258                band.fill_span_linear_luts(x0, x1, y, &luts);
1259            }
1260        } else {
1261            for y in y0..y1 {
1262                band.fill_span_linear(x0, x1, y, color);
1263            }
1264        }
1265        span_len * rows
1266    }
1267
1268    /// Rasterizes a rounded rectangle with optional border using edge-bounded 4x4 RGSS supersampling and linear-light spans.
1269    ///
1270    /// # Arguments
1271    ///
1272    /// - `&mut PixelBand<'_>` - Target pixel band.
1273    /// - `Rect` - Physical rectangle bounds.
1274    /// - `Color` - Fill color.
1275    /// - `CornerRadius` - Physical corner radii.
1276    /// - `Border` - Physical border specification.
1277    /// - `Rect` - Active clip bounds.
1278    /// - `AntialiasingMode` - Active AA policy.
1279    ///
1280    /// # Returns
1281    ///
1282    /// - `usize` - Number of pixels shaded.
1283    fn raster_rounded_rect(
1284        band: &mut PixelBand<'_>,
1285        rect: Rect,
1286        color: Color,
1287        radius: CornerRadius,
1288        border: Border,
1289        clip: Rect,
1290        aa: AntialiasingMode,
1291    ) -> usize {
1292        let Some(vis) = rect.intersect(clip) else {
1293            return 0;
1294        };
1295        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1296        if radius.max_radius() <= 0.0 && !has_border {
1297            return Self::fill_rect_clipped(band, rect, color, clip);
1298        }
1299        let half_w: f32 = rect.get_width() * 0.5;
1300        let half_h: f32 = rect.get_height() * 0.5;
1301        let cx: f32 = rect.get_x() + half_w;
1302        let cy: f32 = rect.get_y() + half_h;
1303        let border_w: f32 = border.get_width();
1304        let fb_w: u32 = band.width();
1305        let band_y0: u32 = band.y_offset();
1306        let band_y1: u32 = band.y_end();
1307        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1308        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1309        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1310        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1311        let safe_inset: f32 = radius.max_radius().max(border_w) + 1.5;
1312        let edge_inset: f32 = border_w + 1.5;
1313        let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1314        let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
1315        let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1316        let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
1317        let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1318        let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
1319        let has_interior: bool = iy0 < iy1 && ix0 < ix1;
1320        let has_center_band: bool = cx0 < cx1;
1321        let interior_luts: Option<RgbaLutQuad> = if has_interior
1322            && color.get_a() > 0
1323            && color.get_a() < 255
1324            && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
1325        {
1326            Some(build_linear_blend_luts(color))
1327        } else {
1328            None
1329        };
1330        let mut shaded: usize = 0;
1331        for y in y0..y1 {
1332            let py: f32 = (y as f32) + 0.5 - cy;
1333            let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
1334            if has_interior && y >= iy0 && y < iy1 {
1335                for x in x0..ix0 {
1336                    shaded += Self::shade_rounded_pixel(
1337                        band,
1338                        (x, y),
1339                        box_geom,
1340                        radius,
1341                        color,
1342                        border,
1343                        aa,
1344                    );
1345                }
1346                if color.get_a() > 0 {
1347                    if let Some(ref luts) = interior_luts {
1348                        band.fill_span_linear_luts(ix0, ix1, y, luts);
1349                    } else {
1350                        band.fill_span_linear(ix0, ix1, y, color);
1351                    }
1352                    shaded += (ix1 - ix0) as usize;
1353                }
1354                for x in ix1..x1 {
1355                    shaded += Self::shade_rounded_pixel(
1356                        band,
1357                        (x, y),
1358                        box_geom,
1359                        radius,
1360                        color,
1361                        border,
1362                        aa,
1363                    );
1364                }
1365            } else if has_center_band {
1366                for x in x0..cx0 {
1367                    shaded += Self::shade_rounded_pixel(
1368                        band,
1369                        (x, y),
1370                        box_geom,
1371                        radius,
1372                        color,
1373                        border,
1374                        aa,
1375                    );
1376                }
1377                let dist_y: f32 = py.abs() - half_h;
1378                let outer_cov: f32 = sdf_coverage(dist_y, aa);
1379                if outer_cov > 0.0 {
1380                    if has_border {
1381                        let inner_hh: f32 = (half_h - border_w).max(0.0);
1382                        let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
1383                            sdf_coverage(py.abs() - inner_hh, aa)
1384                        } else {
1385                            0.0
1386                        };
1387                        let mixed: Color = composite_fill_and_border(
1388                            color,
1389                            border.get_color(),
1390                            outer_cov,
1391                            inner_cov,
1392                        );
1393                        if mixed.get_a() > 0 {
1394                            band.fill_span_linear(cx0, cx1, y, mixed);
1395                        }
1396                        shaded += (cx1 - cx0) as usize;
1397                    } else if color.get_a() > 0 {
1398                        band.fill_span_linear(cx0, cx1, y, color.multiply_alpha(outer_cov));
1399                        shaded += (cx1 - cx0) as usize;
1400                    }
1401                }
1402                for x in cx1..x1 {
1403                    shaded += Self::shade_rounded_pixel(
1404                        band,
1405                        (x, y),
1406                        box_geom,
1407                        radius,
1408                        color,
1409                        border,
1410                        aa,
1411                    );
1412                }
1413            } else {
1414                for x in x0..x1 {
1415                    shaded += Self::shade_rounded_pixel(
1416                        band,
1417                        (x, y),
1418                        box_geom,
1419                        radius,
1420                        color,
1421                        border,
1422                        aa,
1423                    );
1424                }
1425            }
1426        }
1427        shaded
1428    }
1429
1430    /// Evaluates fast early-rejected analytical SDF and edge-only 4x4 RGSS coverage for a single edge/corner pixel.
1431    ///
1432    /// # Arguments
1433    ///
1434    /// - `&mut PixelBand<'_>` - Target pixel band.
1435    /// - `(u32, u32)` - Global pixel `(x, y)` coordinates.
1436    /// - `(f32, f32, f32, f32)` - Box geometry `(center_x, rel_py, half_w, half_h)`.
1437    /// - `CornerRadius` - Physical corner radii.
1438    /// - `Color` - Fill color.
1439    /// - `Border` - Border width and color.
1440    /// - `AntialiasingMode` - Active AA policy.
1441    ///
1442    /// # Returns
1443    ///
1444    /// - `usize` - `1` if the pixel was shaded, `0` otherwise.
1445    fn shade_rounded_pixel(
1446        band: &mut PixelBand<'_>,
1447        pos: (u32, u32),
1448        geom: (f32, f32, f32, f32),
1449        radius: CornerRadius,
1450        color: Color,
1451        border: Border,
1452        aa: AntialiasingMode,
1453    ) -> usize {
1454        let (x, y): (u32, u32) = pos;
1455        let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
1456        let px: f32 = (x as f32) + 0.5 - cx;
1457        let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1458            .min(half_w)
1459            .min(half_h);
1460        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1461        if dist > 0.85 {
1462            return 0;
1463        }
1464        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1465        let bw: f32 = if has_border { border.get_width() } else { 0.0 };
1466        if !has_border {
1467            if dist < -0.85 {
1468                if color.get_a() > 0 {
1469                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
1470                    return 1;
1471                }
1472                return 0;
1473            }
1474            let in_corner_edge: bool = aa != AntialiasingMode::None
1475                && corner_r > 0.5
1476                && px.abs() > (half_w - corner_r - 1.5)
1477                && py.abs() > (half_h - corner_r - 1.5);
1478            let outer_cov: f32 = if in_corner_edge {
1479                rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1480            } else {
1481                sdf_coverage(dist, aa)
1482            };
1483            if outer_cov > 0.0 && color.get_a() > 0 {
1484                let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
1485                band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
1486                return 1;
1487            }
1488            return 0;
1489        }
1490        if dist < -(bw + 0.85) {
1491            if color.get_a() > 0 {
1492                band.blend_pixel_linear_dithered(x, y, color, 0.0);
1493                return 1;
1494            }
1495            return 0;
1496        }
1497        let inner_hw: f32 = (half_w - bw).max(0.0);
1498        let inner_hh: f32 = (half_h - bw).max(0.0);
1499        let inner_r: f32 = (corner_r - bw).max(0.0);
1500        let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1501            rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
1502        } else {
1503            2.0
1504        };
1505        if dist < -0.85 && inner_dist > 0.85 {
1506            band.blend_pixel_linear_dithered(x, y, border.get_color(), 0.0);
1507            return 1;
1508        }
1509        let in_corner_zone: bool = aa != AntialiasingMode::None
1510            && corner_r > 0.5
1511            && px.abs() > (half_w - corner_r - 1.5)
1512            && py.abs() > (half_h - corner_r - 1.5);
1513        let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
1514            rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
1515        } else {
1516            let oc: f32 = sdf_coverage(dist, aa);
1517            if oc <= 0.0 {
1518                return 0;
1519            }
1520            let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1521                sdf_coverage(inner_dist, aa)
1522            } else {
1523                0.0
1524            };
1525            (oc, ic)
1526        };
1527        if outer_cov <= 0.0 {
1528            return 0;
1529        }
1530        let mixed: Color =
1531            composite_fill_and_border(color, border.get_color(), outer_cov, inner_cov);
1532        if mixed.get_a() > 0 {
1533            band.blend_pixel_linear_dithered(x, y, mixed, 0.0);
1534            return 1;
1535        }
1536        0
1537    }
1538
1539    /// Rasterizes a two-stop linear gradient inside an SDF rounded rectangle with edge-bounded RGSS and IGN dithering.
1540    ///
1541    /// # Arguments
1542    ///
1543    /// - `&mut PixelBand<'_>` - Target pixel band.
1544    /// - `Rect` - Physical bounds.
1545    /// - `LinearGradient` - Gradient angle and stops.
1546    /// - `CornerRadius` - Physical corner radii.
1547    /// - `Rect` - Active clip bounds.
1548    /// - `AntialiasingMode` - Active AA policy.
1549    ///
1550    /// # Returns
1551    ///
1552    /// - `usize` - Shaded pixel count.
1553    fn raster_gradient_rect(
1554        band: &mut PixelBand<'_>,
1555        rect: Rect,
1556        gradient: LinearGradient,
1557        radius: CornerRadius,
1558        clip: Rect,
1559        aa: AntialiasingMode,
1560    ) -> usize {
1561        let Some(vis) = rect.intersect(clip) else {
1562            return 0;
1563        };
1564        let rad: f32 = gradient.get_angle_deg().to_radians();
1565        let dir_x: f32 = rad.sin();
1566        let dir_y: f32 = rad.cos();
1567        let half_w: f32 = rect.get_width() * 0.5;
1568        let half_h: f32 = rect.get_height() * 0.5;
1569        let cx: f32 = rect.get_x() + half_w;
1570        let cy: f32 = rect.get_y() + half_h;
1571        let inv_w: f32 = if rect.get_width() > 0.0 {
1572            1.0 / rect.get_width()
1573        } else {
1574            0.0
1575        };
1576        let inv_h: f32 = if rect.get_height() > 0.0 {
1577            1.0 / rect.get_height()
1578        } else {
1579            0.0
1580        };
1581        let fb_w: u32 = band.width();
1582        let band_y0: u32 = band.y_offset();
1583        let band_y1: u32 = band.y_end();
1584        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1585        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1586        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1587        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1588        let mut shaded: usize = 0;
1589        for y in y0..y1 {
1590            let py: f32 = (y as f32) + 0.5 - cy;
1591            let ny: f32 = ((y as f32) - rect.get_y()) * inv_h;
1592            for x in x0..x1 {
1593                let px: f32 = (x as f32) + 0.5 - cx;
1594                let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1595                    .min(half_w)
1596                    .min(half_h);
1597                let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1598                if dist > 0.85 {
1599                    continue;
1600                }
1601                let cov: f32 = if dist < -0.85 {
1602                    1.0
1603                } else {
1604                    let in_corner: bool = aa != AntialiasingMode::None
1605                        && corner_r > 0.5
1606                        && px.abs() > (half_w - corner_r - 1.5)
1607                        && py.abs() > (half_h - corner_r - 1.5);
1608                    if in_corner {
1609                        rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1610                    } else {
1611                        sdf_coverage(dist, aa)
1612                    }
1613                };
1614                if cov <= 0.0 {
1615                    continue;
1616                }
1617                let nx: f32 = ((x as f32) - rect.get_x()) * inv_w;
1618                let t: f32 = ((nx - 0.5) * dir_x + (ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
1619                let base_sample: Color =
1620                    gradient.get_start_color().lerp(gradient.get_end_color(), t);
1621                let alpha_f: f32 = ((base_sample.get_a() as f32) * (1.0 / 255.0)) * cov;
1622                let dither: f32 = interleaved_gradient_noise(x, y);
1623                band.blend_pixel_f32_dithered(x, y, base_sample, alpha_f, dither);
1624                shaded += 1;
1625            }
1626        }
1627        shaded
1628    }
1629
1630    /// Computes the horizontal opaque-interior skip interval `[cut_x0, cut_x1)` for shadow row `y`.
1631    ///
1632    /// # Arguments
1633    ///
1634    /// - `u32` - Global physical Y row.
1635    /// - `(Rect, Rect)` - Opaque cutout cross `(horizontal_bar, vertical_bar)`.
1636    /// - `u32` - Clamped row start X.
1637    /// - `u32` - Clamped row end X.
1638    ///
1639    /// # Returns
1640    ///
1641    /// - `(u32, u32)` - Opaque X span safely skippable on row `y`.
1642    #[must_use]
1643    fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
1644        let (cut_h, cut_v): (Rect, Rect) = cutouts;
1645        let yf: f32 = (y as f32) + 0.5;
1646        if cut_h.get_width() > 0.0
1647            && cut_h.get_height() > 0.0
1648            && yf >= cut_h.get_y()
1649            && yf < cut_h.bottom()
1650        {
1651            let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1652            let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
1653            return (cx0, cx1);
1654        }
1655        if cut_v.get_width() > 0.0
1656            && cut_v.get_height() > 0.0
1657            && yf >= cut_v.get_y()
1658            && yf < cut_v.bottom()
1659        {
1660            let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1661            let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
1662            return (cx0, cx1);
1663        }
1664        (x1, x1)
1665    }
1666
1667    /// Rasterizes a lossless 2D analytical Gaussian `erfc` LUT drop shadow skipping strictly-opaque card interiors.
1668    ///
1669    /// # Arguments
1670    ///
1671    /// - `&mut PixelBand<'_>` - Target pixel band.
1672    /// - `(Rect, Rect, Rect)` - Tuple `(shadow_rect, caster_rect, clip)` in physical pixels.
1673    /// - `CornerRadius` - Per-quadrant physical corner radii.
1674    /// - `f32` - Gaussian standard deviation `sigma` in physical pixels.
1675    /// - `Color` - Shadow tint color.
1676    /// - `(Rect, Rect)` - Strictly-opaque interior cutout rectangles from immediately following opaque card.
1677    ///
1678    /// # Returns
1679    ///
1680    /// - `usize` - Shaded pixel count.
1681    fn raster_shadow(
1682        band: &mut PixelBand<'_>,
1683        rects: (Rect, Rect, Rect),
1684        radius: CornerRadius,
1685        sigma: f32,
1686        color: Color,
1687        cutouts: (Rect, Rect),
1688    ) -> usize {
1689        let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
1690        if color.get_a() == 0 {
1691            return 0;
1692        }
1693        let Some(vis) = shadow_rect.intersect(clip) else {
1694            return 0;
1695        };
1696        let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
1697        let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
1698        let cx: f32 = caster_rect.get_x() + half_w;
1699        let cy: f32 = caster_rect.get_y() + half_h;
1700        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
1701        let inv_sigma: f32 = 1.0 / sigma.max(0.5);
1702        let cutoff: f32 = sigma * 3.0;
1703        let fb_w: u32 = band.width();
1704        let band_y0: u32 = band.y_offset();
1705        let band_y1: u32 = band.y_end();
1706        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1707        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1708        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1709        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1710        let r_max: f32 = radius.max_radius();
1711        let inner_inset: f32 = cutoff + r_max;
1712        let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1713        let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
1714        let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1715        let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
1716        let has_mid_x: bool = sx0 < sx1;
1717        let has_mid_y: bool = sy0 < sy1;
1718        let mut shaded: usize = 0;
1719        for y in y0..y1 {
1720            let py: f32 = (y as f32) + 0.5 - cy;
1721            let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, x0, x1);
1722            let spans: [(u32, u32); 2] = if cut0 < cut1 {
1723                [(x0, cut0), (cut1, x1)]
1724            } else {
1725                [(x0, x1), (x1, x1)]
1726            };
1727            if has_mid_x && has_mid_y && y >= sy0 && y < sy1 {
1728                for (rx0, rx1) in spans.into_iter() {
1729                    let left_end: u32 = rx1.min(sx0);
1730                    for x in rx0..left_end {
1731                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1732                        if dist < cutoff {
1733                            let alpha_f: f32 =
1734                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1735                            if alpha_f > 0.0005 {
1736                                band.blend_pixel_f32_dithered(
1737                                    x,
1738                                    y,
1739                                    color,
1740                                    alpha_f,
1741                                    interleaved_gradient_noise(x, y),
1742                                );
1743                                shaded += 1;
1744                            }
1745                        }
1746                    }
1747                    let right_start: u32 = rx0.max(sx1);
1748                    for x in right_start..rx1 {
1749                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1750                        if dist < cutoff {
1751                            let alpha_f: f32 =
1752                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1753                            if alpha_f > 0.0005 {
1754                                band.blend_pixel_f32_dithered(
1755                                    x,
1756                                    y,
1757                                    color,
1758                                    alpha_f,
1759                                    interleaved_gradient_noise(x, y),
1760                                );
1761                                shaded += 1;
1762                            }
1763                        }
1764                    }
1765                }
1766            } else if has_mid_x {
1767                let dist_y: f32 = py.abs() - half_h;
1768                let mid_alpha: f32 = if dist_y < cutoff {
1769                    base_alpha * fast_gaussian_shadow_falloff(dist_y, inv_sigma)
1770                } else {
1771                    0.0
1772                };
1773                for (rx0, rx1) in spans.into_iter() {
1774                    if rx0 >= rx1 {
1775                        continue;
1776                    }
1777                    let l_end: u32 = rx1.min(sx0);
1778                    for x in rx0..l_end {
1779                        let px: f32 = (x as f32) + 0.5 - cx;
1780                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1781                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1782                        if dist < cutoff {
1783                            let alpha_f: f32 =
1784                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1785                            if alpha_f > 0.0005 {
1786                                band.blend_pixel_f32_dithered(
1787                                    x,
1788                                    y,
1789                                    color,
1790                                    alpha_f,
1791                                    interleaved_gradient_noise(x, y),
1792                                );
1793                                shaded += 1;
1794                            }
1795                        }
1796                    }
1797                    let m_start: u32 = rx0.max(sx0);
1798                    let m_end: u32 = rx1.min(sx1);
1799                    if mid_alpha > 0.0005 && m_start < m_end {
1800                        band.blend_shadow_span_const_alpha(m_start, m_end, y, color, mid_alpha);
1801                        shaded += (m_end - m_start) as usize;
1802                    }
1803                    let r_start: u32 = rx0.max(sx1);
1804                    for x in r_start..rx1 {
1805                        let px: f32 = (x as f32) + 0.5 - cx;
1806                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1807                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1808                        if dist < cutoff {
1809                            let alpha_f: f32 =
1810                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1811                            if alpha_f > 0.0005 {
1812                                band.blend_pixel_f32_dithered(
1813                                    x,
1814                                    y,
1815                                    color,
1816                                    alpha_f,
1817                                    interleaved_gradient_noise(x, y),
1818                                );
1819                                shaded += 1;
1820                            }
1821                        }
1822                    }
1823                }
1824            } else {
1825                for (rx0, rx1) in spans.into_iter() {
1826                    for x in rx0..rx1 {
1827                        let px: f32 = (x as f32) + 0.5 - cx;
1828                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1829                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1830                        if dist >= cutoff {
1831                            continue;
1832                        }
1833                        let alpha_f: f32 =
1834                            base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1835                        if alpha_f > 0.0005 {
1836                            band.blend_pixel_f32_dithered(
1837                                x,
1838                                y,
1839                                color,
1840                                alpha_f,
1841                                interleaved_gradient_noise(x, y),
1842                            );
1843                            shaded += 1;
1844                        }
1845                    }
1846                }
1847            }
1848        }
1849        shaded
1850    }
1851
1852    /// Rasterizes a pre-measured UTF-8 text run into `band` using the immutable pre-warmed `GlyphAtlas`.
1853    ///
1854    /// # Arguments
1855    ///
1856    /// - `&mut PixelBand<'_>` - Target pixel band.
1857    /// - `Rect` - Logical text bounding box.
1858    /// - `&TextLayoutResult` - Pre-measured wrapped lines.
1859    /// - `TextStyle` - Typography style.
1860    /// - `f32` - Active DPI scale factor.
1861    /// - `Rect` - Active physical clip bounds.
1862    /// - `&GlyphAtlas` - Read-only pre-warmed glyph atlas.
1863    ///
1864    /// # Returns
1865    ///
1866    /// - `usize` - Shaded pixel count.
1867    fn raster_text_run_band(
1868        band: &mut PixelBand<'_>,
1869        rect: Rect,
1870        layout: &TextLayoutResult,
1871        style: TextStyle,
1872        scale: f32,
1873        clip: Rect,
1874        glyph_atlas: &GlyphAtlas,
1875    ) -> usize {
1876        let phys_font_size: f32 = style.get_font_size() * scale;
1877        let line_h_phys: f32 = layout.get_line_height_px() * scale;
1878        let box_w_phys: f32 = rect.get_width() * scale;
1879        let color: Color = style.get_color();
1880        let fb_w: i32 = band.width() as i32;
1881        let band_y0: i32 = band.y_offset() as i32;
1882        let band_y1: i32 = band.y_end() as i32;
1883        let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
1884        let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
1885        let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
1886        let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
1887        if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
1888            return 0;
1889        }
1890        let letter_sp: f32 = style.get_letter_spacing() * scale;
1891        let space_adv: f32 = measure_char_advance(' ', style) * scale;
1892        let glyphs: &HashMap<GlyphKey, RasterizedGlyph> = glyph_atlas.get_glyphs();
1893        let mut shaded: usize = 0;
1894        for (line_idx, line) in layout.get_lines().iter().enumerate() {
1895            let pen_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h_phys;
1896            if (pen_y + line_h_phys) < (clip_y0 as f32) || pen_y > (clip_y1 as f32) {
1897                continue;
1898            }
1899            let align_x: f32 = match style.get_align() {
1900                TextAlign::Left => 0.0,
1901                TextAlign::Center | TextAlign::Right => {
1902                    let mut line_w_phys: f32 = 0.0;
1903                    for ch in line.get_text().chars() {
1904                        if ch == ' ' {
1905                            line_w_phys += space_adv + letter_sp;
1906                        } else {
1907                            let key: GlyphKey =
1908                                GlyphKey::from_text_style(ch, phys_font_size, style);
1909                            let adv: f32 = glyphs
1910                                .get(&key)
1911                                .map(|g: &RasterizedGlyph| (g.get_advance() as f32).max(1.0))
1912                                .unwrap_or(space_adv);
1913                            line_w_phys += adv + letter_sp;
1914                        }
1915                    }
1916                    if style.get_align() == TextAlign::Center {
1917                        ((box_w_phys - line_w_phys) * 0.5).max(0.0)
1918                    } else {
1919                        (box_w_phys - line_w_phys).max(0.0)
1920                    }
1921                }
1922            };
1923            let mut pen_x: f32 = rect.get_x() * scale + align_x;
1924            for ch in line.get_text().chars() {
1925                if ch == ' ' {
1926                    pen_x += space_adv + letter_sp;
1927                    continue;
1928                }
1929                if pen_x > (clip_x1 as f32) {
1930                    break;
1931                }
1932                let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_size, style);
1933                let Some(glyph) = glyphs.get(&key) else {
1934                    pen_x += space_adv + letter_sp;
1935                    continue;
1936                };
1937                let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
1938                let gx0: i32 = pen_x.round() as i32;
1939                let gy0: i32 =
1940                    (pen_y + (line_h_phys - (glyph.get_height() as f32)) * 0.5).round() as i32;
1941                let gw: i32 = glyph.get_width() as i32;
1942                let gh: i32 = glyph.get_height() as i32;
1943                let py_start: i32 = (clip_y0 - gy0).max(0);
1944                let py_end: i32 = (clip_y1 - gy0).min(gh);
1945                let px_start: i32 = (clip_x0 - gx0).max(0);
1946                let px_end: i32 = (clip_x1 - gx0).min(gw);
1947                if py_start < py_end && px_start < px_end {
1948                    let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
1949                    let gw_usize: usize = gw as usize;
1950                    let dx: u32 = (gx0 + px_start) as u32;
1951                    let start_u: usize = px_start as usize;
1952                    let end_u: usize = px_end as usize;
1953                    for py in py_start..py_end {
1954                        let dy: u32 = (gy0 + py) as u32;
1955                        let row_off: usize = (py as usize) * gw_usize;
1956                        let row_slice: &[u8] = &cov_bytes[row_off + start_u..row_off + end_u];
1957                        shaded += band.blend_glyph_row(dx, dy, row_slice, color);
1958                    }
1959                }
1960                pen_x += adv_phys;
1961            }
1962        }
1963        shaded
1964    }
1965
1966    /// Blits a single bilinear-interpolated RGBA8 image scanline into `dst_row` using fixed-point 8.8 weights.
1967    ///
1968    /// # Arguments
1969    ///
1970    /// - `(usize, usize, f32, f32, f32)` - Row geometry `(y, x0, rect_y, inv_dst_h, src_h_f)`.
1971    /// - `(usize, usize)` - Source image dimensions `(src_w, max_sy)`.
1972    /// - `&[(usize, usize, u32)]` - Precomputed horizontal sample LUT `(sx0, sx1, wx_256)`.
1973    /// - `&[u8]` - Source RGBA8 pixel slice.
1974    /// - `&mut [u8]` - Destination framebuffer row slice.
1975    fn blit_bilinear_row(
1976        geom: (usize, usize, f32, f32, f32),
1977        src_dims: (usize, usize),
1978        x_lut: &[(usize, usize, u32)],
1979        src_bytes: &[u8],
1980        dst_row: &mut [u8],
1981    ) {
1982        let (y, x0, rect_y, inv_dst_h, src_h_f): (usize, usize, f32, f32, f32) = geom;
1983        let (src_w_usize, max_sy): (usize, usize) = src_dims;
1984        let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
1985        let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
1986        let sy0: usize = (fy.floor() as usize).min(max_sy);
1987        let sy1: usize = (sy0 + 1).min(max_sy);
1988        let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
1989        let iwy: u32 = 256 - wy;
1990        let row0: usize = sy0 * src_w_usize;
1991        let row1: usize = sy1 * src_w_usize;
1992        let src_len: usize = src_bytes.len();
1993        for (lx, &(sx0, sx1, wx)) in x_lut.iter().enumerate() {
1994            let i00: usize = (row0 + sx0) * 4;
1995            let i10: usize = (row0 + sx1) * 4;
1996            let i01: usize = (row1 + sx0) * 4;
1997            let i11: usize = (row1 + sx1) * 4;
1998            if i11 + 4 > src_len {
1999                continue;
2000            }
2001            let didx: usize = (x0 + lx) * 4;
2002            if didx + 4 > dst_row.len() {
2003                continue;
2004            }
2005            let iwx: u32 = 256 - wx;
2006            let w00: u32 = iwx * iwy;
2007            let w10: u32 = wx * iwy;
2008            let w01: u32 = iwx * wy;
2009            let w11: u32 = wx * wy;
2010            let a00: u32 = src_bytes[i00 + 3] as u32;
2011            let a10: u32 = src_bytes[i10 + 3] as u32;
2012            let a01: u32 = src_bytes[i01 + 3] as u32;
2013            let a11: u32 = src_bytes[i11 + 3] as u32;
2014            if (a00 & a10 & a01 & a11) == 255 {
2015                dst_row[didx] = (((src_bytes[i00] as u32) * w00
2016                    + (src_bytes[i10] as u32) * w10
2017                    + (src_bytes[i01] as u32) * w01
2018                    + (src_bytes[i11] as u32) * w11
2019                    + 32768)
2020                    >> 16) as u8;
2021                dst_row[didx + 1] = (((src_bytes[i00 + 1] as u32) * w00
2022                    + (src_bytes[i10 + 1] as u32) * w10
2023                    + (src_bytes[i01 + 1] as u32) * w01
2024                    + (src_bytes[i11 + 1] as u32) * w11
2025                    + 32768)
2026                    >> 16) as u8;
2027                dst_row[didx + 2] = (((src_bytes[i00 + 2] as u32) * w00
2028                    + (src_bytes[i10 + 2] as u32) * w10
2029                    + (src_bytes[i01 + 2] as u32) * w01
2030                    + (src_bytes[i11 + 2] as u32) * w11
2031                    + 32768)
2032                    >> 16) as u8;
2033                dst_row[didx + 3] = 255;
2034                continue;
2035            }
2036            let a_val: u32 = (a00 * w00 + a10 * w10 + a01 * w01 + a11 * w11 + 32768) >> 16;
2037            if a_val == 0 {
2038                continue;
2039            }
2040            let r: u32 = ((src_bytes[i00] as u32) * w00
2041                + (src_bytes[i10] as u32) * w10
2042                + (src_bytes[i01] as u32) * w01
2043                + (src_bytes[i11] as u32) * w11
2044                + 32768)
2045                >> 16;
2046            let g: u32 = ((src_bytes[i00 + 1] as u32) * w00
2047                + (src_bytes[i10 + 1] as u32) * w10
2048                + (src_bytes[i01 + 1] as u32) * w01
2049                + (src_bytes[i11 + 1] as u32) * w11
2050                + 32768)
2051                >> 16;
2052            let b: u32 = ((src_bytes[i00 + 2] as u32) * w00
2053                + (src_bytes[i10 + 2] as u32) * w10
2054                + (src_bytes[i01 + 2] as u32) * w01
2055                + (src_bytes[i11 + 2] as u32) * w11
2056                + 32768)
2057                >> 16;
2058            let inv_a: u32 = 255 - a_val;
2059            dst_row[didx] = ((r * a_val + (dst_row[didx] as u32) * inv_a + 127) / 255) as u8;
2060            dst_row[didx + 1] =
2061                ((g * a_val + (dst_row[didx + 1] as u32) * inv_a + 127) / 255) as u8;
2062            dst_row[didx + 2] =
2063                ((b * a_val + (dst_row[didx + 2] as u32) * inv_a + 127) / 255) as u8;
2064            dst_row[didx + 3] = 255;
2065        }
2066    }
2067
2068    /// Blits a decoded `ImageBuffer` into `band` with bilinear filtering and per-quadrant SDF rounded clip.
2069    ///
2070    /// # Arguments
2071    ///
2072    /// - `&mut PixelBand<'_>` - Target pixel band.
2073    /// - `Rect` - Physical destination bounds.
2074    /// - `&ImageBuffer` - Source RGBA8 image.
2075    /// - `CornerRadius` - Physical corner radii.
2076    /// - `Rect` - Active clip bounds.
2077    /// - `AntialiasingMode` - Active AA policy.
2078    ///
2079    /// # Returns
2080    ///
2081    /// - `usize` - Shaded pixel count.
2082    fn raster_image(
2083        band: &mut PixelBand<'_>,
2084        rect: Rect,
2085        buffer: &ImageBuffer,
2086        radius: CornerRadius,
2087        clip: Rect,
2088        aa: AntialiasingMode,
2089    ) -> usize {
2090        if buffer.get_width() == 0 || buffer.get_height() == 0 {
2091            return 0;
2092        }
2093        let Some(vis) = rect.intersect(clip) else {
2094            return 0;
2095        };
2096        let half_w: f32 = rect.get_width() * 0.5;
2097        let half_h: f32 = rect.get_height() * 0.5;
2098        let cx: f32 = rect.get_x() + half_w;
2099        let cy: f32 = rect.get_y() + half_h;
2100        let fb_w: u32 = band.width();
2101        let band_y0: u32 = band.y_offset();
2102        let band_y1: u32 = band.y_end();
2103        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2104        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2105        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2106        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2107        let src_w: u32 = buffer.get_width();
2108        let src_h: u32 = buffer.get_height();
2109        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
2110        let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
2111        let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
2112        let use_bilinear: bool = aa != AntialiasingMode::None
2113            && ((rect.get_width() - (src_w as f32)).abs() > 0.5
2114                || (rect.get_height() - (src_h as f32)).abs() > 0.5);
2115        let has_radius: bool = radius.max_radius() > 0.0;
2116        let max_sx: usize = (src_w as usize).saturating_sub(1);
2117        let max_sy: usize = (src_h as usize).saturating_sub(1);
2118        let src_w_usize: usize = src_w as usize;
2119        if !has_radius && use_bilinear && x0 < x1 && y0 < y1 {
2120            let span_w: usize = (x1 - x0) as usize;
2121            let mut x_lut: Vec<(usize, usize, u32)> = Vec::with_capacity(span_w);
2122            for x in x0..x1 {
2123                let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2124                let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
2125                let sx0: usize = (fx.floor() as usize).min(max_sx);
2126                let sx1: usize = (sx0 + 1).min(max_sx);
2127                let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
2128                x_lut.push((sx0, sx1, wx));
2129            }
2130            let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
2131            let rect_y: f32 = rect.get_y();
2132            let src_h_f: f32 = src_h as f32;
2133            let x0_usize: usize = x0 as usize;
2134            for y in y0..y1 {
2135                if let Some(row_buf) = band.row_slice_mut(y) {
2136                    Self::blit_bilinear_row(
2137                        (y as usize, x0_usize, rect_y, inv_dst_h, src_h_f),
2138                        (src_w_usize, max_sy),
2139                        x_lut_ref,
2140                        src_bytes,
2141                        row_buf,
2142                    );
2143                }
2144            }
2145            return span_w * ((y1 - y0) as usize);
2146        }
2147        let mut shaded: usize = 0;
2148        for y in y0..y1 {
2149            let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
2150            let py: f32 = (y as f32) + 0.5 - cy;
2151            if use_bilinear {
2152                let fy: f32 = (v * (src_h as f32) - 0.5).clamp(0.0, max_sy as f32);
2153                let sy0: usize = (fy.floor() as usize).min(max_sy);
2154                let sy1: usize = (sy0 + 1).min(max_sy);
2155                let wy: f32 = fy - (sy0 as f32);
2156                let iwy: f32 = 1.0 - wy;
2157                let row0: usize = sy0 * src_w_usize;
2158                let row1: usize = sy1 * src_w_usize;
2159                for x in x0..x1 {
2160                    let cov: f32 = if has_radius {
2161                        let px: f32 = (x as f32) + 0.5 - cx;
2162                        let cr: f32 = quadrant_corner_radius(radius, px, py);
2163                        sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2164                    } else {
2165                        1.0
2166                    };
2167                    if cov <= 0.0 {
2168                        continue;
2169                    }
2170                    let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2171                    let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
2172                    let sx0: usize = (fx.floor() as usize).min(max_sx);
2173                    let sx1: usize = (sx0 + 1).min(max_sx);
2174                    let wx: f32 = fx - (sx0 as f32);
2175                    let iwx: f32 = 1.0 - wx;
2176                    let i00: usize = (row0 + sx0) * 4;
2177                    let i10: usize = (row0 + sx1) * 4;
2178                    let i01: usize = (row1 + sx0) * 4;
2179                    let i11: usize = (row1 + sx1) * 4;
2180                    if i11 + 4 <= src_bytes.len() {
2181                        let w00: f32 = iwx * iwy;
2182                        let w10: f32 = wx * iwy;
2183                        let w01: f32 = iwx * wy;
2184                        let w11: f32 = wx * wy;
2185                        let r: u8 = ((src_bytes[i00] as f32) * w00
2186                            + (src_bytes[i10] as f32) * w10
2187                            + (src_bytes[i01] as f32) * w01
2188                            + (src_bytes[i11] as f32) * w11)
2189                            .round() as u8;
2190                        let g: u8 = ((src_bytes[i00 + 1] as f32) * w00
2191                            + (src_bytes[i10 + 1] as f32) * w10
2192                            + (src_bytes[i01 + 1] as f32) * w01
2193                            + (src_bytes[i11 + 1] as f32) * w11)
2194                            .round() as u8;
2195                        let b: u8 = ((src_bytes[i00 + 2] as f32) * w00
2196                            + (src_bytes[i10 + 2] as f32) * w10
2197                            + (src_bytes[i01 + 2] as f32) * w01
2198                            + (src_bytes[i11 + 2] as f32) * w11)
2199                            .round() as u8;
2200                        let a: u8 = ((src_bytes[i00 + 3] as f32) * w00
2201                            + (src_bytes[i10 + 3] as f32) * w10
2202                            + (src_bytes[i01 + 3] as f32) * w01
2203                            + (src_bytes[i11 + 3] as f32) * w11)
2204                            .round() as u8;
2205                        let sample: Color = Color::new(r, g, b, a).multiply_alpha(cov);
2206                        band.blend_pixel(x, y, sample);
2207                        shaded += 1;
2208                    }
2209                }
2210            } else {
2211                let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
2212                let row: usize = sy * src_w_usize;
2213                for x in x0..x1 {
2214                    let cov: f32 = if has_radius {
2215                        let px: f32 = (x as f32) + 0.5 - cx;
2216                        let cr: f32 = quadrant_corner_radius(radius, px, py);
2217                        sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2218                    } else {
2219                        1.0
2220                    };
2221                    if cov <= 0.0 {
2222                        continue;
2223                    }
2224                    let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2225                    let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
2226                    let idx: usize = (row + sx) * 4;
2227                    if idx + 4 <= src_bytes.len() {
2228                        let sample: Color = Color::new(
2229                            src_bytes[idx],
2230                            src_bytes[idx + 1],
2231                            src_bytes[idx + 2],
2232                            src_bytes[idx + 3],
2233                        )
2234                        .multiply_alpha(cov);
2235                        band.blend_pixel(x, y, sample);
2236                        shaded += 1;
2237                    }
2238                }
2239            }
2240        }
2241        shaded
2242    }
2243
2244    /// Rasterizes an anti-aliased line segment between `from` and `to`.
2245    ///
2246    /// # Arguments
2247    ///
2248    /// - `&mut PixelBand<'_>` - Target pixel band.
2249    /// - `Point` - Physical start point.
2250    /// - `Point` - Physical end point.
2251    /// - `Color` - Stroke color.
2252    /// - `f32` - Physical stroke width.
2253    /// - `Rect` - Active clip bounds.
2254    /// - `AntialiasingMode` - Active AA policy.
2255    ///
2256    /// # Returns
2257    ///
2258    /// - `usize` - Shaded pixel count.
2259    fn raster_line(
2260        band: &mut PixelBand<'_>,
2261        from: Point,
2262        to: Point,
2263        color: Color,
2264        width: f32,
2265        clip: Rect,
2266        aa: AntialiasingMode,
2267    ) -> usize {
2268        let half_w: f32 = width * 0.5;
2269        let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
2270        let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
2271        let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
2272        let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
2273        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2274        else {
2275            return 0;
2276        };
2277        let dx: f32 = to.get_x() - from.get_x();
2278        let dy: f32 = to.get_y() - from.get_y();
2279        let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
2280        let fb_w: u32 = band.width();
2281        let band_y0: u32 = band.y_offset();
2282        let band_y1: u32 = band.y_end();
2283        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2284        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2285        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2286        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2287        let mut shaded: usize = 0;
2288        for y in y0..y1 {
2289            let py: f32 = (y as f32) + 0.5;
2290            for x in x0..x1 {
2291                let px: f32 = (x as f32) + 0.5;
2292                let t: f32 = (((px - from.get_x()) * dx + (py - from.get_y()) * dy) / len_sq)
2293                    .clamp(0.0, 1.0);
2294                let proj_x: f32 = from.get_x() + t * dx;
2295                let proj_y: f32 = from.get_y() + t * dy;
2296                let dist: f32 =
2297                    ((px - proj_x) * (px - proj_x) + (py - proj_y) * (py - proj_y)).sqrt() - half_w;
2298                let cov: f32 = sdf_coverage(dist, aa);
2299                if cov > 0.0 {
2300                    let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * cov;
2301                    band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
2302                    shaded += 1;
2303                }
2304            }
2305        }
2306        shaded
2307    }
2308
2309    /// Rasterizes an analytical SDF anti-aliased filled circle with 4x4 RGSS perimeter sampling.
2310    ///
2311    /// # Arguments
2312    ///
2313    /// - `&mut PixelBand<'_>` - Target pixel band.
2314    /// - `Point` - Physical center point.
2315    /// - `f32` - Physical radius.
2316    /// - `Color` - Fill color.
2317    /// - `Rect` - Active clip bounds.
2318    /// - `AntialiasingMode` - Active AA policy.
2319    ///
2320    /// # Returns
2321    ///
2322    /// - `usize` - Shaded pixel count.
2323    fn raster_circle(
2324        band: &mut PixelBand<'_>,
2325        center: Point,
2326        radius: f32,
2327        color: Color,
2328        clip: Rect,
2329        aa: AntialiasingMode,
2330    ) -> usize {
2331        if radius <= 0.0 || color.get_a() == 0 {
2332            return 0;
2333        }
2334        let bounds: Rect = Rect::new(
2335            center.get_x() - radius - 1.0,
2336            center.get_y() - radius - 1.0,
2337            (radius + 1.0) * 2.0,
2338            (radius + 1.0) * 2.0,
2339        );
2340        let Some(vis) = bounds.intersect(clip) else {
2341            return 0;
2342        };
2343        let fb_w: u32 = band.width();
2344        let band_y0: u32 = band.y_offset();
2345        let band_y1: u32 = band.y_end();
2346        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2347        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2348        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2349        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2350        let outer_r: f32 = radius + 1.0;
2351        let inner_r: f32 = (radius - 1.0).max(0.0);
2352        let outer_r2: f32 = outer_r * outer_r;
2353        let inner_r2: f32 = inner_r * inner_r;
2354        let cx: f32 = center.get_x();
2355        let cy: f32 = center.get_y();
2356        let mut shaded: usize = 0;
2357        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2358        for y in y0..y1 {
2359            let dy: f32 = (y as f32) + 0.5 - cy;
2360            let dy2: f32 = dy * dy;
2361            if dy2 >= outer_r2 {
2362                continue;
2363            }
2364            let out_dx: f32 = (outer_r2 - dy2).sqrt();
2365            let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
2366            let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(x0, x1);
2367            if dy2 < inner_r2 && inner_r > 1.0 {
2368                let in_dx: f32 = (inner_r2 - dy2).sqrt();
2369                let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
2370                let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(row_x0, row_x1);
2371                for x in row_x0..in_x0 {
2372                    let dx: f32 = (x as f32) + 0.5 - cx;
2373                    let cov: f32 = if aa == AntialiasingMode::None {
2374                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2375                    } else {
2376                        circle_supersampled_coverage(dx, dy, radius)
2377                    };
2378                    if cov > 0.0 {
2379                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2380                        shaded += 1;
2381                    }
2382                }
2383                if in_x0 < in_x1 {
2384                    band.fill_span_linear(in_x0, in_x1, y, color);
2385                    shaded += (in_x1 - in_x0) as usize;
2386                }
2387                for x in in_x1..row_x1 {
2388                    let dx: f32 = (x as f32) + 0.5 - cx;
2389                    let cov: f32 = if aa == AntialiasingMode::None {
2390                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2391                    } else {
2392                        circle_supersampled_coverage(dx, dy, radius)
2393                    };
2394                    if cov > 0.0 {
2395                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2396                        shaded += 1;
2397                    }
2398                }
2399            } else {
2400                for x in row_x0..row_x1 {
2401                    let dx: f32 = (x as f32) + 0.5 - cx;
2402                    let cov: f32 = if aa == AntialiasingMode::None {
2403                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2404                    } else {
2405                        circle_supersampled_coverage(dx, dy, radius)
2406                    };
2407                    if cov > 0.0 {
2408                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2409                        shaded += 1;
2410                    }
2411                }
2412            }
2413        }
2414        shaded
2415    }
2416
2417    /// Rasterizes a solid filled triangle using fast signed-edge classification and edge-only 4x4 RGSS.
2418    ///
2419    /// # Arguments
2420    ///
2421    /// - `&mut PixelBand<'_>` - Target pixel band.
2422    /// - `Point` - First physical vertex.
2423    /// - `Point` - Second physical vertex.
2424    /// - `Point` - Third physical vertex.
2425    /// - `Color` - Fill color.
2426    /// - `Rect` - Active clip bounds.
2427    /// - `AntialiasingMode` - Active AA policy.
2428    ///
2429    /// # Returns
2430    ///
2431    /// - `usize` - Shaded pixel count.
2432    fn raster_triangle(
2433        band: &mut PixelBand<'_>,
2434        p0: Point,
2435        p1: Point,
2436        p2: Point,
2437        color: Color,
2438        clip: Rect,
2439        aa: AntialiasingMode,
2440    ) -> usize {
2441        if color.get_a() == 0 {
2442            return 0;
2443        }
2444        let area: f32 = (p1.get_x() - p0.get_x()) * (p2.get_y() - p0.get_y())
2445            - (p1.get_y() - p0.get_y()) * (p2.get_x() - p0.get_x());
2446        if area.abs() < 1e-5 {
2447            return 0;
2448        }
2449        let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
2450        let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
2451        let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
2452        let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
2453        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2454        else {
2455            return 0;
2456        };
2457        let fb_w: u32 = band.width();
2458        let band_y0: u32 = band.y_offset();
2459        let band_y1: u32 = band.y_end();
2460        let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2461        let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2462        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2463        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2464        let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
2465        let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
2466        let inv_l0: f32 = sign
2467            / (p1.get_x() - p0.get_x())
2468                .hypot(p1.get_y() - p0.get_y())
2469                .max(1e-5);
2470        let inv_l1: f32 = sign
2471            / (p2.get_x() - p1.get_x())
2472                .hypot(p2.get_y() - p1.get_y())
2473                .max(1e-5);
2474        let inv_l2: f32 = sign
2475            / (p0.get_x() - p2.get_x())
2476                .hypot(p0.get_y() - p2.get_y())
2477                .max(1e-5);
2478        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2479        let mut shaded: usize = 0;
2480        for y in y0..y1 {
2481            let py: f32 = (y as f32) + 0.5;
2482            if aa == AntialiasingMode::None {
2483                let mut min_ix: f32 = f32::INFINITY;
2484                let mut max_ix: f32 = f32::NEG_INFINITY;
2485                for (a, b) in edges.iter() {
2486                    let ay: f32 = a.get_y();
2487                    let by: f32 = b.get_y();
2488                    if (ay <= py && by > py) || (by <= py && ay > py) {
2489                        let t: f32 = (py - ay) / (by - ay);
2490                        let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
2491                        min_ix = min_ix.min(ix);
2492                        max_ix = max_ix.max(ix);
2493                    }
2494                }
2495                if min_ix <= max_ix {
2496                    let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
2497                    let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
2498                    if sx0 < sx1 {
2499                        band.fill_span_linear(sx0, sx1, y, color);
2500                        shaded += (sx1 - sx0) as usize;
2501                    }
2502                }
2503                continue;
2504            }
2505            for x in clip_x0..clip_x1 {
2506                let px: f32 = (x as f32) + 0.5;
2507                let d0: f32 = ((p1.get_x() - p0.get_x()) * (py - p0.get_y())
2508                    - (p1.get_y() - p0.get_y()) * (px - p0.get_x()))
2509                    * inv_l0;
2510                if d0 < -0.85 {
2511                    continue;
2512                }
2513                let d1: f32 = ((p2.get_x() - p1.get_x()) * (py - p1.get_y())
2514                    - (p2.get_y() - p1.get_y()) * (px - p1.get_x()))
2515                    * inv_l1;
2516                if d1 < -0.85 {
2517                    continue;
2518                }
2519                let d2: f32 = ((p0.get_x() - p2.get_x()) * (py - p2.get_y())
2520                    - (p0.get_y() - p2.get_y()) * (px - p2.get_x()))
2521                    * inv_l2;
2522                if d2 < -0.85 {
2523                    continue;
2524                }
2525                if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
2526                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
2527                    shaded += 1;
2528                    continue;
2529                }
2530                let cov: f32 = triangle_supersampled_coverage(px, py, p0, p1, p2);
2531                if cov >= 0.999 {
2532                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
2533                    shaded += 1;
2534                } else if cov > 0.0 {
2535                    band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2536                    shaded += 1;
2537                }
2538            }
2539        }
2540        shaded
2541    }
2542
2543    /// Blits a cropped sub-rectangle of an `ImageBuffer` sprite sheet into `band` with bilinear filtering and optional tint.
2544    ///
2545    /// # Arguments
2546    ///
2547    /// - `&mut PixelBand<'_>` - Target pixel band.
2548    /// - `Rect` - Physical destination bounds.
2549    /// - `&ImageBuffer` - Source sprite-sheet RGBA8 buffer.
2550    /// - `Rect` - Source pixel sub-rectangle.
2551    /// - `Color` - Multiplicative tint color.
2552    /// - `Rect` - Active clip bounds.
2553    /// - `AntialiasingMode` - Active AA policy.
2554    ///
2555    /// # Returns
2556    ///
2557    /// - `usize` - Shaded pixel count.
2558    fn raster_sprite_region(
2559        band: &mut PixelBand<'_>,
2560        rect: Rect,
2561        buffer: &ImageBuffer,
2562        src_rect: Rect,
2563        tint: Color,
2564        clip: Rect,
2565        aa: AntialiasingMode,
2566    ) -> usize {
2567        if buffer.get_width() == 0
2568            || buffer.get_height() == 0
2569            || tint.get_a() == 0
2570            || src_rect.get_width() <= 0.0
2571            || src_rect.get_height() <= 0.0
2572        {
2573            return 0;
2574        }
2575        let Some(vis) = rect.intersect(clip) else {
2576            return 0;
2577        };
2578        let fb_w: u32 = band.width();
2579        let band_y0: u32 = band.y_offset();
2580        let band_y1: u32 = band.y_end();
2581        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2582        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2583        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2584        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2585        let buf_w: u32 = buffer.get_width();
2586        let buf_h: u32 = buffer.get_height();
2587        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
2588        let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
2589        let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
2590        let untinted: bool = tint == COLOR_WHITE;
2591        let tr: u32 = tint.get_r() as u32;
2592        let tg: u32 = tint.get_g() as u32;
2593        let tb: u32 = tint.get_b() as u32;
2594        let ta: u32 = tint.get_a() as u32;
2595        let use_bilinear: bool = aa != AntialiasingMode::None
2596            && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
2597                || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
2598        let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
2599        let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
2600        let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
2601        let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
2602        let buf_w_usize: usize = buf_w as usize;
2603        let mut shaded: usize = 0;
2604        for y in y0..y1 {
2605            let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_h).clamp(0.0, 1.0);
2606            let fy: f32 = (src_rect.get_y() + v * src_rect.get_height() - 0.5)
2607                .clamp(min_sy as f32, max_sy as f32);
2608            let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
2609            let sy1: u32 = (sy0 + 1).min(max_sy);
2610            let wy: f32 = if use_bilinear { fy - (sy0 as f32) } else { 0.0 };
2611            let iwy: f32 = 1.0 - wy;
2612            let row0: usize = (sy0 as usize) * buf_w_usize;
2613            let row1: usize = (sy1 as usize) * buf_w_usize;
2614            for x in x0..x1 {
2615                let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_w).clamp(0.0, 1.0);
2616                let fx: f32 = (src_rect.get_x() + u * src_rect.get_width() - 0.5)
2617                    .clamp(min_sx as f32, max_sx as f32);
2618                let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
2619                let sx1: u32 = (sx0 + 1).min(max_sx);
2620                let (sr_u8, sg_u8, sb_u8, sa_u8): (u8, u8, u8, u8) = if use_bilinear {
2621                    let wx: f32 = fx - (sx0 as f32);
2622                    let iwx: f32 = 1.0 - wx;
2623                    let i00: usize = (row0 + (sx0 as usize)) * 4;
2624                    let i10: usize = (row0 + (sx1 as usize)) * 4;
2625                    let i01: usize = (row1 + (sx0 as usize)) * 4;
2626                    let i11: usize = (row1 + (sx1 as usize)) * 4;
2627                    if i11 + 4 > src_bytes.len() {
2628                        continue;
2629                    }
2630                    let w00: f32 = iwx * iwy;
2631                    let w10: f32 = wx * iwy;
2632                    let w01: f32 = iwx * wy;
2633                    let w11: f32 = wx * wy;
2634                    (
2635                        ((src_bytes[i00] as f32) * w00
2636                            + (src_bytes[i10] as f32) * w10
2637                            + (src_bytes[i01] as f32) * w01
2638                            + (src_bytes[i11] as f32) * w11)
2639                            .round() as u8,
2640                        ((src_bytes[i00 + 1] as f32) * w00
2641                            + (src_bytes[i10 + 1] as f32) * w10
2642                            + (src_bytes[i01 + 1] as f32) * w01
2643                            + (src_bytes[i11 + 1] as f32) * w11)
2644                            .round() as u8,
2645                        ((src_bytes[i00 + 2] as f32) * w00
2646                            + (src_bytes[i10 + 2] as f32) * w10
2647                            + (src_bytes[i01 + 2] as f32) * w01
2648                            + (src_bytes[i11 + 2] as f32) * w11)
2649                            .round() as u8,
2650                        ((src_bytes[i00 + 3] as f32) * w00
2651                            + (src_bytes[i10 + 3] as f32) * w10
2652                            + (src_bytes[i01 + 3] as f32) * w01
2653                            + (src_bytes[i11 + 3] as f32) * w11)
2654                            .round() as u8,
2655                    )
2656                } else {
2657                    let idx: usize = (row0 + (sx0 as usize)) * 4;
2658                    if idx + 4 > src_bytes.len() {
2659                        continue;
2660                    }
2661                    (
2662                        src_bytes[idx],
2663                        src_bytes[idx + 1],
2664                        src_bytes[idx + 2],
2665                        src_bytes[idx + 3],
2666                    )
2667                };
2668                if sa_u8 == 0 {
2669                    continue;
2670                }
2671                let sample: Color = if untinted {
2672                    Color::new(sr_u8, sg_u8, sb_u8, sa_u8)
2673                } else {
2674                    let rr: u32 = (sr_u8 as u32) * tr + 128;
2675                    let gg: u32 = (sg_u8 as u32) * tg + 128;
2676                    let bb: u32 = (sb_u8 as u32) * tb + 128;
2677                    let aa_v: u32 = (sa_u8 as u32) * ta + 128;
2678                    Color::new(
2679                        ((rr + (rr >> 8)) >> 8) as u8,
2680                        ((gg + (gg >> 8)) >> 8) as u8,
2681                        ((bb + (bb >> 8)) >> 8) as u8,
2682                        ((aa_v + (aa_v >> 8)) >> 8) as u8,
2683                    )
2684                };
2685                band.blend_pixel(x, y, sample);
2686                shaded += 1;
2687            }
2688        }
2689        shaded
2690    }
2691}