1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
5impl BandWorkerPool {
7 #[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 fn execute_serial(
88 bands: &mut [PixelBand<'_>],
89 commands: &[DrawCommand],
90 prepped: &[PreppedCommand],
91 aux: (&[TextLayoutResult], &[RoundedClipMask]),
92 atlas: &GlyphAtlas,
93 render_opts: (f32, AntialiasingMode, Option<&[u8]>),
94 ) -> usize {
95 let (layouts, rounded_clips): (&[TextLayoutResult], &[RoundedClipMask]) = aux;
96 let (scale, aa, base_restore): (f32, AntialiasingMode, Option<&[u8]>) = render_opts;
97 let mut total: usize = 0;
98 for band in bands.iter_mut() {
99 if let Some(src_buf) = base_restore {
100 let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
101 let byte_end: usize = byte_off + band.pixels.len();
102 if let Some(src_slice) = src_buf.get(byte_off..byte_end) {
103 band.pixels.copy_from_slice(src_slice);
104 }
105 }
106 total += SoftwareRenderer::render_band(
107 band,
108 commands,
109 prepped,
110 layouts,
111 rounded_clips,
112 atlas,
113 (scale, aa),
114 );
115 }
116 total
117 }
118
119 #[must_use]
125 pub(crate) fn total_threads(&self) -> usize {
126 let Self { worker_count, .. } = self;
127 worker_count.saturating_add(1)
128 }
129
130 pub(crate) fn execute(
146 &self,
147 bands: &mut [PixelBand<'_>],
148 commands: &[DrawCommand],
149 prepped: &[PreppedCommand],
150 aux: (&[TextLayoutResult], &[RoundedClipMask]),
151 atlas: &GlyphAtlas,
152 render_opts: (f32, AntialiasingMode, Option<&[u8]>),
153 ) -> usize {
154 let Self {
155 worker_count,
156 dispatch_lock,
157 shared,
158 } = self;
159 let (layouts, rounded_clips): (&[TextLayoutResult], &[RoundedClipMask]) = aux;
160 let (scale, aa, base_restore): (f32, AntialiasingMode, Option<&[u8]>) = render_opts;
161 if *worker_count == 0 || bands.len() <= 1 {
162 return Self::execute_serial(
163 bands,
164 commands,
165 prepped,
166 (layouts, rounded_clips),
167 atlas,
168 (scale, aa, base_restore),
169 );
170 }
171 let Ok(_dispatch_guard) = dispatch_lock.try_lock() else {
172 return Self::execute_serial(
173 bands,
174 commands,
175 prepped,
176 (layouts, rounded_clips),
177 atlas,
178 (scale, aa, base_restore),
179 );
180 };
181 let mut tasks: Vec<BandTaskSlice> = Vec::with_capacity(bands.len());
182 for band in bands.iter_mut() {
183 let base_ptr: usize = if let Some(src_buf) = base_restore {
184 let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
185 let byte_end: usize = byte_off + band.pixels.len();
186 if byte_end <= src_buf.len() {
187 unsafe { src_buf.as_ptr().add(byte_off) as usize }
188 } else {
189 0
190 }
191 } else {
192 0
193 };
194 tasks.push(BandTaskSlice {
195 pixels_ptr: band.pixels.as_mut_ptr() as usize,
196 pixels_len: band.pixels.len(),
197 width: band.width,
198 y_start: band.y_offset,
199 height: band.height,
200 base_src_ptr: base_ptr,
201 });
202 }
203 let job: BandJob = BandJob {
204 tasks_ptr: tasks.as_ptr() as usize,
205 tasks_len: tasks.len(),
206 commands_ptr: commands.as_ptr() as usize,
207 commands_len: commands.len(),
208 prepped_ptr: prepped.as_ptr() as usize,
209 prepped_len: prepped.len(),
210 layouts_ptr: layouts.as_ptr() as usize,
211 layouts_len: layouts.len(),
212 rounded_clips_ptr: rounded_clips.as_ptr() as usize,
213 rounded_clips_len: rounded_clips.len(),
214 atlas_ptr: (atlas as *const GlyphAtlas) as usize,
215 scale,
216 aa,
217 next_idx: AtomicUsize::new(0),
218 workers_done: AtomicUsize::new(0),
219 total_shaded: AtomicUsize::new(0),
220 };
221 let (lock, wake_workers, wake_caller): &(Mutex<BandPoolState>, Condvar, Condvar) = shared;
222 {
223 if let Ok(mut state) = lock.lock() {
224 let next_epoch: u64 = state.get_epoch().wrapping_add(1);
225 state.set_active_job((&job as *const BandJob) as usize);
226 state.set_epoch(next_epoch);
227 wake_workers.notify_all();
228 } else {
229 run_band_job_loop(&job);
230 return job.total_shaded.load(Ordering::Acquire);
231 }
232 }
233 run_band_job_loop(&job);
234 let mut wait_guard: Option<MutexGuard<'_, BandPoolState>> = lock.lock().ok();
235 while let Some(state) = wait_guard.take() {
236 if job.workers_done.load(Ordering::Acquire) >= *worker_count {
237 let mut done_state: MutexGuard<'_, BandPoolState> = state;
238 done_state.set_active_job(0);
239 break;
240 }
241 wait_guard = wake_caller.wait(state).ok();
242 }
243 job.total_shaded.load(Ordering::Acquire)
244 }
245}
246
247impl SoftwareRenderer {
249 #[must_use]
261 pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
262 Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
263 }
264
265 #[must_use]
278 pub fn with_font_provider(
279 width: u32,
280 height: u32,
281 config: RenderConfig,
282 font_provider: NativeSystemFont,
283 ) -> Self {
284 Self {
285 framebuffer: Framebuffer::allocate(width, height),
286 glyph_atlas: GlyphAtlas::default(),
287 font_provider,
288 measurer: DeterministicTextMeasurer,
289 text_layout_cache: HashMap::with_capacity(128),
290 clip_stack: Vec::with_capacity(8),
291 rounded_clip_stack: Vec::with_capacity(8),
292 antialiasing: config.get_antialiasing(),
293 tile_size: config.get_tile_size().max(16),
294 base_cache_width: 0,
295 base_cache_height: 0,
296 base_cache_hash: 0,
297 prev_base_hash: 0,
298 base_cache_pixels: Vec::new(),
299 }
300 }
301
302 pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
314 let scale: f32 = display_list.get_scale_factor().max(0.5);
315 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
316 let phys_h: u32 =
317 ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
318 let resized: bool = self.get_mut_framebuffer().resize(phys_w, phys_h);
319 if resized {
320 self.set_base_cache_hash(0);
321 self.set_prev_base_hash(0);
322 self.set_base_cache_width(0);
323 self.set_base_cache_height(0);
324 }
325 let effective_damage: DamageRegion = if resized {
326 DamageRegion::full()
327 } else {
328 damage
329 };
330 let Some(root_clip) = effective_damage.resolve(phys_w, phys_h) else {
331 return (0, 0);
332 };
333 let tile_sz: u32 = self.get_tile_size().max(16);
334 let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
335 let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
336 let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
337 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
338 let split: usize = display_list.get_portal_split_index().min(commands.len());
339 let has_portals: bool = split > 0 && split < commands.len();
340 let is_full_frame: bool = root_clip.get_x() <= 0.0
341 && root_clip.get_y() <= 0.0
342 && root_clip.get_width() >= (phys_w as f32)
343 && root_clip.get_height() >= (phys_h as f32);
344 if has_portals && is_full_frame {
345 let base_hash: u64 = display_list.base_layer_hash();
346 let fb_len: usize = self.get_framebuffer().get_pixels().len();
347 let cache_hit: bool = base_hash != 0
348 && self.get_base_cache_hash() == base_hash
349 && self.get_base_cache_width() == phys_w
350 && self.get_base_cache_height() == phys_h
351 && self.get_base_cache_pixels().len() == fb_len;
352 if cache_hit {
353 let (prepped, text_layouts, rounded_clips): (
354 Vec<PreppedCommand>,
355 Vec<TextLayoutResult>,
356 Vec<RoundedClipMask>,
357 ) = self.prepare_frame_range(
358 display_list,
359 split,
360 commands.len(),
361 root_clip,
362 scale,
363 phys_h,
364 );
365 let pixels_shaded: usize = self.execute_prepared_bands(
366 commands,
367 (
368 prepped.as_slice(),
369 text_layouts.as_slice(),
370 rounded_clips.as_slice(),
371 ),
372 root_clip,
373 (phys_w, phys_h, scale),
374 true,
375 );
376 return (tiles_updated, pixels_shaded.max(1));
377 }
378 let (base_prepped, base_layouts, base_rounded): (
379 Vec<PreppedCommand>,
380 Vec<TextLayoutResult>,
381 Vec<RoundedClipMask>,
382 ) = self.prepare_frame_range(display_list, 0, split, root_clip, scale, phys_h);
383 let base_shaded: usize = self.execute_prepared_bands(
384 commands,
385 (
386 base_prepped.as_slice(),
387 base_layouts.as_slice(),
388 base_rounded.as_slice(),
389 ),
390 root_clip,
391 (phys_w, phys_h, scale),
392 false,
393 );
394 let base_stable: bool = base_hash != 0 && self.get_prev_base_hash() == base_hash;
395 self.set_prev_base_hash(base_hash);
396 if base_stable {
397 let Self {
398 framebuffer,
399 base_cache_pixels,
400 base_cache_width,
401 base_cache_height,
402 base_cache_hash,
403 ..
404 } = self;
405 let src_pixels: &[u8] = framebuffer.get_pixels().as_slice();
406 if base_cache_pixels.len() != src_pixels.len() {
407 base_cache_pixels.resize(src_pixels.len(), 0);
408 }
409 base_cache_pixels.copy_from_slice(src_pixels);
410 *base_cache_width = phys_w;
411 *base_cache_height = phys_h;
412 *base_cache_hash = base_hash;
413 }
414 let (portal_prepped, portal_layouts, portal_rounded): (
415 Vec<PreppedCommand>,
416 Vec<TextLayoutResult>,
417 Vec<RoundedClipMask>,
418 ) = self.prepare_frame_range(
419 display_list,
420 split,
421 commands.len(),
422 root_clip,
423 scale,
424 phys_h,
425 );
426 let portal_shaded: usize = self.execute_prepared_bands(
427 commands,
428 (
429 portal_prepped.as_slice(),
430 portal_layouts.as_slice(),
431 portal_rounded.as_slice(),
432 ),
433 root_clip,
434 (phys_w, phys_h, scale),
435 false,
436 );
437 return (tiles_updated, base_shaded.saturating_add(portal_shaded));
438 }
439 if !has_portals {
440 self.set_base_cache_hash(0);
441 self.set_prev_base_hash(0);
442 }
443 let (prepped, text_layouts, rounded_clips): (
444 Vec<PreppedCommand>,
445 Vec<TextLayoutResult>,
446 Vec<RoundedClipMask>,
447 ) = self.prepare_frame_range(display_list, 0, commands.len(), root_clip, scale, phys_h);
448 let pixels_shaded: usize = self.execute_prepared_bands(
449 commands,
450 (
451 prepped.as_slice(),
452 text_layouts.as_slice(),
453 rounded_clips.as_slice(),
454 ),
455 root_clip,
456 (phys_w, phys_h, scale),
457 false,
458 );
459 (tiles_updated, pixels_shaded)
460 }
461
462 fn execute_prepared_bands(
477 &mut self,
478 commands: &[DrawCommand],
479 prepared: (&[PreppedCommand], &[TextLayoutResult], &[RoundedClipMask]),
480 root_clip: Rect,
481 dims: (u32, u32, f32),
482 restore_base_cache: bool,
483 ) -> usize {
484 let (prepped_slice, layouts_slice, rounded_clips_slice): (
485 &[PreppedCommand],
486 &[TextLayoutResult],
487 &[RoundedClipMask],
488 ) = prepared;
489 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
490 let aa: AntialiasingMode = self.get_antialiasing();
491 let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
492 let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
493 let clip_w: u32 = (root_clip.get_width().ceil().max(0.0) as u32).min(phys_w);
494 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
495 let Self {
496 framebuffer,
497 glyph_atlas,
498 base_cache_pixels,
499 ..
500 } = self;
501 let atlas_ref: &GlyphAtlas = glyph_atlas;
502 let base_restore: Option<&[u8]> = if restore_base_cache {
503 Some(base_cache_pixels.as_slice())
504 } else {
505 None
506 };
507 #[cfg(not(target_arch = "wasm32"))]
508 {
509 if (clip_w as usize).saturating_mul(clip_h as usize) >= 65_536 && clip_h >= 64 {
510 let pool: &BandWorkerPool = global_band_worker_pool();
511 let strip_count: usize = (pool.total_threads().saturating_mul(2))
512 .min((clip_h / 24) as usize)
513 .max(1);
514 if strip_count > 1 && pool.total_threads() > 1 {
515 let mut bands: Vec<PixelBand<'_>> =
516 framebuffer.split_bands_mut(clip_y0, clip_y1, strip_count);
517 return pool.execute(
518 bands.as_mut_slice(),
519 commands,
520 prepped_slice,
521 (layouts_slice, rounded_clips_slice),
522 atlas_ref,
523 (scale, aa, base_restore),
524 );
525 }
526 }
527 if let Some(src_buf) = base_restore
528 && src_buf.len() == framebuffer.get_pixels().len()
529 {
530 framebuffer.get_mut_pixels().copy_from_slice(src_buf);
531 }
532 let mut band: PixelBand<'_> = framebuffer.as_band_mut();
533 Self::render_band(
534 &mut band,
535 commands,
536 prepped_slice,
537 layouts_slice,
538 rounded_clips_slice,
539 atlas_ref,
540 (scale, aa),
541 )
542 }
543 #[cfg(target_arch = "wasm32")]
544 {
545 let _: (u32, u32) = (clip_w, clip_h);
546 if let Some(src_buf) = base_restore
547 && src_buf.len() == framebuffer.get_pixels().len()
548 {
549 framebuffer.get_mut_pixels().copy_from_slice(src_buf);
550 }
551 let mut band: PixelBand<'_> = framebuffer.as_band_mut();
552 Self::render_band(
553 &mut band,
554 commands,
555 prepped_slice,
556 layouts_slice,
557 rounded_clips_slice,
558 atlas_ref,
559 (scale, aa),
560 )
561 }
562 }
563
564 fn prepare_frame_range(
580 &mut self,
581 display_list: &DisplayList,
582 start_idx: usize,
583 end_idx: usize,
584 root_clip: Rect,
585 scale: f32,
586 phys_h: u32,
587 ) -> PreparedFrameData {
588 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
589 let clamped_end: usize = end_idx.min(commands.len());
590 let clamped_start: usize = start_idx.min(clamped_end);
591 let mut prepped: Vec<PreppedCommand> = Vec::with_capacity(clamped_end - clamped_start);
592 let mut text_layouts: Vec<TextLayoutResult> = Vec::new();
593 let mut rounded_clips: Vec<RoundedClipMask> = Vec::new();
594 let Self {
595 glyph_atlas,
596 font_provider,
597 measurer,
598 text_layout_cache,
599 clip_stack,
600 rounded_clip_stack,
601 ..
602 } = self;
603 clip_stack.clear();
604 clip_stack.push(root_clip);
605 rounded_clip_stack.clear();
606 rounded_clip_stack.push(None);
607 if text_layout_cache.len() > TEXT_LAYOUT_CACHE_LIMIT {
608 text_layout_cache.clear();
609 }
610 for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
611 let cmd_index: usize = clamped_start + offset;
612 let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
613 match cmd {
614 DrawCommand::PushClip(rect) => {
615 let phys: Rect = snap_physical_rect(*rect, scale);
616 let next: Rect = active_clip.intersect(phys).unwrap_or_default();
617 clip_stack.push(next);
618 rounded_clip_stack.push(None);
619 }
620 DrawCommand::PushRoundedClip { rect, radius } => {
621 let phys: Rect = snap_physical_rect(*rect, scale);
622 let next: Rect = active_clip.intersect(phys).unwrap_or_default();
623 clip_stack.push(next);
624 let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
625 if phys.get_width() > 0.0
626 && phys.get_height() > 0.0
627 && phys_r.max_radius() > 0.25
628 {
629 rounded_clip_stack.push(Some(RoundedClipMask {
630 rect: phys,
631 radius: phys_r,
632 }));
633 } else {
634 rounded_clip_stack.push(None);
635 }
636 }
637 DrawCommand::PopClip => {
638 if clip_stack.len() > 1 {
639 clip_stack.pop();
640 let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
641 }
642 }
643 DrawCommand::Clear(_) => {
644 let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
645 let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
646 if y0 < y1 {
647 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
648 rounded_clip_stack.as_slice(),
649 &mut rounded_clips,
650 active_clip,
651 );
652 prepped.push(PreppedCommand {
653 cmd_index,
654 active_clip,
655 y0,
656 y1,
657 opaque_cutout_h: Rect::default(),
658 opaque_cutout_v: Rect::default(),
659 text_layout_idx: u32::MAX,
660 rounded_clip_start: rc_start,
661 rounded_clip_len: rc_len,
662 });
663 }
664 }
665 DrawCommand::FillRoundedRect { rect, .. }
666 | DrawCommand::LinearGradientRect { rect, .. }
667 | DrawCommand::Image { rect, .. }
668 | DrawCommand::SpriteRegion { rect, .. } => {
669 let phys: Rect = snap_physical_rect(*rect, scale);
670 if let Some(vis) = phys.intersect(active_clip) {
671 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
672 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
673 if y0 < y1 {
674 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
675 rounded_clip_stack.as_slice(),
676 &mut rounded_clips,
677 vis,
678 );
679 prepped.push(PreppedCommand {
680 cmd_index,
681 active_clip,
682 y0,
683 y1,
684 opaque_cutout_h: Rect::default(),
685 opaque_cutout_v: Rect::default(),
686 text_layout_idx: u32::MAX,
687 rounded_clip_start: rc_start,
688 rounded_clip_len: rc_len,
689 });
690 }
691 }
692 }
693 DrawCommand::BoxShadow { rect, shadow, .. } => {
694 if shadow.get_color().get_a() == 0 {
695 continue;
696 }
697 let spread: f32 = shadow.get_spread_radius() * scale;
698 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
699 let sigma: f32 = (blur * 0.5).max(0.75);
700 let pad: f32 = (sigma * 3.0).ceil();
701 let base_rect: Rect = snap_physical_rect(*rect, scale);
702 let caster_rect: Rect = Rect::new(
703 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
704 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
705 (base_rect.get_width() + spread * 2.0).max(1.0),
706 (base_rect.get_height() + spread * 2.0).max(1.0),
707 );
708 let shadow_rect: Rect = Rect::new(
709 caster_rect.get_x() - pad,
710 caster_rect.get_y() - pad,
711 caster_rect.get_width() + pad * 2.0,
712 caster_rect.get_height() + pad * 2.0,
713 );
714 if let Some(vis) = shadow_rect.intersect(active_clip) {
715 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
716 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
717 if y0 < y1 {
718 let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
719 commands.get(cmd_index + 1),
720 scale,
721 );
722 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
723 rounded_clip_stack.as_slice(),
724 &mut rounded_clips,
725 vis,
726 );
727 prepped.push(PreppedCommand {
728 cmd_index,
729 active_clip,
730 y0,
731 y1,
732 opaque_cutout_h: cut_h,
733 opaque_cutout_v: cut_v,
734 text_layout_idx: u32::MAX,
735 rounded_clip_start: rc_start,
736 rounded_clip_len: rc_len,
737 });
738 }
739 }
740 }
741 DrawCommand::TextRun { rect, text, style } => {
742 if text.is_empty() || style.get_color().get_a() == 0 {
743 continue;
744 }
745 let phys_rect: Rect = Self::scale_rect(*rect, scale);
746 let pad: f32 = style.get_font_size() * scale * 0.5;
747 let expanded: Rect = Rect::new(
748 phys_rect.get_x() - pad,
749 phys_rect.get_y() - pad,
750 phys_rect.get_width() + pad * 2.0,
751 phys_rect.get_height() + pad * 2.0,
752 );
753 let Some(vis) = expanded.intersect(active_clip) else {
754 continue;
755 };
756 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
757 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
758 if y0 >= y1 {
759 continue;
760 }
761 let max_w: f32 = rect.get_width().max(1.0);
762 let cache_key: (u64, u32) = (
763 hash_text_layout_key(text, *style),
764 (max_w * 10.0).round() as u32,
765 );
766 let layout: TextLayoutResult =
767 if let Some(cached) = text_layout_cache.get(&cache_key) {
768 cached.clone()
769 } else {
770 let measured: TextLayoutResult =
771 measurer.measure(text, *style, Some(max_w));
772 text_layout_cache.insert(cache_key, measured.clone());
773 measured
774 };
775 let phys_font_size: f32 = style.get_font_size() * scale;
776 for line in layout.get_lines().iter() {
777 for ch in line.get_text().chars() {
778 if ch != ' ' {
779 let key: GlyphKey =
780 GlyphKey::from_text_style(ch, phys_font_size, *style);
781 let _: &RasterizedGlyph =
782 glyph_atlas.get_or_rasterize_with(key, font_provider);
783 }
784 }
785 }
786 let layout_idx: u32 = text_layouts.len() as u32;
787 text_layouts.push(layout);
788 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
789 rounded_clip_stack.as_slice(),
790 &mut rounded_clips,
791 vis,
792 );
793 prepped.push(PreppedCommand {
794 cmd_index,
795 active_clip,
796 y0,
797 y1,
798 opaque_cutout_h: Rect::default(),
799 opaque_cutout_v: Rect::default(),
800 text_layout_idx: layout_idx,
801 rounded_clip_start: rc_start,
802 rounded_clip_len: rc_len,
803 });
804 }
805 DrawCommand::TextCaret {
806 content_rect,
807 text,
808 style,
809 color,
810 multiline,
811 ..
812 } => {
813 if color.get_a() == 0 {
814 continue;
815 }
816 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
817 let Some(vis) = phys_content.intersect(active_clip) else {
818 continue;
819 };
820 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
821 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
822 if y0 >= y1 {
823 continue;
824 }
825 let max_w: Option<f32> = if *multiline {
826 Some(content_rect.get_width().max(1.0))
827 } else {
828 None
829 };
830 let layout: TextLayoutResult = measurer.measure(text, *style, max_w);
831 let phys_font_size: f32 = style.get_font_size() * scale;
832 for line in layout.get_lines().iter() {
833 for ch in line.get_text().chars() {
834 if ch != ' ' {
835 let key: GlyphKey =
836 GlyphKey::from_text_style(ch, phys_font_size, *style);
837 let _: &RasterizedGlyph =
838 glyph_atlas.get_or_rasterize_with(key, font_provider);
839 }
840 }
841 }
842 let layout_idx: u32 = text_layouts.len() as u32;
843 text_layouts.push(layout);
844 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
845 rounded_clip_stack.as_slice(),
846 &mut rounded_clips,
847 vis,
848 );
849 prepped.push(PreppedCommand {
850 cmd_index,
851 active_clip,
852 y0,
853 y1,
854 opaque_cutout_h: Rect::default(),
855 opaque_cutout_v: Rect::default(),
856 text_layout_idx: layout_idx,
857 rounded_clip_start: rc_start,
858 rounded_clip_len: rc_len,
859 });
860 }
861 DrawCommand::Line {
862 from, to, width, ..
863 } => {
864 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
865 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
866 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
867 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
868 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
869 if let Some(vis) =
870 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
871 {
872 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
873 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
874 if y0 < y1 {
875 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
876 rounded_clip_stack.as_slice(),
877 &mut rounded_clips,
878 vis,
879 );
880 prepped.push(PreppedCommand {
881 cmd_index,
882 active_clip,
883 y0,
884 y1,
885 opaque_cutout_h: Rect::default(),
886 opaque_cutout_v: Rect::default(),
887 text_layout_idx: u32::MAX,
888 rounded_clip_start: rc_start,
889 rounded_clip_len: rc_len,
890 });
891 }
892 }
893 }
894 DrawCommand::Circle { center, radius, .. } => {
895 let r: f32 = radius * scale + 1.0;
896 let bounds: Rect = Rect::new(
897 center.get_x() * scale - r,
898 center.get_y() * scale - r,
899 r * 2.0,
900 r * 2.0,
901 );
902 if let Some(vis) = bounds.intersect(active_clip) {
903 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
904 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
905 if y0 < y1 {
906 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
907 rounded_clip_stack.as_slice(),
908 &mut rounded_clips,
909 vis,
910 );
911 prepped.push(PreppedCommand {
912 cmd_index,
913 active_clip,
914 y0,
915 y1,
916 opaque_cutout_h: Rect::default(),
917 opaque_cutout_v: Rect::default(),
918 text_layout_idx: u32::MAX,
919 rounded_clip_start: rc_start,
920 rounded_clip_len: rc_len,
921 });
922 }
923 }
924 }
925 DrawCommand::Triangle { p0, p1, p2, .. } => {
926 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
927 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
928 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
929 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
930 if let Some(vis) =
931 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
932 {
933 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
934 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
935 if y0 < y1 {
936 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
937 rounded_clip_stack.as_slice(),
938 &mut rounded_clips,
939 vis,
940 );
941 prepped.push(PreppedCommand {
942 cmd_index,
943 active_clip,
944 y0,
945 y1,
946 opaque_cutout_h: Rect::default(),
947 opaque_cutout_v: Rect::default(),
948 text_layout_idx: u32::MAX,
949 rounded_clip_start: rc_start,
950 rounded_clip_len: rc_len,
951 });
952 }
953 }
954 }
955 }
956 }
957 (prepped, text_layouts, rounded_clips)
958 }
959
960 #[must_use]
972 fn collect_active_rounded(
973 stack: &[Option<RoundedClipMask>],
974 out: &mut Vec<RoundedClipMask>,
975 vis: Rect,
976 ) -> (u32, u16) {
977 let start: u32 = out.len() as u32;
978 for entry in stack.iter().copied().flatten() {
979 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
980 out.push(entry);
981 }
982 }
983 let len: u16 = (out.len() as u32)
984 .saturating_sub(start)
985 .min(u16::MAX as u32) as u16;
986 (start, len)
987 }
988
989 #[must_use]
1000 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
1001 let Some(DrawCommand::FillRoundedRect {
1002 rect,
1003 color,
1004 radius,
1005 ..
1006 }) = next_cmd
1007 else {
1008 return (Rect::default(), Rect::default());
1009 };
1010 if color.get_a() != 255 {
1011 return (Rect::default(), Rect::default());
1012 }
1013 let phys: Rect = snap_physical_rect(*rect, scale);
1014 let r_max: f32 = Self::scale_radius(*radius, scale)
1015 .max_radius()
1016 .min(phys.get_width() * 0.5)
1017 .min(phys.get_height() * 0.5);
1018 let pad: f32 = 1.5;
1019 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
1020 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
1021 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
1022 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
1023 } else {
1024 Rect::default()
1025 };
1026 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
1027 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
1028 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
1029 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
1030 } else {
1031 Rect::default()
1032 };
1033 (cut_h, cut_v)
1034 }
1035
1036 pub(crate) fn render_band(
1052 band: &mut PixelBand<'_>,
1053 commands: &[DrawCommand],
1054 prepped: &[PreppedCommand],
1055 text_layouts: &[TextLayoutResult],
1056 rounded_clips: &[RoundedClipMask],
1057 glyph_atlas: &GlyphAtlas,
1058 render_opts: (f32, AntialiasingMode),
1059 ) -> usize {
1060 let (scale, aa): (f32, AntialiasingMode) = render_opts;
1061 let band_y0: u32 = band.y_offset();
1062 let band_y1: u32 = band.y_end();
1063 let fb_w: u32 = band.width();
1064 let band_rect: Rect =
1065 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
1066 let mut corner_boxes: Vec<(u32, u32, u32, u32)> = Vec::new();
1067 let mut saved_corners: Vec<[u8; 4]> = Vec::new();
1068 let mut shaded: usize = 0;
1069 for item in prepped.iter() {
1070 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
1071 continue;
1072 }
1073 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
1074 continue;
1075 };
1076 let rc_len: usize = item.get_rounded_clip_len() as usize;
1077 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
1078 let start: usize = item.get_rounded_clip_start() as usize;
1079 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
1080 &rounded_clips[start..end]
1081 } else {
1082 &[]
1083 };
1084 let has_corner_mask: bool = if !item_masks.is_empty() {
1085 corner_boxes.clear();
1086 saved_corners.clear();
1087 for mask in item_masks.iter().copied() {
1088 collect_rounded_clip_boxes(
1089 mask,
1090 active_clip,
1091 (fb_w, band_y0, band_y1),
1092 &mut corner_boxes,
1093 );
1094 }
1095 if corner_boxes.is_empty() {
1096 false
1097 } else {
1098 for &(bx0, by0, bx1, by1) in corner_boxes.iter() {
1099 for y in by0..by1 {
1100 for x in bx0..bx1 {
1101 saved_corners.push(band.get_pixel_rgba(x, y));
1102 }
1103 }
1104 }
1105 true
1106 }
1107 } else {
1108 false
1109 };
1110 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
1111 shaded += match cmd {
1112 DrawCommand::Clear(color) => {
1113 if active_clip.get_x() <= 0.0
1114 && active_clip.get_width() >= (band.width() as f32)
1115 && active_clip.get_y() <= (band_y0 as f32)
1116 && active_clip.bottom() >= (band_y1 as f32)
1117 {
1118 band.clear(*color);
1119 (band.width() as usize) * ((band_y1 - band_y0) as usize)
1120 } else {
1121 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
1122 }
1123 }
1124 DrawCommand::FillRoundedRect {
1125 rect,
1126 color,
1127 radius,
1128 border,
1129 } => {
1130 let phys_rect: Rect = snap_physical_rect(*rect, scale);
1131 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
1132 let bw: f32 = if border.get_width() > 0.0 {
1133 (border.get_width() * scale).max(1.0)
1134 } else {
1135 0.0
1136 };
1137 let phys_border: Border = Border::new(bw, border.get_color());
1138 Self::raster_rounded_rect(
1139 band,
1140 phys_rect,
1141 *color,
1142 phys_radius,
1143 phys_border,
1144 active_clip,
1145 aa,
1146 )
1147 }
1148 DrawCommand::LinearGradientRect {
1149 rect,
1150 gradient,
1151 radius,
1152 } => {
1153 let phys_rect: Rect = snap_physical_rect(*rect, scale);
1154 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
1155 Self::raster_gradient_rect(
1156 band,
1157 phys_rect,
1158 *gradient,
1159 phys_radius,
1160 active_clip,
1161 aa,
1162 )
1163 }
1164 DrawCommand::BoxShadow {
1165 rect,
1166 radius,
1167 shadow,
1168 } => {
1169 let spread: f32 = shadow.get_spread_radius() * scale;
1170 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
1171 let sigma: f32 = (blur * 0.5).max(0.75);
1172 let pad: f32 = (sigma * 3.0).ceil();
1173 let base_rect: Rect = snap_physical_rect(*rect, scale);
1174 let caster_rect: Rect = Rect::new(
1175 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
1176 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
1177 (base_rect.get_width() + spread * 2.0).max(1.0),
1178 (base_rect.get_height() + spread * 2.0).max(1.0),
1179 );
1180 let shadow_rect: Rect = Rect::new(
1181 caster_rect.get_x() - pad,
1182 caster_rect.get_y() - pad,
1183 caster_rect.get_width() + pad * 2.0,
1184 caster_rect.get_height() + pad * 2.0,
1185 );
1186 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
1187 let phys_radius: CornerRadius = CornerRadius::new(
1188 (raw_r.get_top_left() + spread).max(0.0),
1189 (raw_r.get_top_right() + spread).max(0.0),
1190 (raw_r.get_bottom_right() + spread).max(0.0),
1191 (raw_r.get_bottom_left() + spread).max(0.0),
1192 );
1193 Self::raster_shadow(
1194 band,
1195 (shadow_rect, caster_rect, active_clip),
1196 phys_radius,
1197 sigma,
1198 shadow.get_color(),
1199 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
1200 )
1201 }
1202 DrawCommand::TextRun { rect, style, .. } => {
1203 let lidx: usize = item.get_text_layout_idx() as usize;
1204 if let Some(layout) = text_layouts.get(lidx) {
1205 Self::raster_text_run_band(
1206 band,
1207 *rect,
1208 layout,
1209 *style,
1210 scale,
1211 active_clip,
1212 glyph_atlas,
1213 )
1214 } else {
1215 0
1216 }
1217 }
1218 DrawCommand::TextCaret {
1219 text_rect,
1220 content_rect,
1221 style,
1222 caret_height,
1223 color,
1224 multiline,
1225 ..
1226 } => {
1227 let lidx: usize = item.get_text_layout_idx() as usize;
1228 let phys_font_size: f32 = style.get_font_size() * scale;
1229 let letter_sp: f32 = style.get_letter_spacing() * scale;
1230 let space_adv: f32 = measure_char_advance(' ', *style) * scale;
1231 let glyphs: &HashMap<GlyphKey, RasterizedGlyph> = glyph_atlas.get_glyphs();
1232 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
1233 if let Some(layout) = text_layouts.get(lidx) {
1234 let lh: f32 = layout.get_line_height_px() * scale;
1235 let idx: usize = layout.get_lines().len().saturating_sub(1);
1236 let w_phys: f32 = layout
1237 .get_lines()
1238 .last()
1239 .map(|line: &TextLine| {
1240 let mut acc: f32 = 0.0;
1241 for ch in line.get_text().chars() {
1242 if ch == ' ' {
1243 acc += space_adv + letter_sp;
1244 } else {
1245 let key: GlyphKey = GlyphKey::from_text_style(
1246 ch,
1247 phys_font_size,
1248 *style,
1249 );
1250 let adv: f32 = glyphs
1251 .get(&key)
1252 .map(|g: &RasterizedGlyph| {
1253 (g.get_advance() as f32).max(1.0)
1254 })
1255 .unwrap_or(space_adv);
1256 acc += adv + letter_sp;
1257 }
1258 }
1259 acc
1260 })
1261 .unwrap_or(0.0);
1262 (w_phys, idx, lh)
1263 } else {
1264 (
1265 0.0,
1266 0,
1267 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
1268 )
1269 };
1270 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
1271 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
1272 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0)
1273 .max(content_rect.get_x() * scale);
1274 let caret_x_phys: f32 =
1275 (text_rect.get_x() * scale + last_w_phys + 1.5 * scale).min(max_x);
1276 let caret_y_phys: f32 = if *multiline {
1277 let raw_y: f32 = content_rect.get_y() * scale
1278 + (line_idx as f32) * line_h_phys
1279 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
1280 raw_y
1281 .min(content_rect.bottom() * scale - caret_h_phys)
1282 .max(content_rect.get_y() * scale)
1283 } else {
1284 content_rect.get_y() * scale
1285 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
1286 };
1287 let caret_rect: Rect = Rect::new(
1288 caret_x_phys.round(),
1289 caret_y_phys.round(),
1290 caret_w_phys.round().max(1.0),
1291 caret_h_phys.round().max(2.0),
1292 );
1293 Self::raster_rounded_rect(
1294 band,
1295 caret_rect,
1296 *color,
1297 CornerRadius::all(0.5 * scale),
1298 Border::default(),
1299 active_clip,
1300 aa,
1301 )
1302 }
1303 DrawCommand::Image {
1304 rect,
1305 buffer,
1306 radius,
1307 } => {
1308 let phys_rect: Rect = snap_physical_rect(*rect, scale);
1309 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
1310 Self::raster_image(band, phys_rect, buffer, phys_radius, active_clip, aa)
1311 }
1312 DrawCommand::Line {
1313 from,
1314 to,
1315 color,
1316 width,
1317 } => {
1318 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
1319 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
1320 Self::raster_line(
1321 band,
1322 p0,
1323 p1,
1324 *color,
1325 (width * scale).max(1.0),
1326 active_clip,
1327 aa,
1328 )
1329 }
1330 DrawCommand::Circle {
1331 center,
1332 radius,
1333 color,
1334 } => {
1335 let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
1336 Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
1337 }
1338 DrawCommand::Triangle { p0, p1, p2, color } => {
1339 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
1340 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
1341 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
1342 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
1343 }
1344 DrawCommand::SpriteRegion {
1345 rect,
1346 buffer,
1347 src_rect,
1348 tint,
1349 } => {
1350 let phys_rect: Rect = snap_physical_rect(*rect, scale);
1351 Self::raster_sprite_region(
1352 band,
1353 phys_rect,
1354 buffer,
1355 *src_rect,
1356 *tint,
1357 active_clip,
1358 aa,
1359 )
1360 }
1361 DrawCommand::PushClip(_)
1362 | DrawCommand::PushRoundedClip { .. }
1363 | DrawCommand::PopClip => 0,
1364 };
1365 if has_corner_mask {
1366 let multi_mask: bool = item_masks.len() > 1;
1367 let mut saved_idx: usize = 0;
1368 for (box_idx, &(bx0, by0, bx1, by1)) in corner_boxes.iter().enumerate() {
1369 for y in by0..by1 {
1370 for x in bx0..bx1 {
1371 let saved_rgba: [u8; 4] = saved_corners[saved_idx];
1372 saved_idx += 1;
1373 if multi_mask
1374 && corner_boxes[..box_idx].iter().any(
1375 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
1376 x >= px0 && x < px1 && y >= py0 && y < py1
1377 },
1378 )
1379 {
1380 continue;
1381 }
1382 let mut cov: f32 = 1.0;
1383 for mask in item_masks.iter().copied() {
1384 cov *= rounded_clip_coverage(x, y, mask, aa);
1385 if cov <= 0.0005 {
1386 break;
1387 }
1388 }
1389 if cov <= 0.0005 {
1390 band.set_pixel_rgba(x, y, saved_rgba);
1391 } else if cov < 0.9995 {
1392 band.lerp_pixel_from_saved_linear(x, y, saved_rgba, cov);
1393 }
1394 }
1395 }
1396 }
1397 }
1398 }
1399 shaded
1400 }
1401
1402 fn scale_rect(rect: Rect, scale: f32) -> Rect {
1413 Rect::new(
1414 rect.get_x() * scale,
1415 rect.get_y() * scale,
1416 rect.get_width() * scale,
1417 rect.get_height() * scale,
1418 )
1419 }
1420
1421 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
1432 CornerRadius::new(
1433 radius.get_top_left() * scale,
1434 radius.get_top_right() * scale,
1435 radius.get_bottom_right() * scale,
1436 radius.get_bottom_left() * scale,
1437 )
1438 }
1439
1440 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
1453 if color.get_a() == 0 {
1454 return 0;
1455 }
1456 let Some(vis) = rect.intersect(clip) else {
1457 return 0;
1458 };
1459 let fb_w: u32 = band.width();
1460 let band_y0: u32 = band.y_offset();
1461 let band_y1: u32 = band.y_end();
1462 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1463 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1464 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1465 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1466 if x0 >= x1 || y0 >= y1 {
1467 return 0;
1468 }
1469 let span_len: usize = (x1 - x0) as usize;
1470 let rows: usize = (y1 - y0) as usize;
1471 let sa: u8 = color.get_a();
1472 if sa < 255 && span_len.saturating_mul(rows) >= 512 {
1473 let luts: ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) = build_linear_blend_luts(color);
1474 for y in y0..y1 {
1475 band.fill_span_linear_luts(x0, x1, y, &luts);
1476 }
1477 } else {
1478 for y in y0..y1 {
1479 band.fill_span_linear(x0, x1, y, color);
1480 }
1481 }
1482 span_len * rows
1483 }
1484
1485 fn raster_rounded_rect(
1501 band: &mut PixelBand<'_>,
1502 rect: Rect,
1503 color: Color,
1504 radius: CornerRadius,
1505 border: Border,
1506 clip: Rect,
1507 aa: AntialiasingMode,
1508 ) -> usize {
1509 let Some(vis) = rect.intersect(clip) else {
1510 return 0;
1511 };
1512 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1513 if radius.max_radius() <= 0.0 && !has_border {
1514 return Self::fill_rect_clipped(band, rect, color, clip);
1515 }
1516 let half_w: f32 = rect.get_width() * 0.5;
1517 let half_h: f32 = rect.get_height() * 0.5;
1518 let cx: f32 = rect.get_x() + half_w;
1519 let cy: f32 = rect.get_y() + half_h;
1520 let border_w: f32 = border.get_width();
1521 let fb_w: u32 = band.width();
1522 let band_y0: u32 = band.y_offset();
1523 let band_y1: u32 = band.y_end();
1524 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1525 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1526 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1527 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1528 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
1529 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
1530 let edge_inset: f32 = border_w + 1.5;
1531 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1532 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
1533 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1534 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
1535 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1536 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
1537 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
1538 let has_center_band: bool = cx0 < cx1;
1539 let interior_luts: Option<RgbaLutQuad> = if has_interior
1540 && color.get_a() > 0
1541 && color.get_a() < 255
1542 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
1543 {
1544 Some(build_linear_blend_luts(color))
1545 } else {
1546 None
1547 };
1548 let mut shaded: usize = 0;
1549 for y in y0..y1 {
1550 let py: f32 = (y as f32) + 0.5 - cy;
1551 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
1552 if has_interior && y >= iy0 && y < iy1 {
1553 for x in x0..ix0 {
1554 shaded += Self::shade_rounded_pixel(
1555 band,
1556 (x, y),
1557 box_geom,
1558 radius,
1559 color,
1560 border,
1561 aa,
1562 );
1563 }
1564 if color.get_a() > 0 {
1565 if let Some(ref luts) = interior_luts {
1566 band.fill_span_linear_luts(ix0, ix1, y, luts);
1567 } else {
1568 band.fill_span_linear(ix0, ix1, y, color);
1569 }
1570 shaded += (ix1 - ix0) as usize;
1571 }
1572 for x in ix1..x1 {
1573 shaded += Self::shade_rounded_pixel(
1574 band,
1575 (x, y),
1576 box_geom,
1577 radius,
1578 color,
1579 border,
1580 aa,
1581 );
1582 }
1583 } else if has_center_band {
1584 for x in x0..cx0 {
1585 shaded += Self::shade_rounded_pixel(
1586 band,
1587 (x, y),
1588 box_geom,
1589 radius,
1590 color,
1591 border,
1592 aa,
1593 );
1594 }
1595 let dist_y: f32 = py.abs() - half_h;
1596 let outer_cov: f32 = sdf_coverage(dist_y, aa);
1597 if outer_cov > 0.0 {
1598 if has_border {
1599 let inner_hh: f32 = (half_h - border_w).max(0.0);
1600 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
1601 sdf_coverage(py.abs() - inner_hh, aa)
1602 } else {
1603 0.0
1604 };
1605 let mixed: Color = composite_fill_and_border(
1606 color,
1607 border.get_color(),
1608 outer_cov,
1609 inner_cov,
1610 );
1611 if mixed.get_a() > 0 {
1612 band.fill_span_linear(cx0, cx1, y, mixed);
1613 }
1614 shaded += (cx1 - cx0) as usize;
1615 } else if color.get_a() > 0 {
1616 band.fill_span_linear(cx0, cx1, y, color.multiply_alpha(outer_cov));
1617 shaded += (cx1 - cx0) as usize;
1618 }
1619 }
1620 for x in cx1..x1 {
1621 shaded += Self::shade_rounded_pixel(
1622 band,
1623 (x, y),
1624 box_geom,
1625 radius,
1626 color,
1627 border,
1628 aa,
1629 );
1630 }
1631 } else {
1632 for x in x0..x1 {
1633 shaded += Self::shade_rounded_pixel(
1634 band,
1635 (x, y),
1636 box_geom,
1637 radius,
1638 color,
1639 border,
1640 aa,
1641 );
1642 }
1643 }
1644 }
1645 shaded
1646 }
1647
1648 fn shade_rounded_pixel(
1664 band: &mut PixelBand<'_>,
1665 pos: (u32, u32),
1666 geom: (f32, f32, f32, f32),
1667 radius: CornerRadius,
1668 color: Color,
1669 border: Border,
1670 aa: AntialiasingMode,
1671 ) -> usize {
1672 let (x, y): (u32, u32) = pos;
1673 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
1674 let px: f32 = (x as f32) + 0.5 - cx;
1675 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1676 .min(half_w)
1677 .min(half_h);
1678 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1679 if dist > 0.85 {
1680 return 0;
1681 }
1682 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1683 let bw: f32 = if has_border { border.get_width() } else { 0.0 };
1684 if !has_border {
1685 if dist < -0.85 {
1686 if color.get_a() > 0 {
1687 band.blend_pixel_linear_dithered(x, y, color, 0.0);
1688 return 1;
1689 }
1690 return 0;
1691 }
1692 let in_corner_edge: bool = aa != AntialiasingMode::None
1693 && corner_r > 0.5
1694 && px.abs() > (half_w - corner_r - 1.5)
1695 && py.abs() > (half_h - corner_r - 1.5);
1696 let outer_cov: f32 = if in_corner_edge {
1697 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1698 } else {
1699 sdf_coverage(dist, aa)
1700 };
1701 if outer_cov > 0.0 && color.get_a() > 0 {
1702 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
1703 band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
1704 return 1;
1705 }
1706 return 0;
1707 }
1708 if dist < -(bw + 0.85) {
1709 if color.get_a() > 0 {
1710 band.blend_pixel_linear_dithered(x, y, color, 0.0);
1711 return 1;
1712 }
1713 return 0;
1714 }
1715 let inner_hw: f32 = (half_w - bw).max(0.0);
1716 let inner_hh: f32 = (half_h - bw).max(0.0);
1717 let inner_r: f32 = (corner_r - bw).max(0.0);
1718 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1719 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
1720 } else {
1721 2.0
1722 };
1723 if dist < -0.85 && inner_dist > 0.85 {
1724 band.blend_pixel_linear_dithered(x, y, border.get_color(), 0.0);
1725 return 1;
1726 }
1727 let in_corner_zone: bool = aa != AntialiasingMode::None
1728 && corner_r > 0.5
1729 && px.abs() > (half_w - corner_r - 1.5)
1730 && py.abs() > (half_h - corner_r - 1.5);
1731 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
1732 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
1733 } else {
1734 let oc: f32 = sdf_coverage(dist, aa);
1735 if oc <= 0.0 {
1736 return 0;
1737 }
1738 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1739 sdf_coverage(inner_dist, aa)
1740 } else {
1741 0.0
1742 };
1743 (oc, ic)
1744 };
1745 if outer_cov <= 0.0 {
1746 return 0;
1747 }
1748 let mixed: Color =
1749 composite_fill_and_border(color, border.get_color(), outer_cov, inner_cov);
1750 if mixed.get_a() > 0 {
1751 band.blend_pixel_linear_dithered(x, y, mixed, 0.0);
1752 return 1;
1753 }
1754 0
1755 }
1756
1757 fn raster_gradient_rect(
1772 band: &mut PixelBand<'_>,
1773 rect: Rect,
1774 gradient: LinearGradient,
1775 radius: CornerRadius,
1776 clip: Rect,
1777 aa: AntialiasingMode,
1778 ) -> usize {
1779 let Some(vis) = rect.intersect(clip) else {
1780 return 0;
1781 };
1782 let rad: f32 = gradient.get_angle_deg().to_radians();
1783 let dir_x: f32 = rad.sin();
1784 let dir_y: f32 = rad.cos();
1785 let half_w: f32 = rect.get_width() * 0.5;
1786 let half_h: f32 = rect.get_height() * 0.5;
1787 let cx: f32 = rect.get_x() + half_w;
1788 let cy: f32 = rect.get_y() + half_h;
1789 let inv_w: f32 = if rect.get_width() > 0.0 {
1790 1.0 / rect.get_width()
1791 } else {
1792 0.0
1793 };
1794 let inv_h: f32 = if rect.get_height() > 0.0 {
1795 1.0 / rect.get_height()
1796 } else {
1797 0.0
1798 };
1799 let fb_w: u32 = band.width();
1800 let band_y0: u32 = band.y_offset();
1801 let band_y1: u32 = band.y_end();
1802 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1803 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1804 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1805 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1806 let mut shaded: usize = 0;
1807 for y in y0..y1 {
1808 let py: f32 = (y as f32) + 0.5 - cy;
1809 let ny: f32 = ((y as f32) - rect.get_y()) * inv_h;
1810 for x in x0..x1 {
1811 let px: f32 = (x as f32) + 0.5 - cx;
1812 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1813 .min(half_w)
1814 .min(half_h);
1815 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1816 if dist > 0.85 {
1817 continue;
1818 }
1819 let cov: f32 = if dist < -0.85 {
1820 1.0
1821 } else {
1822 let in_corner: bool = aa != AntialiasingMode::None
1823 && corner_r > 0.5
1824 && px.abs() > (half_w - corner_r - 1.5)
1825 && py.abs() > (half_h - corner_r - 1.5);
1826 if in_corner {
1827 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1828 } else {
1829 sdf_coverage(dist, aa)
1830 }
1831 };
1832 if cov <= 0.0 {
1833 continue;
1834 }
1835 let nx: f32 = ((x as f32) - rect.get_x()) * inv_w;
1836 let t: f32 = ((nx - 0.5) * dir_x + (ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
1837 let base_sample: Color =
1838 gradient.get_start_color().lerp(gradient.get_end_color(), t);
1839 let alpha_f: f32 = ((base_sample.get_a() as f32) * (1.0 / 255.0)) * cov;
1840 let dither: f32 = interleaved_gradient_noise(x, y);
1841 band.blend_pixel_f32_dithered(x, y, base_sample, alpha_f, dither);
1842 shaded += 1;
1843 }
1844 }
1845 shaded
1846 }
1847
1848 #[must_use]
1861 fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
1862 let (cut_h, cut_v): (Rect, Rect) = cutouts;
1863 let yf: f32 = (y as f32) + 0.5;
1864 if cut_h.get_width() > 0.0
1865 && cut_h.get_height() > 0.0
1866 && yf >= cut_h.get_y()
1867 && yf < cut_h.bottom()
1868 {
1869 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1870 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
1871 return (cx0, cx1);
1872 }
1873 if cut_v.get_width() > 0.0
1874 && cut_v.get_height() > 0.0
1875 && yf >= cut_v.get_y()
1876 && yf < cut_v.bottom()
1877 {
1878 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1879 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
1880 return (cx0, cx1);
1881 }
1882 (x1, x1)
1883 }
1884
1885 fn raster_shadow(
1900 band: &mut PixelBand<'_>,
1901 rects: (Rect, Rect, Rect),
1902 radius: CornerRadius,
1903 sigma: f32,
1904 color: Color,
1905 cutouts: (Rect, Rect),
1906 ) -> usize {
1907 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
1908 if color.get_a() == 0 {
1909 return 0;
1910 }
1911 let Some(vis) = shadow_rect.intersect(clip) else {
1912 return 0;
1913 };
1914 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
1915 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
1916 let cx: f32 = caster_rect.get_x() + half_w;
1917 let cy: f32 = caster_rect.get_y() + half_h;
1918 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
1919 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
1920 let cutoff: f32 = sigma * 3.0;
1921 let fb_w: u32 = band.width();
1922 let band_y0: u32 = band.y_offset();
1923 let band_y1: u32 = band.y_end();
1924 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1925 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1926 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1927 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1928 let r_max: f32 = radius.max_radius();
1929 let inner_inset: f32 = cutoff + r_max;
1930 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1931 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
1932 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1933 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
1934 let has_mid_x: bool = sx0 < sx1;
1935 let has_mid_y: bool = sy0 < sy1;
1936 let mut shaded: usize = 0;
1937 for y in y0..y1 {
1938 let py: f32 = (y as f32) + 0.5 - cy;
1939 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, x0, x1);
1940 let spans: [(u32, u32); 2] = if cut0 < cut1 {
1941 [(x0, cut0), (cut1, x1)]
1942 } else {
1943 [(x0, x1), (x1, x1)]
1944 };
1945 if has_mid_x && has_mid_y && y >= sy0 && y < sy1 {
1946 for (rx0, rx1) in spans.into_iter() {
1947 let left_end: u32 = rx1.min(sx0);
1948 for x in rx0..left_end {
1949 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1950 if dist < cutoff {
1951 let alpha_f: f32 =
1952 base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1953 if alpha_f > 0.0005 {
1954 band.blend_pixel_f32_dithered(
1955 x,
1956 y,
1957 color,
1958 alpha_f,
1959 interleaved_gradient_noise(x, y),
1960 );
1961 shaded += 1;
1962 }
1963 }
1964 }
1965 let right_start: u32 = rx0.max(sx1);
1966 for x in right_start..rx1 {
1967 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1968 if dist < cutoff {
1969 let alpha_f: f32 =
1970 base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1971 if alpha_f > 0.0005 {
1972 band.blend_pixel_f32_dithered(
1973 x,
1974 y,
1975 color,
1976 alpha_f,
1977 interleaved_gradient_noise(x, y),
1978 );
1979 shaded += 1;
1980 }
1981 }
1982 }
1983 }
1984 } else if has_mid_x {
1985 let dist_y: f32 = py.abs() - half_h;
1986 let mid_alpha: f32 = if dist_y < cutoff {
1987 base_alpha * fast_gaussian_shadow_falloff(dist_y, inv_sigma)
1988 } else {
1989 0.0
1990 };
1991 for (rx0, rx1) in spans.into_iter() {
1992 if rx0 >= rx1 {
1993 continue;
1994 }
1995 let l_end: u32 = rx1.min(sx0);
1996 for x in rx0..l_end {
1997 let px: f32 = (x as f32) + 0.5 - cx;
1998 let cr: f32 = quadrant_corner_radius(radius, px, py);
1999 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
2000 if dist < cutoff {
2001 let alpha_f: f32 =
2002 base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
2003 if alpha_f > 0.0005 {
2004 band.blend_pixel_f32_dithered(
2005 x,
2006 y,
2007 color,
2008 alpha_f,
2009 interleaved_gradient_noise(x, y),
2010 );
2011 shaded += 1;
2012 }
2013 }
2014 }
2015 let m_start: u32 = rx0.max(sx0);
2016 let m_end: u32 = rx1.min(sx1);
2017 if mid_alpha > 0.0005 && m_start < m_end {
2018 band.blend_shadow_span_const_alpha(m_start, m_end, y, color, mid_alpha);
2019 shaded += (m_end - m_start) as usize;
2020 }
2021 let r_start: u32 = rx0.max(sx1);
2022 for x in r_start..rx1 {
2023 let px: f32 = (x as f32) + 0.5 - cx;
2024 let cr: f32 = quadrant_corner_radius(radius, px, py);
2025 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
2026 if dist < cutoff {
2027 let alpha_f: f32 =
2028 base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
2029 if alpha_f > 0.0005 {
2030 band.blend_pixel_f32_dithered(
2031 x,
2032 y,
2033 color,
2034 alpha_f,
2035 interleaved_gradient_noise(x, y),
2036 );
2037 shaded += 1;
2038 }
2039 }
2040 }
2041 }
2042 } else {
2043 for (rx0, rx1) in spans.into_iter() {
2044 for x in rx0..rx1 {
2045 let px: f32 = (x as f32) + 0.5 - cx;
2046 let cr: f32 = quadrant_corner_radius(radius, px, py);
2047 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
2048 if dist >= cutoff {
2049 continue;
2050 }
2051 let alpha_f: f32 =
2052 base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
2053 if alpha_f > 0.0005 {
2054 band.blend_pixel_f32_dithered(
2055 x,
2056 y,
2057 color,
2058 alpha_f,
2059 interleaved_gradient_noise(x, y),
2060 );
2061 shaded += 1;
2062 }
2063 }
2064 }
2065 }
2066 }
2067 shaded
2068 }
2069
2070 fn raster_text_run_band(
2086 band: &mut PixelBand<'_>,
2087 rect: Rect,
2088 layout: &TextLayoutResult,
2089 style: TextStyle,
2090 scale: f32,
2091 clip: Rect,
2092 glyph_atlas: &GlyphAtlas,
2093 ) -> usize {
2094 let phys_font_size: f32 = style.get_font_size() * scale;
2095 let line_h_phys: f32 = layout.get_line_height_px() * scale;
2096 let box_w_phys: f32 = rect.get_width() * scale;
2097 let color: Color = style.get_color();
2098 let fb_w: i32 = band.width() as i32;
2099 let band_y0: i32 = band.y_offset() as i32;
2100 let band_y1: i32 = band.y_end() as i32;
2101 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
2102 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
2103 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
2104 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
2105 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
2106 return 0;
2107 }
2108 let letter_sp: f32 = style.get_letter_spacing() * scale;
2109 let space_adv: f32 = measure_char_advance(' ', style) * scale;
2110 let glyphs: &HashMap<GlyphKey, RasterizedGlyph> = glyph_atlas.get_glyphs();
2111 let base_x_phys: f32 = (rect.get_x() * scale).round();
2112 let base_y_phys: f32 = (rect.get_y() * scale).round();
2113 let mut shaded: usize = 0;
2114 for (line_idx, line) in layout.get_lines().iter().enumerate() {
2115 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
2116 let pen_y: f32 = base_y_phys + line_off_y;
2117 if (pen_y + line_h_phys) < (clip_y0 as f32) || pen_y > (clip_y1 as f32) {
2118 continue;
2119 }
2120 let align_x: f32 = match style.get_align() {
2121 TextAlign::Left => 0.0,
2122 TextAlign::Center | TextAlign::Right => {
2123 let mut line_w_phys: f32 = 0.0;
2124 for ch in line.get_text().chars() {
2125 if ch == ' ' {
2126 line_w_phys += space_adv + letter_sp;
2127 } else {
2128 let key: GlyphKey =
2129 GlyphKey::from_text_style(ch, phys_font_size, style);
2130 let adv: f32 = glyphs
2131 .get(&key)
2132 .map(|g: &RasterizedGlyph| (g.get_advance() as f32).max(1.0))
2133 .unwrap_or(space_adv);
2134 line_w_phys += adv + letter_sp;
2135 }
2136 }
2137 if style.get_align() == TextAlign::Center {
2138 ((box_w_phys - line_w_phys) * 0.5).max(0.0)
2139 } else {
2140 (box_w_phys - line_w_phys).max(0.0)
2141 }
2142 }
2143 };
2144 let mut pen_x: f32 = base_x_phys + align_x.round();
2145 for ch in line.get_text().chars() {
2146 if ch == ' ' {
2147 pen_x += space_adv + letter_sp;
2148 continue;
2149 }
2150 if pen_x > (clip_x1 as f32) {
2151 break;
2152 }
2153 let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_size, style);
2154 let Some(glyph) = glyphs.get(&key) else {
2155 pen_x += space_adv + letter_sp;
2156 continue;
2157 };
2158 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2159 let gx0: i32 = pen_x.round() as i32;
2160 let glyph_v_off: f32 = ((line_h_phys - (glyph.get_height() as f32)) * 0.5).round();
2161 let gy0: i32 = (pen_y + glyph_v_off) as i32;
2162 let gw: i32 = glyph.get_width() as i32;
2163 let gh: i32 = glyph.get_height() as i32;
2164 let py_start: i32 = (clip_y0 - gy0).max(0);
2165 let py_end: i32 = (clip_y1 - gy0).min(gh);
2166 let px_start: i32 = (clip_x0 - gx0).max(0);
2167 let px_end: i32 = (clip_x1 - gx0).min(gw);
2168 if py_start < py_end && px_start < px_end {
2169 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
2170 let gw_usize: usize = gw as usize;
2171 let dx: u32 = (gx0 + px_start) as u32;
2172 let start_u: usize = px_start as usize;
2173 let end_u: usize = px_end as usize;
2174 for py in py_start..py_end {
2175 let dy: u32 = (gy0 + py) as u32;
2176 let row_off: usize = (py as usize) * gw_usize;
2177 let row_slice: &[u8] = &cov_bytes[row_off + start_u..row_off + end_u];
2178 shaded += band.blend_glyph_row(dx, dy, row_slice, color);
2179 }
2180 }
2181 pen_x += adv_phys;
2182 }
2183 }
2184 shaded
2185 }
2186
2187 fn blit_bilinear_row(
2197 geom: (usize, usize, f32, f32, f32),
2198 src_dims: (usize, usize),
2199 x_lut: &[(usize, usize, u32)],
2200 src_bytes: &[u8],
2201 dst_row: &mut [u8],
2202 ) {
2203 let (y, x0, rect_y, inv_dst_h, src_h_f): (usize, usize, f32, f32, f32) = geom;
2204 let (src_w_usize, max_sy): (usize, usize) = src_dims;
2205 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
2206 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
2207 let sy0: usize = (fy.floor() as usize).min(max_sy);
2208 let sy1: usize = (sy0 + 1).min(max_sy);
2209 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
2210 let iwy: u32 = 256 - wy;
2211 let row0: usize = sy0 * src_w_usize;
2212 let row1: usize = sy1 * src_w_usize;
2213 let src_len: usize = src_bytes.len();
2214 for (lx, &(sx0, sx1, wx)) in x_lut.iter().enumerate() {
2215 let i00: usize = (row0 + sx0) * 4;
2216 let i10: usize = (row0 + sx1) * 4;
2217 let i01: usize = (row1 + sx0) * 4;
2218 let i11: usize = (row1 + sx1) * 4;
2219 if i11 + 4 > src_len {
2220 continue;
2221 }
2222 let didx: usize = (x0 + lx) * 4;
2223 if didx + 4 > dst_row.len() {
2224 continue;
2225 }
2226 let iwx: u32 = 256 - wx;
2227 let w00: u32 = iwx * iwy;
2228 let w10: u32 = wx * iwy;
2229 let w01: u32 = iwx * wy;
2230 let w11: u32 = wx * wy;
2231 let a00: u32 = src_bytes[i00 + 3] as u32;
2232 let a10: u32 = src_bytes[i10 + 3] as u32;
2233 let a01: u32 = src_bytes[i01 + 3] as u32;
2234 let a11: u32 = src_bytes[i11 + 3] as u32;
2235 if (a00 & a10 & a01 & a11) == 255 {
2236 dst_row[didx] = (((src_bytes[i00] as u32) * w00
2237 + (src_bytes[i10] as u32) * w10
2238 + (src_bytes[i01] as u32) * w01
2239 + (src_bytes[i11] as u32) * w11
2240 + 32768)
2241 >> 16) as u8;
2242 dst_row[didx + 1] = (((src_bytes[i00 + 1] as u32) * w00
2243 + (src_bytes[i10 + 1] as u32) * w10
2244 + (src_bytes[i01 + 1] as u32) * w01
2245 + (src_bytes[i11 + 1] as u32) * w11
2246 + 32768)
2247 >> 16) as u8;
2248 dst_row[didx + 2] = (((src_bytes[i00 + 2] as u32) * w00
2249 + (src_bytes[i10 + 2] as u32) * w10
2250 + (src_bytes[i01 + 2] as u32) * w01
2251 + (src_bytes[i11 + 2] as u32) * w11
2252 + 32768)
2253 >> 16) as u8;
2254 dst_row[didx + 3] = 255;
2255 continue;
2256 }
2257 let a_val: u32 = (a00 * w00 + a10 * w10 + a01 * w01 + a11 * w11 + 32768) >> 16;
2258 if a_val == 0 {
2259 continue;
2260 }
2261 let r: u32 = ((src_bytes[i00] as u32) * w00
2262 + (src_bytes[i10] as u32) * w10
2263 + (src_bytes[i01] as u32) * w01
2264 + (src_bytes[i11] as u32) * w11
2265 + 32768)
2266 >> 16;
2267 let g: u32 = ((src_bytes[i00 + 1] as u32) * w00
2268 + (src_bytes[i10 + 1] as u32) * w10
2269 + (src_bytes[i01 + 1] as u32) * w01
2270 + (src_bytes[i11 + 1] as u32) * w11
2271 + 32768)
2272 >> 16;
2273 let b: u32 = ((src_bytes[i00 + 2] as u32) * w00
2274 + (src_bytes[i10 + 2] as u32) * w10
2275 + (src_bytes[i01 + 2] as u32) * w01
2276 + (src_bytes[i11 + 2] as u32) * w11
2277 + 32768)
2278 >> 16;
2279 let inv_a: u32 = 255 - a_val;
2280 dst_row[didx] = ((r * a_val + (dst_row[didx] as u32) * inv_a + 127) / 255) as u8;
2281 dst_row[didx + 1] =
2282 ((g * a_val + (dst_row[didx + 1] as u32) * inv_a + 127) / 255) as u8;
2283 dst_row[didx + 2] =
2284 ((b * a_val + (dst_row[didx + 2] as u32) * inv_a + 127) / 255) as u8;
2285 dst_row[didx + 3] = 255;
2286 }
2287 }
2288
2289 fn raster_image(
2304 band: &mut PixelBand<'_>,
2305 rect: Rect,
2306 buffer: &ImageBuffer,
2307 radius: CornerRadius,
2308 clip: Rect,
2309 aa: AntialiasingMode,
2310 ) -> usize {
2311 if buffer.get_width() == 0 || buffer.get_height() == 0 {
2312 return 0;
2313 }
2314 let Some(vis) = rect.intersect(clip) else {
2315 return 0;
2316 };
2317 let half_w: f32 = rect.get_width() * 0.5;
2318 let half_h: f32 = rect.get_height() * 0.5;
2319 let cx: f32 = rect.get_x() + half_w;
2320 let cy: f32 = rect.get_y() + half_h;
2321 let fb_w: u32 = band.width();
2322 let band_y0: u32 = band.y_offset();
2323 let band_y1: u32 = band.y_end();
2324 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2325 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2326 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2327 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2328 let src_w: u32 = buffer.get_width();
2329 let src_h: u32 = buffer.get_height();
2330 let src_bytes: &[u8] = buffer.get_pixels().as_slice();
2331 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
2332 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
2333 let use_bilinear: bool = aa != AntialiasingMode::None
2334 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
2335 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
2336 let has_radius: bool = radius.max_radius() > 0.0;
2337 let max_sx: usize = (src_w as usize).saturating_sub(1);
2338 let max_sy: usize = (src_h as usize).saturating_sub(1);
2339 let src_w_usize: usize = src_w as usize;
2340 if !has_radius && use_bilinear && x0 < x1 && y0 < y1 {
2341 let span_w: usize = (x1 - x0) as usize;
2342 let mut x_lut: Vec<(usize, usize, u32)> = Vec::with_capacity(span_w);
2343 for x in x0..x1 {
2344 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2345 let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
2346 let sx0: usize = (fx.floor() as usize).min(max_sx);
2347 let sx1: usize = (sx0 + 1).min(max_sx);
2348 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
2349 x_lut.push((sx0, sx1, wx));
2350 }
2351 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
2352 let rect_y: f32 = rect.get_y();
2353 let src_h_f: f32 = src_h as f32;
2354 let x0_usize: usize = x0 as usize;
2355 for y in y0..y1 {
2356 if let Some(row_buf) = band.row_slice_mut(y) {
2357 Self::blit_bilinear_row(
2358 (y as usize, x0_usize, rect_y, inv_dst_h, src_h_f),
2359 (src_w_usize, max_sy),
2360 x_lut_ref,
2361 src_bytes,
2362 row_buf,
2363 );
2364 }
2365 }
2366 return span_w * ((y1 - y0) as usize);
2367 }
2368 let mut shaded: usize = 0;
2369 for y in y0..y1 {
2370 let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
2371 let py: f32 = (y as f32) + 0.5 - cy;
2372 if use_bilinear {
2373 let fy: f32 = (v * (src_h as f32) - 0.5).clamp(0.0, max_sy as f32);
2374 let sy0: usize = (fy.floor() as usize).min(max_sy);
2375 let sy1: usize = (sy0 + 1).min(max_sy);
2376 let wy: f32 = fy - (sy0 as f32);
2377 let iwy: f32 = 1.0 - wy;
2378 let row0: usize = sy0 * src_w_usize;
2379 let row1: usize = sy1 * src_w_usize;
2380 for x in x0..x1 {
2381 let cov: f32 = if has_radius {
2382 let px: f32 = (x as f32) + 0.5 - cx;
2383 let cr: f32 = quadrant_corner_radius(radius, px, py);
2384 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2385 } else {
2386 1.0
2387 };
2388 if cov <= 0.0 {
2389 continue;
2390 }
2391 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2392 let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
2393 let sx0: usize = (fx.floor() as usize).min(max_sx);
2394 let sx1: usize = (sx0 + 1).min(max_sx);
2395 let wx: f32 = fx - (sx0 as f32);
2396 let iwx: f32 = 1.0 - wx;
2397 let i00: usize = (row0 + sx0) * 4;
2398 let i10: usize = (row0 + sx1) * 4;
2399 let i01: usize = (row1 + sx0) * 4;
2400 let i11: usize = (row1 + sx1) * 4;
2401 if i11 + 4 <= src_bytes.len() {
2402 let w00: f32 = iwx * iwy;
2403 let w10: f32 = wx * iwy;
2404 let w01: f32 = iwx * wy;
2405 let w11: f32 = wx * wy;
2406 let r: u8 = ((src_bytes[i00] as f32) * w00
2407 + (src_bytes[i10] as f32) * w10
2408 + (src_bytes[i01] as f32) * w01
2409 + (src_bytes[i11] as f32) * w11)
2410 .round() as u8;
2411 let g: u8 = ((src_bytes[i00 + 1] as f32) * w00
2412 + (src_bytes[i10 + 1] as f32) * w10
2413 + (src_bytes[i01 + 1] as f32) * w01
2414 + (src_bytes[i11 + 1] as f32) * w11)
2415 .round() as u8;
2416 let b: u8 = ((src_bytes[i00 + 2] as f32) * w00
2417 + (src_bytes[i10 + 2] as f32) * w10
2418 + (src_bytes[i01 + 2] as f32) * w01
2419 + (src_bytes[i11 + 2] as f32) * w11)
2420 .round() as u8;
2421 let a: u8 = ((src_bytes[i00 + 3] as f32) * w00
2422 + (src_bytes[i10 + 3] as f32) * w10
2423 + (src_bytes[i01 + 3] as f32) * w01
2424 + (src_bytes[i11 + 3] as f32) * w11)
2425 .round() as u8;
2426 let sample: Color = Color::new(r, g, b, a).multiply_alpha(cov);
2427 band.blend_pixel(x, y, sample);
2428 shaded += 1;
2429 }
2430 }
2431 } else {
2432 let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
2433 let row: usize = sy * src_w_usize;
2434 for x in x0..x1 {
2435 let cov: f32 = if has_radius {
2436 let px: f32 = (x as f32) + 0.5 - cx;
2437 let cr: f32 = quadrant_corner_radius(radius, px, py);
2438 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2439 } else {
2440 1.0
2441 };
2442 if cov <= 0.0 {
2443 continue;
2444 }
2445 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2446 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
2447 let idx: usize = (row + sx) * 4;
2448 if idx + 4 <= src_bytes.len() {
2449 let sample: Color = Color::new(
2450 src_bytes[idx],
2451 src_bytes[idx + 1],
2452 src_bytes[idx + 2],
2453 src_bytes[idx + 3],
2454 )
2455 .multiply_alpha(cov);
2456 band.blend_pixel(x, y, sample);
2457 shaded += 1;
2458 }
2459 }
2460 }
2461 }
2462 shaded
2463 }
2464
2465 fn raster_line(
2481 band: &mut PixelBand<'_>,
2482 from: Point,
2483 to: Point,
2484 color: Color,
2485 width: f32,
2486 clip: Rect,
2487 aa: AntialiasingMode,
2488 ) -> usize {
2489 let half_w: f32 = width * 0.5;
2490 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
2491 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
2492 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
2493 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
2494 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2495 else {
2496 return 0;
2497 };
2498 let dx: f32 = to.get_x() - from.get_x();
2499 let dy: f32 = to.get_y() - from.get_y();
2500 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
2501 let fb_w: u32 = band.width();
2502 let band_y0: u32 = band.y_offset();
2503 let band_y1: u32 = band.y_end();
2504 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2505 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2506 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2507 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2508 let mut shaded: usize = 0;
2509 for y in y0..y1 {
2510 let py: f32 = (y as f32) + 0.5;
2511 for x in x0..x1 {
2512 let px: f32 = (x as f32) + 0.5;
2513 let t: f32 = (((px - from.get_x()) * dx + (py - from.get_y()) * dy) / len_sq)
2514 .clamp(0.0, 1.0);
2515 let proj_x: f32 = from.get_x() + t * dx;
2516 let proj_y: f32 = from.get_y() + t * dy;
2517 let dist: f32 =
2518 ((px - proj_x) * (px - proj_x) + (py - proj_y) * (py - proj_y)).sqrt() - half_w;
2519 let cov: f32 = sdf_coverage(dist, aa);
2520 if cov > 0.0 {
2521 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * cov;
2522 band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
2523 shaded += 1;
2524 }
2525 }
2526 }
2527 shaded
2528 }
2529
2530 fn raster_circle(
2545 band: &mut PixelBand<'_>,
2546 center: Point,
2547 radius: f32,
2548 color: Color,
2549 clip: Rect,
2550 aa: AntialiasingMode,
2551 ) -> usize {
2552 if radius <= 0.0 || color.get_a() == 0 {
2553 return 0;
2554 }
2555 let bounds: Rect = Rect::new(
2556 center.get_x() - radius - 1.0,
2557 center.get_y() - radius - 1.0,
2558 (radius + 1.0) * 2.0,
2559 (radius + 1.0) * 2.0,
2560 );
2561 let Some(vis) = bounds.intersect(clip) else {
2562 return 0;
2563 };
2564 let fb_w: u32 = band.width();
2565 let band_y0: u32 = band.y_offset();
2566 let band_y1: u32 = band.y_end();
2567 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2568 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2569 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2570 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2571 let outer_r: f32 = radius + 1.0;
2572 let inner_r: f32 = (radius - 1.0).max(0.0);
2573 let outer_r2: f32 = outer_r * outer_r;
2574 let inner_r2: f32 = inner_r * inner_r;
2575 let cx: f32 = center.get_x();
2576 let cy: f32 = center.get_y();
2577 let mut shaded: usize = 0;
2578 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2579 for y in y0..y1 {
2580 let dy: f32 = (y as f32) + 0.5 - cy;
2581 let dy2: f32 = dy * dy;
2582 if dy2 >= outer_r2 {
2583 continue;
2584 }
2585 let out_dx: f32 = (outer_r2 - dy2).sqrt();
2586 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
2587 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(x0, x1);
2588 if dy2 < inner_r2 && inner_r > 1.0 {
2589 let in_dx: f32 = (inner_r2 - dy2).sqrt();
2590 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
2591 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(row_x0, row_x1);
2592 for x in row_x0..in_x0 {
2593 let dx: f32 = (x as f32) + 0.5 - cx;
2594 let cov: f32 = if aa == AntialiasingMode::None {
2595 sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2596 } else {
2597 circle_supersampled_coverage(dx, dy, radius)
2598 };
2599 if cov > 0.0 {
2600 band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2601 shaded += 1;
2602 }
2603 }
2604 if in_x0 < in_x1 {
2605 band.fill_span_linear(in_x0, in_x1, y, color);
2606 shaded += (in_x1 - in_x0) as usize;
2607 }
2608 for x in in_x1..row_x1 {
2609 let dx: f32 = (x as f32) + 0.5 - cx;
2610 let cov: f32 = if aa == AntialiasingMode::None {
2611 sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2612 } else {
2613 circle_supersampled_coverage(dx, dy, radius)
2614 };
2615 if cov > 0.0 {
2616 band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2617 shaded += 1;
2618 }
2619 }
2620 } else {
2621 for x in row_x0..row_x1 {
2622 let dx: f32 = (x as f32) + 0.5 - cx;
2623 let cov: f32 = if aa == AntialiasingMode::None {
2624 sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2625 } else {
2626 circle_supersampled_coverage(dx, dy, radius)
2627 };
2628 if cov > 0.0 {
2629 band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2630 shaded += 1;
2631 }
2632 }
2633 }
2634 }
2635 shaded
2636 }
2637
2638 fn raster_triangle(
2654 band: &mut PixelBand<'_>,
2655 p0: Point,
2656 p1: Point,
2657 p2: Point,
2658 color: Color,
2659 clip: Rect,
2660 aa: AntialiasingMode,
2661 ) -> usize {
2662 if color.get_a() == 0 {
2663 return 0;
2664 }
2665 let area: f32 = (p1.get_x() - p0.get_x()) * (p2.get_y() - p0.get_y())
2666 - (p1.get_y() - p0.get_y()) * (p2.get_x() - p0.get_x());
2667 if area.abs() < 1e-5 {
2668 return 0;
2669 }
2670 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
2671 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
2672 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
2673 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
2674 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2675 else {
2676 return 0;
2677 };
2678 let fb_w: u32 = band.width();
2679 let band_y0: u32 = band.y_offset();
2680 let band_y1: u32 = band.y_end();
2681 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2682 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2683 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2684 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2685 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
2686 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
2687 let inv_l0: f32 = sign
2688 / (p1.get_x() - p0.get_x())
2689 .hypot(p1.get_y() - p0.get_y())
2690 .max(1e-5);
2691 let inv_l1: f32 = sign
2692 / (p2.get_x() - p1.get_x())
2693 .hypot(p2.get_y() - p1.get_y())
2694 .max(1e-5);
2695 let inv_l2: f32 = sign
2696 / (p0.get_x() - p2.get_x())
2697 .hypot(p0.get_y() - p2.get_y())
2698 .max(1e-5);
2699 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2700 let mut shaded: usize = 0;
2701 for y in y0..y1 {
2702 let py: f32 = (y as f32) + 0.5;
2703 if aa == AntialiasingMode::None {
2704 let mut min_ix: f32 = f32::INFINITY;
2705 let mut max_ix: f32 = f32::NEG_INFINITY;
2706 for (a, b) in edges.iter() {
2707 let ay: f32 = a.get_y();
2708 let by: f32 = b.get_y();
2709 if (ay <= py && by > py) || (by <= py && ay > py) {
2710 let t: f32 = (py - ay) / (by - ay);
2711 let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
2712 min_ix = min_ix.min(ix);
2713 max_ix = max_ix.max(ix);
2714 }
2715 }
2716 if min_ix <= max_ix {
2717 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
2718 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
2719 if sx0 < sx1 {
2720 band.fill_span_linear(sx0, sx1, y, color);
2721 shaded += (sx1 - sx0) as usize;
2722 }
2723 }
2724 continue;
2725 }
2726 for x in clip_x0..clip_x1 {
2727 let px: f32 = (x as f32) + 0.5;
2728 let d0: f32 = ((p1.get_x() - p0.get_x()) * (py - p0.get_y())
2729 - (p1.get_y() - p0.get_y()) * (px - p0.get_x()))
2730 * inv_l0;
2731 if d0 < -0.85 {
2732 continue;
2733 }
2734 let d1: f32 = ((p2.get_x() - p1.get_x()) * (py - p1.get_y())
2735 - (p2.get_y() - p1.get_y()) * (px - p1.get_x()))
2736 * inv_l1;
2737 if d1 < -0.85 {
2738 continue;
2739 }
2740 let d2: f32 = ((p0.get_x() - p2.get_x()) * (py - p2.get_y())
2741 - (p0.get_y() - p2.get_y()) * (px - p2.get_x()))
2742 * inv_l2;
2743 if d2 < -0.85 {
2744 continue;
2745 }
2746 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
2747 band.blend_pixel_linear_dithered(x, y, color, 0.0);
2748 shaded += 1;
2749 continue;
2750 }
2751 let cov: f32 = triangle_supersampled_coverage(px, py, p0, p1, p2);
2752 if cov >= 0.999 {
2753 band.blend_pixel_linear_dithered(x, y, color, 0.0);
2754 shaded += 1;
2755 } else if cov > 0.0 {
2756 band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2757 shaded += 1;
2758 }
2759 }
2760 }
2761 shaded
2762 }
2763
2764 fn raster_sprite_region(
2780 band: &mut PixelBand<'_>,
2781 rect: Rect,
2782 buffer: &ImageBuffer,
2783 src_rect: Rect,
2784 tint: Color,
2785 clip: Rect,
2786 aa: AntialiasingMode,
2787 ) -> usize {
2788 if buffer.get_width() == 0
2789 || buffer.get_height() == 0
2790 || tint.get_a() == 0
2791 || src_rect.get_width() <= 0.0
2792 || src_rect.get_height() <= 0.0
2793 {
2794 return 0;
2795 }
2796 let Some(vis) = rect.intersect(clip) else {
2797 return 0;
2798 };
2799 let fb_w: u32 = band.width();
2800 let band_y0: u32 = band.y_offset();
2801 let band_y1: u32 = band.y_end();
2802 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2803 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2804 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2805 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2806 let buf_w: u32 = buffer.get_width();
2807 let buf_h: u32 = buffer.get_height();
2808 let src_bytes: &[u8] = buffer.get_pixels().as_slice();
2809 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
2810 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
2811 let untinted: bool = tint == COLOR_WHITE;
2812 let tr: u32 = tint.get_r() as u32;
2813 let tg: u32 = tint.get_g() as u32;
2814 let tb: u32 = tint.get_b() as u32;
2815 let ta: u32 = tint.get_a() as u32;
2816 let use_bilinear: bool = aa != AntialiasingMode::None
2817 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
2818 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
2819 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
2820 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
2821 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
2822 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
2823 let buf_w_usize: usize = buf_w as usize;
2824 let mut shaded: usize = 0;
2825 for y in y0..y1 {
2826 let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_h).clamp(0.0, 1.0);
2827 let fy: f32 = (src_rect.get_y() + v * src_rect.get_height() - 0.5)
2828 .clamp(min_sy as f32, max_sy as f32);
2829 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
2830 let sy1: u32 = (sy0 + 1).min(max_sy);
2831 let wy: f32 = if use_bilinear { fy - (sy0 as f32) } else { 0.0 };
2832 let iwy: f32 = 1.0 - wy;
2833 let row0: usize = (sy0 as usize) * buf_w_usize;
2834 let row1: usize = (sy1 as usize) * buf_w_usize;
2835 for x in x0..x1 {
2836 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_w).clamp(0.0, 1.0);
2837 let fx: f32 = (src_rect.get_x() + u * src_rect.get_width() - 0.5)
2838 .clamp(min_sx as f32, max_sx as f32);
2839 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
2840 let sx1: u32 = (sx0 + 1).min(max_sx);
2841 let (sr_u8, sg_u8, sb_u8, sa_u8): (u8, u8, u8, u8) = if use_bilinear {
2842 let wx: f32 = fx - (sx0 as f32);
2843 let iwx: f32 = 1.0 - wx;
2844 let i00: usize = (row0 + (sx0 as usize)) * 4;
2845 let i10: usize = (row0 + (sx1 as usize)) * 4;
2846 let i01: usize = (row1 + (sx0 as usize)) * 4;
2847 let i11: usize = (row1 + (sx1 as usize)) * 4;
2848 if i11 + 4 > src_bytes.len() {
2849 continue;
2850 }
2851 let w00: f32 = iwx * iwy;
2852 let w10: f32 = wx * iwy;
2853 let w01: f32 = iwx * wy;
2854 let w11: f32 = wx * wy;
2855 (
2856 ((src_bytes[i00] as f32) * w00
2857 + (src_bytes[i10] as f32) * w10
2858 + (src_bytes[i01] as f32) * w01
2859 + (src_bytes[i11] as f32) * w11)
2860 .round() as u8,
2861 ((src_bytes[i00 + 1] as f32) * w00
2862 + (src_bytes[i10 + 1] as f32) * w10
2863 + (src_bytes[i01 + 1] as f32) * w01
2864 + (src_bytes[i11 + 1] as f32) * w11)
2865 .round() as u8,
2866 ((src_bytes[i00 + 2] as f32) * w00
2867 + (src_bytes[i10 + 2] as f32) * w10
2868 + (src_bytes[i01 + 2] as f32) * w01
2869 + (src_bytes[i11 + 2] as f32) * w11)
2870 .round() as u8,
2871 ((src_bytes[i00 + 3] as f32) * w00
2872 + (src_bytes[i10 + 3] as f32) * w10
2873 + (src_bytes[i01 + 3] as f32) * w01
2874 + (src_bytes[i11 + 3] as f32) * w11)
2875 .round() as u8,
2876 )
2877 } else {
2878 let idx: usize = (row0 + (sx0 as usize)) * 4;
2879 if idx + 4 > src_bytes.len() {
2880 continue;
2881 }
2882 (
2883 src_bytes[idx],
2884 src_bytes[idx + 1],
2885 src_bytes[idx + 2],
2886 src_bytes[idx + 3],
2887 )
2888 };
2889 if sa_u8 == 0 {
2890 continue;
2891 }
2892 let sample: Color = if untinted {
2893 Color::new(sr_u8, sg_u8, sb_u8, sa_u8)
2894 } else {
2895 let rr: u32 = (sr_u8 as u32) * tr + 128;
2896 let gg: u32 = (sg_u8 as u32) * tg + 128;
2897 let bb: u32 = (sb_u8 as u32) * tb + 128;
2898 let aa_v: u32 = (sa_u8 as u32) * ta + 128;
2899 Color::new(
2900 ((rr + (rr >> 8)) >> 8) as u8,
2901 ((gg + (gg >> 8)) >> 8) as u8,
2902 ((bb + (bb >> 8)) >> 8) as u8,
2903 ((aa_v + (aa_v >> 8)) >> 8) as u8,
2904 )
2905 };
2906 band.blend_pixel(x, y, sample);
2907 shaded += 1;
2908 }
2909 }
2910 shaded
2911 }
2912}