1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
5impl BandWorkerPool {
6 #[must_use]
12 pub(crate) fn new() -> Self {
13 let total: usize = available_parallelism()
14 .map(usize::from)
15 .unwrap_or(4)
16 .clamp(1, BAND_WORKER_MAX_THREADS);
17 let requested_workers: usize = total.saturating_sub(1);
18 let mut slots: Vec<BandWorkerSlot> = Vec::with_capacity(requested_workers);
19 for _ in 0..requested_workers {
20 slots.push(BandWorkerSlot::default());
21 }
22 let shared: Arc<BandPoolShared> = Arc::new(BandPoolShared {
23 active_job: AtomicUsize::new(0),
24 active_workers: AtomicUsize::new(0),
25 spin_limit: AtomicUsize::new(BAND_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed)),
26 shutdown: AtomicUsize::new(0),
27 caller_parked: AlignedAtomicUsize::default(),
28 caller_lock: Mutex::new(()),
29 wake_caller: Condvar::new(),
30 slots,
31 });
32 let mut handles: Vec<JoinHandle<()>> = Vec::with_capacity(requested_workers);
33 for idx in 0..requested_workers {
34 let shared_clone: Arc<BandPoolShared> = Arc::clone(&shared);
35 let name: String = format!("{BAND_WORKER_THREAD_PREFIX}-{idx}");
36 if let Ok(handle) = Builder::new().name(name).spawn(move || {
37 let slot: &BandWorkerSlot = &shared_clone.slots[idx];
38 let mut seen_epoch: usize = 0;
39 loop {
40 let mut spins: u32 = 0;
41 let mut spin_budget: u32 =
42 shared_clone.spin_limit.load(Ordering::Relaxed) as u32;
43 let job_ptr: usize = loop {
44 let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
45 if cur_epoch != seen_epoch {
46 let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
47 if ptr != 0 {
48 seen_epoch = cur_epoch;
49 break ptr;
50 }
51 }
52 if shared_clone.shutdown.load(Ordering::Acquire) != 0 {
53 return;
54 }
55 if spins < spin_budget {
56 spins += 1;
57 if (spins & 63) == 0 {
58 spin_budget =
59 shared_clone.spin_limit.load(Ordering::Relaxed) as u32;
60 }
61 spin_loop();
62 continue;
63 }
64 let Ok(mut guard) = slot.lock.lock() else {
65 return;
66 };
67 slot.parked.store(1, Ordering::SeqCst);
68 let parked_ptr: Option<usize> = loop {
69 let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
70 if locked_epoch != seen_epoch {
71 let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
72 if ptr != 0 {
73 seen_epoch = locked_epoch;
74 break Some(ptr);
75 }
76 }
77 if shared_clone.shutdown.load(Ordering::SeqCst) != 0 {
78 break None;
79 }
80 let Ok(next_guard) = slot.wake.wait(guard) else {
81 break None;
82 };
83 guard = next_guard;
84 };
85 slot.parked.store(0, Ordering::SeqCst);
86 let Some(ptr) = parked_ptr else {
87 return;
88 };
89 break ptr;
90 };
91 let job: &BandJob = unsafe { &*(job_ptr as *const BandJob) };
93 run_band_job_loop(job);
94 let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
95 let finished: usize = job.workers_done.value.fetch_add(1, Ordering::SeqCst) + 1;
96 if finished >= expected
97 && shared_clone.caller_parked.value.load(Ordering::SeqCst) != 0
98 && let Ok(_guard) = shared_clone.caller_lock.lock()
99 {
100 shared_clone.wake_caller.notify_one();
101 }
102 }
103 }) {
104 handles.push(handle);
105 } else {
106 break;
107 }
108 }
109 let worker_count: usize = handles.len();
110 Self {
111 worker_count,
112 dispatch_tasks: Mutex::new(Vec::with_capacity(
113 worker_count.saturating_add(1).saturating_mul(2),
114 )),
115 shared,
116 handles,
117 }
118 }
119
120 fn execute_serial(
135 slice_spec: (&mut [u8], u32, u32, u32, usize),
136 commands: &[DrawCommand],
137 prepped: &[PreppedCommand],
138 aux: BandAuxSlices<'_>,
139 atlas: &GlyphAtlas,
140 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
141 ) -> usize {
142 let (pixels, width, y_offset, height, start_byte): (&mut [u8], u32, u32, u32, usize) =
143 slice_spec;
144 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
145 if let Some(src_buf) = restore.base_pixels {
146 let end_byte: usize = start_byte + pixels.len();
147 if let Some(src_slice) = src_buf.get(start_byte..end_byte) {
148 let x0_clamped: u32 = restore.x0.min(width);
149 let x1_clamped: u32 = restore.x1.clamp(x0_clamped, width);
150 restore_band_strip(
151 pixels,
152 src_slice,
153 (
154 (width as usize) * 4,
155 height as usize,
156 (x0_clamped as usize) * 4,
157 ((x1_clamped - x0_clamped) as usize) * 4,
158 ),
159 restore.scrim_luts,
160 );
161 }
162 }
163 let mut band: PixelBand<'_> = PixelBand {
164 width,
165 y_offset,
166 height,
167 pixels,
168 };
169 SoftwareRenderer::render_band(&mut band, commands, prepped, aux, atlas, (scale, aa))
170 }
171
172 #[must_use]
178 pub(crate) fn total_threads(&self) -> usize {
179 let Self { worker_count, .. } = self;
180 worker_count.saturating_add(1)
181 }
182
183 pub(crate) fn execute(
199 &self,
200 framebuffer: &mut Framebuffer,
201 band_range: (u32, u32, usize, usize),
202 cmd_slices: (&[DrawCommand], &[PreppedCommand]),
203 aux: BandAuxSlices<'_>,
204 atlas: &GlyphAtlas,
205 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
206 ) -> usize {
207 let Self {
208 worker_count,
209 dispatch_tasks,
210 ..
211 } = self;
212 let (y0, y1, band_count, max_workers): (u32, u32, usize, usize) = band_range;
213 let (commands, prepped): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
214 let BandAuxSlices {
215 positioned_glyphs,
216 caret_rects,
217 rounded_clips,
218 corner_masks,
219 } = aux;
220 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
221 let fb_w: u32 = framebuffer.get_width();
222 let fb_h: u32 = framebuffer.get_height();
223 let start_y: u32 = y0.min(fb_h);
224 let end_y: u32 = y1.clamp(start_y, fb_h);
225 let total_rows: u32 = end_y - start_y;
226 if total_rows == 0 || fb_w == 0 {
227 return 0;
228 }
229 let row_stride: usize = (fb_w as usize) * 4;
230 let start_byte: usize = (start_y as usize) * row_stride;
231 let end_byte: usize = (end_y as usize) * row_stride;
232 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
233 return 0;
234 };
235 let strip_count: usize = band_count.max(1).min(total_rows as usize);
236 let worker_budget: usize = (*worker_count).min(max_workers);
237 if worker_budget == 0 || strip_count <= 1 {
238 return Self::execute_serial(
239 (slice, fb_w, start_y, total_rows, start_byte),
240 commands,
241 prepped,
242 aux,
243 atlas,
244 (scale, aa, restore),
245 );
246 }
247 let Ok(mut tasks) = dispatch_tasks.try_lock() else {
248 return Self::execute_serial(
249 (slice, fb_w, start_y, total_rows, start_byte),
250 commands,
251 prepped,
252 aux,
253 atlas,
254 (scale, aa, restore),
255 );
256 };
257 tasks.clear();
258 let rx0_clamped: u32 = restore.x0.min(fb_w);
259 let rx1_clamped: u32 = restore.x1.clamp(rx0_clamped, fb_w);
260 let restore_x0_bytes: usize = (rx0_clamped as usize) * 4;
261 let restore_row_bytes: usize = ((rx1_clamped - rx0_clamped) as usize) * 4;
262 let rows_per: usize = (total_rows as usize).div_ceil(strip_count);
263 let chunk_bytes: usize = rows_per * row_stride;
264 let mut cur_y: u32 = start_y;
265 let mut cur_byte_off: usize = start_byte;
266 for chunk in slice.chunks_mut(chunk_bytes) {
267 let chunk_len: usize = chunk.len();
268 let chunk_rows: u32 = (chunk_len / row_stride) as u32;
269 let base_ptr: usize = if let Some(src_buf) = restore.base_pixels {
270 let byte_end: usize = cur_byte_off + chunk_len;
271 if byte_end <= src_buf.len() {
272 unsafe { src_buf.as_ptr().add(cur_byte_off) as usize }
274 } else {
275 0
276 }
277 } else {
278 0
279 };
280 tasks.push(BandTaskSlice {
281 pixels_ptr: chunk.as_mut_ptr() as usize,
282 pixels_len: chunk_len,
283 width: fb_w,
284 y_start: cur_y,
285 height: chunk_rows,
286 base_src_ptr: base_ptr,
287 restore_x0_bytes,
288 restore_row_bytes,
289 });
290 cur_y += chunk_rows;
291 cur_byte_off += chunk_len;
292 }
293 let scrim_luts_ptr: usize = restore.scrim_luts.map_or(0, |luts: &[[u8; 256]; 4]| {
294 (luts as *const [[u8; 256]; 4]) as usize
295 });
296 let job: BandJob = BandJob {
297 kind: BandJobKind::RasterBands,
298 tasks_ptr: tasks.as_ptr() as usize,
299 tasks_len: tasks.len(),
300 commands_ptr: commands.as_ptr() as usize,
301 commands_len: commands.len(),
302 prepped_ptr: prepped.as_ptr() as usize,
303 prepped_len: prepped.len(),
304 glyphs_ptr: positioned_glyphs.as_ptr() as usize,
305 glyphs_len: positioned_glyphs.len(),
306 caret_rects_ptr: caret_rects.as_ptr() as usize,
307 caret_rects_len: caret_rects.len(),
308 rounded_clips_ptr: rounded_clips.as_ptr() as usize,
309 rounded_clips_len: rounded_clips.len(),
310 corner_masks_ptr: corner_masks.as_ptr() as usize,
311 corner_masks_len: corner_masks.len(),
312 atlas_ptr: (atlas as *const GlyphAtlas) as usize,
313 scrim_luts_ptr,
314 scale,
315 aa,
316 blur_desc: BlurPassDesc::default(),
317 next_idx: AlignedAtomicUsize::default(),
318 workers_done: AlignedAtomicUsize::default(),
319 total_shaded: AlignedAtomicUsize::default(),
320 };
321 let dispatch_workers: usize = worker_budget.min(tasks.len().saturating_sub(1));
322 self.dispatch_job(&job, dispatch_workers)
323 }
324
325 pub(crate) fn execute_blur_pass(
338 &self,
339 kind: BandJobKind,
340 blur_desc: BlurPassDesc,
341 max_workers: usize,
342 ) -> usize {
343 let Self {
344 worker_count,
345 dispatch_tasks,
346 ..
347 } = self;
348 let worker_budget: usize = (*worker_count)
349 .min(max_workers)
350 .min(blur_desc.strip_count.saturating_sub(1));
351 let job: BandJob = BandJob {
352 kind,
353 tasks_ptr: 0,
354 tasks_len: 0,
355 commands_ptr: 0,
356 commands_len: 0,
357 prepped_ptr: 0,
358 prepped_len: 0,
359 glyphs_ptr: 0,
360 glyphs_len: 0,
361 caret_rects_ptr: 0,
362 caret_rects_len: 0,
363 rounded_clips_ptr: 0,
364 rounded_clips_len: 0,
365 corner_masks_ptr: 0,
366 corner_masks_len: 0,
367 atlas_ptr: 0,
368 scrim_luts_ptr: 0,
369 scale: 1.0,
370 aa: AntialiasingMode::None,
371 blur_desc,
372 next_idx: AlignedAtomicUsize::default(),
373 workers_done: AlignedAtomicUsize::default(),
374 total_shaded: AlignedAtomicUsize::default(),
375 };
376 if worker_budget == 0 {
377 run_band_job_loop(&job);
378 return job.total_shaded.value.load(Ordering::Acquire);
379 }
380 let Ok(_guard) = dispatch_tasks.try_lock() else {
381 run_band_job_loop(&job);
382 return job.total_shaded.value.load(Ordering::Acquire);
383 };
384 self.dispatch_job(&job, worker_budget)
385 }
386
387 pub(crate) fn execute_hash_tiles(
397 &self,
398 target_framebuffer: &Framebuffer,
399 hash_tiles: &mut [u64],
400 dirty_bits: Option<&[u64]>,
401 tiles_x: u32,
402 ) {
403 let total_tiles: usize = hash_tiles.len();
404 let total_chunks: usize = total_tiles.div_ceil(16);
405 let Self {
406 worker_count,
407 dispatch_tasks,
408 ..
409 } = self;
410 let worker_budget: usize = (*worker_count).min(5).min(total_chunks.saturating_sub(1));
411 let job: BandJob = BandJob {
412 kind: BandJobKind::HashTiles,
413 tasks_ptr: (target_framebuffer as *const Framebuffer) as usize,
414 tasks_len: total_chunks,
415 commands_ptr: hash_tiles.as_mut_ptr() as usize,
416 commands_len: total_tiles,
417 prepped_ptr: dirty_bits.map_or(0, |blue_val: &[u64]| blue_val.as_ptr() as usize),
418 prepped_len: tiles_x as usize,
419 glyphs_ptr: 0,
420 glyphs_len: 0,
421 caret_rects_ptr: 0,
422 caret_rects_len: 0,
423 rounded_clips_ptr: 0,
424 rounded_clips_len: 0,
425 corner_masks_ptr: 0,
426 corner_masks_len: 0,
427 atlas_ptr: 0,
428 scrim_luts_ptr: 0,
429 scale: 1.0,
430 aa: AntialiasingMode::None,
431 blur_desc: BlurPassDesc::default(),
432 next_idx: AlignedAtomicUsize::default(),
433 workers_done: AlignedAtomicUsize::default(),
434 total_shaded: AlignedAtomicUsize::default(),
435 };
436 if worker_budget == 0 {
437 run_band_job_loop(&job);
438 return;
439 }
440 let Ok(_guard) = dispatch_tasks.try_lock() else {
441 run_band_job_loop(&job);
442 return;
443 };
444 let _: usize = self.dispatch_job(&job, worker_budget);
445 }
446
447 fn dispatch_job(&self, job: &BandJob, dispatch_workers: usize) -> usize {
459 let Self { shared, .. } = self;
460 if dispatch_workers == 0 {
461 run_band_job_loop(job);
462 return job.total_shaded.value.load(Ordering::Acquire);
463 }
464 shared
465 .active_workers
466 .store(dispatch_workers, Ordering::Relaxed);
467 shared
468 .active_job
469 .store((job as *const BandJob) as usize, Ordering::Release);
470 let active_slots: &[BandWorkerSlot] = &shared.slots[..dispatch_workers];
471 for slot in active_slots.iter() {
472 let next_epoch: usize = slot.epoch.load(Ordering::Relaxed).wrapping_add(1);
473 slot.epoch.store(next_epoch, Ordering::SeqCst);
474 }
475 for slot in active_slots.iter() {
476 if slot.parked.load(Ordering::SeqCst) != 0
477 && let Ok(_guard) = slot.lock.lock()
478 {
479 slot.wake.notify_one();
480 }
481 }
482 run_band_job_loop(job);
483 let caller_spin_limit: u32 = if shared.spin_limit.load(Ordering::Relaxed) > 0 {
484 BAND_CALLER_SPIN_LIMIT_ACTIVE
485 } else {
486 BAND_CALLER_SPIN_LIMIT_IDLE
487 };
488 let mut caller_spins: u32 = 0;
489 while job.workers_done.value.load(Ordering::Acquire) < dispatch_workers {
490 if caller_spins < caller_spin_limit {
491 caller_spins += 1;
492 spin_loop();
493 continue;
494 }
495 if let Ok(mut guard) = shared.caller_lock.lock() {
496 shared.caller_parked.value.store(1, Ordering::SeqCst);
497 while job.workers_done.value.load(Ordering::SeqCst) < dispatch_workers {
498 let Ok(next_guard) = shared.wake_caller.wait(guard) else {
499 break;
500 };
501 guard = next_guard;
502 }
503 shared.caller_parked.value.store(0, Ordering::SeqCst);
504 } else {
505 spin_loop();
506 }
507 }
508 shared.active_job.store(0, Ordering::Release);
509 job.total_shaded.value.load(Ordering::Acquire)
510 }
511}
512
513#[cfg(not(target_arch = "wasm32"))]
515impl Drop for BandWorkerPool {
516 fn drop(&mut self) {
522 let Self {
523 shared, handles, ..
524 } = self;
525 shared.shutdown.store(1, Ordering::SeqCst);
526 for slot in shared.slots.iter() {
527 if let Ok(_guard) = slot.lock.lock() {
528 slot.wake.notify_one();
529 }
530 }
531 for handle in handles.drain(..) {
532 let _: Result<(), Box<dyn Any + Send>> = handle.join();
533 }
534 }
535}
536
537impl TextLayoutCache {
539 #[must_use]
549 pub(crate) fn with_capacity(slot_cap: usize) -> Self {
550 let cap: usize = slot_cap.max(16).next_power_of_two();
551 let entry_cap: usize = cap / 2;
552 Self {
553 slots: vec![EMPTY_TEXT_LAYOUT_SLOT; cap],
554 entries: Vec::with_capacity(entry_cap),
555 entry_keys: Vec::with_capacity(entry_cap),
556 entry_last_used: Vec::with_capacity(entry_cap),
557 entry_bytes: Vec::with_capacity(entry_cap),
558 resident_bytes: 0,
559 budget_bytes: TEXT_LAYOUT_CACHE_BUDGET_BYTES,
560 lru_clock: 0,
561 cache_hits: 0,
562 cache_misses: 0,
563 evictions: 0,
564 }
565 }
566
567 #[inline]
577 #[must_use]
578 fn estimate_entry_bytes(layout: &TextLayoutResult) -> usize {
579 let mut bytes: usize = TEXT_LAYOUT_ENTRY_OVERHEAD_BYTES;
580 for line in layout.get_lines().iter() {
581 bytes = bytes
582 .saturating_add(TEXT_LINE_OVERHEAD_BYTES)
583 .saturating_add(line.get_text().len());
584 }
585 bytes
586 }
587
588 #[must_use]
598 pub(crate) fn stats(&self) -> (u64, u64, u64, usize) {
599 let Self {
600 cache_hits,
601 cache_misses,
602 evictions,
603 resident_bytes,
604 ..
605 } = self;
606 (*cache_hits, *cache_misses, *evictions, *resident_bytes)
607 }
608
609 #[must_use]
620 pub(crate) fn get(&self, idx: u32) -> Option<&TextLayoutResult> {
621 let Self { entries, .. } = self;
622 entries.get(idx as usize)
623 }
624
625 pub(crate) fn evict_lru_if_needed(&mut self) {
631 let Self {
632 slots,
633 entries,
634 entry_keys,
635 entry_last_used,
636 entry_bytes,
637 resident_bytes,
638 budget_bytes,
639 evictions,
640 ..
641 } = self;
642 let effective_budget: usize = if *budget_bytes == 0 {
643 TEXT_LAYOUT_CACHE_BUDGET_BYTES
644 } else {
645 *budget_bytes
646 };
647 let count: usize = entries.len();
648 if count <= TEXT_LAYOUT_CACHE_LIMIT && *resident_bytes <= effective_budget {
649 return;
650 }
651 let target_count: usize = (TEXT_LAYOUT_CACHE_LIMIT * 3) / 4;
652 let target_bytes: usize = (effective_budget * 3) / 4;
653 let mut order: Vec<usize> = (0..count).collect();
654 order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
655 let mut keep: Vec<bool> = vec![true; count];
656 let mut remaining_count: usize = count;
657 let mut remaining_bytes: usize = *resident_bytes;
658 let mut evicted_count: usize = 0;
659 for idx in order.into_iter() {
660 if remaining_count <= target_count && remaining_bytes <= target_bytes {
661 break;
662 }
663 keep[idx] = false;
664 remaining_count = remaining_count.saturating_sub(1);
665 remaining_bytes = remaining_bytes.saturating_sub(entry_bytes[idx]);
666 evicted_count += 1;
667 }
668 if evicted_count == 0 {
669 return;
670 }
671 let mut write_idx: usize = 0;
672 let mut next_resident: usize = 0;
673 for (read_idx, &kept) in keep.iter().enumerate() {
674 if kept {
675 if write_idx != read_idx {
676 entries.swap(write_idx, read_idx);
677 entry_keys.swap(write_idx, read_idx);
678 entry_last_used.swap(write_idx, read_idx);
679 entry_bytes.swap(write_idx, read_idx);
680 }
681 next_resident = next_resident.saturating_add(entry_bytes[write_idx]);
682 write_idx += 1;
683 }
684 }
685 entries.truncate(write_idx);
686 entry_keys.truncate(write_idx);
687 entry_last_used.truncate(write_idx);
688 entry_bytes.truncate(write_idx);
689 *resident_bytes = next_resident;
690 *evictions = evictions.saturating_add(evicted_count as u64);
691 if slots.len() > TEXT_LAYOUT_CACHE_SLOTS {
692 slots.resize(TEXT_LAYOUT_CACHE_SLOTS, EMPTY_TEXT_LAYOUT_SLOT);
693 }
694 slots.fill(EMPTY_TEXT_LAYOUT_SLOT);
695 if !slots.is_empty() {
696 let mask: usize = slots.len() - 1;
697 for (slot_entry_idx, &(key_hash, width_key)) in entry_keys.iter().enumerate() {
698 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
699 while slots[idx].entry_idx != u32::MAX {
700 idx = (idx + 1) & mask;
701 }
702 slots[idx] = TextLayoutSlot {
703 key_hash,
704 width_key,
705 entry_idx: slot_entry_idx as u32,
706 };
707 }
708 }
709 }
710
711 #[inline(always)]
723 #[must_use]
724 fn slot_start(key_hash: u64, width_key: u32, mask: usize) -> usize {
725 let mixed: u64 = (key_hash ^ (width_key as u64)).wrapping_mul(FX_HASH_K64);
726 ((mixed ^ (mixed >> 32)) as usize) & mask
727 }
728
729 fn rehash(&mut self, new_cap: usize) {
736 let cap: usize = new_cap.max(TEXT_LAYOUT_CACHE_SLOTS).next_power_of_two();
737 let mask: usize = cap - 1;
738 let mut next_slots: Vec<TextLayoutSlot> = vec![EMPTY_TEXT_LAYOUT_SLOT; cap];
739 let Self { slots, .. } = self;
740 for old in slots.iter().copied() {
741 if old.entry_idx == u32::MAX {
742 continue;
743 }
744 let mut idx: usize = Self::slot_start(old.key_hash, old.width_key, mask);
745 while next_slots[idx].entry_idx != u32::MAX {
746 idx = (idx + 1) & mask;
747 }
748 next_slots[idx] = old;
749 }
750 *slots = next_slots;
751 }
752
753 pub(crate) fn get_or_insert_with<CallbackFn>(
766 &mut self,
767 key_hash: u64,
768 width_key: u32,
769 compute: CallbackFn,
770 ) -> u32
771 where
772 CallbackFn: FnOnce() -> TextLayoutResult,
773 {
774 let mut empty_slot: Option<usize> = None;
775 {
776 let Self {
777 slots,
778 entry_last_used,
779 lru_clock,
780 cache_hits,
781 ..
782 } = self;
783 if !slots.is_empty() {
784 let mask: usize = slots.len() - 1;
785 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
786 loop {
787 let slot: TextLayoutSlot = slots[idx];
788 if slot.entry_idx == u32::MAX {
789 empty_slot = Some(idx);
790 break;
791 }
792 if slot.key_hash == key_hash && slot.width_key == width_key {
793 *cache_hits = cache_hits.wrapping_add(1);
794 *lru_clock = lru_clock.wrapping_add(1);
795 if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
796 *tick = *lru_clock;
797 }
798 return slot.entry_idx;
799 }
800 idx = (idx + 1) & mask;
801 }
802 }
803 }
804 let measured: TextLayoutResult = compute();
805 let entry_sz: usize = Self::estimate_entry_bytes(&measured);
806 let needs_rehash: bool = {
807 let Self { slots, entries, .. } = self;
808 slots.is_empty() || (entries.len() + 1).saturating_mul(2) > slots.len()
809 };
810 if needs_rehash {
811 let next_cap: usize = {
812 let Self { slots, .. } = self;
813 if slots.is_empty() {
814 TEXT_LAYOUT_CACHE_SLOTS
815 } else {
816 slots.len().saturating_mul(2)
817 }
818 };
819 self.rehash(next_cap);
820 empty_slot = None;
821 }
822 let Self {
823 slots,
824 entries,
825 entry_keys,
826 entry_last_used,
827 entry_bytes,
828 resident_bytes,
829 lru_clock,
830 cache_misses,
831 ..
832 } = self;
833 *cache_misses = cache_misses.wrapping_add(1);
834 *lru_clock = lru_clock.wrapping_add(1);
835 let entry_idx: u32 = entries.len() as u32;
836 entries.push(measured);
837 entry_keys.push((key_hash, width_key));
838 entry_last_used.push(*lru_clock);
839 entry_bytes.push(entry_sz);
840 *resident_bytes = resident_bytes.saturating_add(entry_sz);
841 let target_idx: usize = match empty_slot {
842 Some(idx) => idx,
843 None => {
844 let mask: usize = slots.len() - 1;
845 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
846 while slots[idx].entry_idx != u32::MAX {
847 idx = (idx + 1) & mask;
848 }
849 idx
850 }
851 };
852 slots[target_idx] = TextLayoutSlot {
853 key_hash,
854 width_key,
855 entry_idx,
856 };
857 entry_idx
858 }
859}
860
861impl PositionedGlyphRunCache {
863 pub(crate) fn clear(&mut self) {
869 let Self {
870 slots,
871 glyph_slab,
872 entries,
873 entry_keys,
874 entry_last_used,
875 max_cached_slot,
876 miss_streak,
877 frame_misses,
878 ..
879 } = self;
880 slots.fill(EMPTY_POSITIONED_RUN_SLOT);
881 glyph_slab.clear();
882 entries.clear();
883 entry_keys.clear();
884 entry_last_used.clear();
885 *max_cached_slot = 0;
886 *miss_streak = 0;
887 *frame_misses = 0;
888 }
889
890 pub(crate) fn begin_frame(&mut self) {
896 let Self {
897 miss_streak,
898 frame_misses,
899 ..
900 } = self;
901 if *frame_misses < 8 {
902 *miss_streak = 0;
903 }
904 *frame_misses = 0;
905 }
906
907 #[inline(always)]
917 #[must_use]
918 pub(crate) fn is_streaming(&self) -> bool {
919 let Self { miss_streak, .. } = self;
920 *miss_streak >= 64
921 }
922
923 #[inline(always)]
929 pub(crate) fn record_streaming_miss(&mut self) {
930 let Self {
931 cache_misses,
932 miss_streak,
933 frame_misses,
934 ..
935 } = self;
936 *cache_misses = cache_misses.wrapping_add(1);
937 *miss_streak = miss_streak.saturating_add(1);
938 *frame_misses = frame_misses.saturating_add(1);
939 }
940
941 fn ensure_initialized(&mut self) {
947 let Self {
948 slots,
949 glyph_slab,
950 entries,
951 entry_keys,
952 entry_last_used,
953 evict_keep,
954 evict_slab_scratch,
955 ..
956 } = self;
957 if slots.is_empty() {
958 slots.resize(POSITIONED_RUN_CACHE_SLOTS, EMPTY_POSITIONED_RUN_SLOT);
959 entries.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
960 entry_keys.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
961 entry_last_used.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
962 glyph_slab.reserve_exact(POSITIONED_RUN_GLYPH_SLAB_CAP);
963 evict_keep.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
964 evict_slab_scratch.reserve_exact(POSITIONED_RUN_GLYPH_SLAB_CAP);
965 }
966 }
967
968 pub(crate) fn sync_atlas_epoch(&mut self, atlas: &GlyphAtlas) {
975 let evictions: u64 = atlas.get_evictions();
976 let font_rev: u64 = atlas.get_font_chain_revision();
977 let atlas_len: usize = atlas.len();
978 let needs_clear: bool = {
979 let Self {
980 entries,
981 atlas_evictions,
982 font_chain_revision,
983 max_cached_slot,
984 ..
985 } = self;
986 !entries.is_empty()
987 && (*atlas_evictions != evictions
988 || *font_chain_revision != font_rev
989 || (*max_cached_slot as usize) >= atlas_len)
990 };
991 if needs_clear {
992 self.clear();
993 }
994 let Self {
995 atlas_evictions,
996 font_chain_revision,
997 ..
998 } = self;
999 *atlas_evictions = evictions;
1000 *font_chain_revision = font_rev;
1001 }
1002
1003 #[must_use]
1013 pub(crate) fn stats(&self) -> (u64, u64, usize) {
1014 let Self {
1015 cache_hits,
1016 cache_misses,
1017 entries,
1018 ..
1019 } = self;
1020 (*cache_hits, *cache_misses, entries.len())
1021 }
1022
1023 #[inline(always)]
1036 #[must_use]
1037 fn slot_start(key_hash: u64, width_bits: u32, phys_scale_milli: u32, mask: usize) -> usize {
1038 let packed: u64 = (width_bits as u64) | ((phys_scale_milli as u64) << 32);
1039 let mixed: u64 = (key_hash ^ packed).wrapping_mul(FX_HASH_K64);
1040 ((mixed ^ (mixed >> 32)) as usize) & mask
1041 }
1042
1043 fn compact_lru_to(&mut self, target_count: usize, target_glyphs: usize) {
1051 let Self {
1052 slots,
1053 glyph_slab,
1054 entries,
1055 entry_keys,
1056 entry_last_used,
1057 evict_keep,
1058 evict_slab_scratch,
1059 max_cached_slot,
1060 evictions,
1061 ..
1062 } = self;
1063 let count: usize = entries.len();
1064 if count == 0 {
1065 return;
1066 }
1067 let mut min_tick: u64 = u64::MAX;
1068 let mut max_tick: u64 = 0;
1069 for &tick in entry_last_used.iter().take(count) {
1070 min_tick = min_tick.min(tick);
1071 max_tick = max_tick.max(tick);
1072 }
1073 let mut cutoff: u64 = max_tick.saturating_sub(target_count as u64);
1074 let mut kept_est: usize = 0;
1075 let mut kept_glyphs_est: usize = 0;
1076 for idx in 0..count {
1077 if entry_last_used[idx] > cutoff {
1078 kept_est += 1;
1079 kept_glyphs_est = kept_glyphs_est.saturating_add(entries[idx].glyph_len as usize);
1080 }
1081 }
1082 if kept_est < target_count / 2 && max_tick > min_tick {
1083 let span: u64 = max_tick.saturating_sub(min_tick);
1084 cutoff = min_tick.saturating_add((span.saturating_mul(3)) / 4);
1085 kept_est = 0;
1086 kept_glyphs_est = 0;
1087 for idx in 0..count {
1088 if entry_last_used[idx] > cutoff {
1089 kept_est += 1;
1090 kept_glyphs_est =
1091 kept_glyphs_est.saturating_add(entries[idx].glyph_len as usize);
1092 }
1093 }
1094 }
1095 let _: (usize, usize) = (kept_est, kept_glyphs_est);
1096 evict_keep.clear();
1097 evict_keep.resize(count, false);
1098 let mut kept_count: usize = 0;
1099 let mut kept_glyphs: usize = 0;
1100 for idx in (0..count).rev() {
1101 if entry_last_used[idx] > cutoff {
1102 let g_len: usize = entries[idx].glyph_len as usize;
1103 if kept_count < target_count && kept_glyphs.saturating_add(g_len) <= target_glyphs {
1104 evict_keep[idx] = true;
1105 kept_count += 1;
1106 kept_glyphs = kept_glyphs.saturating_add(g_len);
1107 }
1108 }
1109 }
1110 let evicted_now: usize = count.saturating_sub(kept_count);
1111 if evicted_now == 0 {
1112 return;
1113 }
1114 evict_slab_scratch.clear();
1115 let mut write_idx: usize = 0;
1116 let mut next_max_slot: u32 = 0;
1117 for (read_idx, &kept) in evict_keep.iter().enumerate() {
1118 if kept {
1119 let mut entry: CachedPositionedGlyphRun = entries[read_idx];
1120 let old_s: usize = entry.glyph_start as usize;
1121 let old_e: usize = old_s.saturating_add(entry.glyph_len as usize);
1122 let new_start: u32 = evict_slab_scratch.len() as u32;
1123 if old_e <= glyph_slab.len() {
1124 evict_slab_scratch.extend_from_slice(&glyph_slab[old_s..old_e]);
1125 }
1126 entry.glyph_start = new_start;
1127 entries[write_idx] = entry;
1128 if write_idx != read_idx {
1129 entry_keys[write_idx] = entry_keys[read_idx];
1130 entry_last_used[write_idx] = entry_last_used[read_idx];
1131 }
1132 next_max_slot = next_max_slot.max(entry.max_glyph_slot);
1133 write_idx += 1;
1134 }
1135 }
1136 entries.truncate(write_idx);
1137 entry_keys.truncate(write_idx);
1138 entry_last_used.truncate(write_idx);
1139 swap(glyph_slab, evict_slab_scratch);
1140 evict_slab_scratch.clear();
1141 *max_cached_slot = next_max_slot;
1142 *evictions = evictions.saturating_add(evicted_now as u64);
1143 slots.fill(EMPTY_POSITIONED_RUN_SLOT);
1144 if !slots.is_empty() {
1145 let mask: usize = slots.len() - 1;
1146 for (slot_entry_idx, &(kh, wb, sm)) in entry_keys.iter().enumerate() {
1147 let mut idx: usize = Self::slot_start(kh, wb, sm, mask);
1148 while slots[idx].entry_idx != u32::MAX {
1149 idx = (idx + 1) & mask;
1150 }
1151 slots[idx] = PositionedGlyphRunSlot {
1152 key_hash: kh,
1153 width_bits: wb,
1154 phys_scale_milli: sm,
1155 entry_idx: slot_entry_idx as u32,
1156 };
1157 }
1158 }
1159 }
1160
1161 pub(crate) fn evict_lru_if_needed(&mut self) {
1167 let (count, slab_len): (usize, usize) = {
1168 let Self {
1169 entries,
1170 glyph_slab,
1171 ..
1172 } = self;
1173 (entries.len(), glyph_slab.len())
1174 };
1175 let slab_trigger: usize =
1176 POSITIONED_RUN_GLYPH_SLAB_CAP.saturating_sub(POSITIONED_RUN_MAX_TEXT_LEN);
1177 if count < POSITIONED_RUN_CACHE_LIMIT && slab_len <= slab_trigger {
1178 return;
1179 }
1180 let target_count: usize = POSITIONED_RUN_CACHE_LIMIT / 4;
1181 let target_glyphs: usize = POSITIONED_RUN_GLYPH_SLAB_CAP / 4;
1182 self.compact_lru_to(target_count, target_glyphs);
1183 }
1184
1185 pub(crate) fn lookup(
1198 &mut self,
1199 key_hash: u64,
1200 width_bits: u32,
1201 phys_scale_milli: u32,
1202 ) -> Option<(CachedPositionedGlyphRun, &[PositionedGlyph])> {
1203 let Self {
1204 slots,
1205 glyph_slab,
1206 entries,
1207 entry_last_used,
1208 lru_clock,
1209 cache_hits,
1210 miss_streak,
1211 ..
1212 } = self;
1213 if slots.is_empty() {
1214 return None;
1215 }
1216 let mask: usize = slots.len() - 1;
1217 let mut idx: usize = Self::slot_start(key_hash, width_bits, phys_scale_milli, mask);
1218 loop {
1219 let slot: PositionedGlyphRunSlot = slots[idx];
1220 if slot.entry_idx == u32::MAX {
1221 return None;
1222 }
1223 if slot.key_hash == key_hash
1224 && slot.width_bits == width_bits
1225 && slot.phys_scale_milli == phys_scale_milli
1226 {
1227 *cache_hits = cache_hits.wrapping_add(1);
1228 *miss_streak = 0;
1229 *lru_clock = lru_clock.wrapping_add(1);
1230 if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
1231 *tick = *lru_clock;
1232 }
1233 let run: CachedPositionedGlyphRun = *entries.get(slot.entry_idx as usize)?;
1234 let g_s: usize = run.glyph_start as usize;
1235 let g_e: usize = g_s.saturating_add(run.glyph_len as usize);
1236 let slice: &[PositionedGlyph] = glyph_slab.get(g_s..g_e)?;
1237 return Some((run, slice));
1238 }
1239 idx = (idx + 1) & mask;
1240 }
1241 }
1242
1243 pub(crate) fn insert_with<CallbackFn>(
1256 &mut self,
1257 key: (u64, u32, u32),
1258 max_glyphs: usize,
1259 build_fn: CallbackFn,
1260 ) -> (CachedPositionedGlyphRun, &[PositionedGlyph])
1261 where
1262 CallbackFn: FnOnce(&mut Vec<PositionedGlyph>) -> (bool, u32),
1263 {
1264 self.ensure_initialized();
1265 let needs_evict: bool = {
1266 let Self {
1267 entries,
1268 glyph_slab,
1269 ..
1270 } = self;
1271 entries.len() >= POSITIONED_RUN_CACHE_LIMIT
1272 || glyph_slab.len().saturating_add(max_glyphs) > POSITIONED_RUN_GLYPH_SLAB_CAP
1273 };
1274 if needs_evict {
1275 let target_count: usize = POSITIONED_RUN_CACHE_LIMIT / 4;
1276 let target_glyphs: usize = POSITIONED_RUN_GLYPH_SLAB_CAP
1277 .saturating_sub(max_glyphs.max(POSITIONED_RUN_MAX_TEXT_LEN))
1278 .min(POSITIONED_RUN_GLYPH_SLAB_CAP / 4);
1279 self.compact_lru_to(target_count, target_glyphs);
1280 }
1281 let (key_hash, width_bits, phys_scale_milli): (u64, u32, u32) = key;
1282 let Self {
1283 slots,
1284 glyph_slab,
1285 entries,
1286 entry_keys,
1287 entry_last_used,
1288 lru_clock,
1289 max_cached_slot,
1290 cache_misses,
1291 miss_streak,
1292 frame_misses,
1293 ..
1294 } = self;
1295 let glyph_start: usize = glyph_slab.len();
1296 let (has_fractional_x, max_glyph_slot): (bool, u32) = build_fn(glyph_slab);
1297 let glyph_end: usize = glyph_slab.len();
1298 let run: CachedPositionedGlyphRun = CachedPositionedGlyphRun {
1299 glyph_start: glyph_start as u32,
1300 glyph_len: (glyph_end.saturating_sub(glyph_start)) as u32,
1301 has_fractional_x,
1302 max_glyph_slot,
1303 };
1304 *cache_misses = cache_misses.wrapping_add(1);
1305 *miss_streak = miss_streak.saturating_add(1);
1306 *frame_misses = frame_misses.saturating_add(1);
1307 *lru_clock = lru_clock.wrapping_add(1);
1308 *max_cached_slot = (*max_cached_slot).max(max_glyph_slot);
1309 let entry_idx: u32 = entries.len() as u32;
1310 entries.push(run);
1311 entry_keys.push((key_hash, width_bits, phys_scale_milli));
1312 entry_last_used.push(*lru_clock);
1313 let mask: usize = slots.len() - 1;
1314 let mut idx: usize = Self::slot_start(key_hash, width_bits, phys_scale_milli, mask);
1315 while slots[idx].entry_idx != u32::MAX {
1316 idx = (idx + 1) & mask;
1317 }
1318 slots[idx] = PositionedGlyphRunSlot {
1319 key_hash,
1320 width_bits,
1321 phys_scale_milli,
1322 entry_idx,
1323 };
1324 (run, &glyph_slab[glyph_start..glyph_end])
1325 }
1326}
1327
1328impl CornerMaskCache {
1330 #[must_use]
1340 pub(crate) fn len(&self) -> usize {
1341 let Self { entries } = self;
1342 entries.len()
1343 }
1344
1345 #[must_use]
1355 pub(crate) fn entries(&self) -> &[CachedCornerMask] {
1356 let Self { entries } = self;
1357 entries.as_slice()
1358 }
1359
1360 pub(crate) fn clear(&mut self) {
1366 let Self { entries } = self;
1367 entries.clear();
1368 }
1369
1370 #[must_use]
1382 fn build_quadrant(radius: f32, quadrant: u8, aa_enabled: bool) -> CachedCornerMask {
1383 let dim: usize = (radius + 1.0).ceil().max(1.0) as usize;
1384 let dim_f: f32 = dim as f32;
1385 let half_extent: f32 = dim_f + 64.0;
1386 let cx_lim: f32 = half_extent - radius;
1387 let r_in: f32 = radius - 1.0;
1388 let r_in_sq: f32 = r_in * r_in;
1389 let r_out: f32 = radius + 1.0;
1390 let r_out_sq: f32 = r_out * r_out;
1391 let r_sq: f32 = radius * radius;
1392 let mut cov: Vec<u8> = vec![16; dim * dim];
1393 let mut row_spans: Vec<CornerMaskRowSpan> = Vec::with_capacity(dim);
1394 let is_left: bool = quadrant == 0 || quadrant == 3;
1395 let is_top: bool = quadrant == 0 || quadrant == 1;
1396 for my in 0..dim {
1397 let py: f32 = if is_top {
1398 (my as f32) + 0.5 - half_extent
1399 } else {
1400 (my as f32) + 0.5 + (half_extent - dim_f)
1401 };
1402 let qy: f32 = py.abs() - cx_lim;
1403 let row_off: usize = my * dim;
1404 for mx in 0..dim {
1405 let px: f32 = if is_left {
1406 (mx as f32) + 0.5 - half_extent
1407 } else {
1408 (mx as f32) + 0.5 + (half_extent - dim_f)
1409 };
1410 let qx: f32 = px.abs() - cx_lim;
1411 let hits: u8 = if qx <= 0.0 || qy <= 0.0 {
1412 let dist: f32 = qx.max(qy) - radius;
1413 if dist <= -1.0 {
1414 16
1415 } else if dist >= 1.0 {
1416 0
1417 } else if !aa_enabled {
1418 if dist <= 0.0 { 16 } else { 0 }
1419 } else {
1420 let char_item: f32 = rounded_box_supersampled_coverage(
1421 px,
1422 py,
1423 half_extent,
1424 half_extent,
1425 radius,
1426 0.0,
1427 )
1428 .0;
1429 (char_item * 16.0).round() as u8
1430 }
1431 } else {
1432 let d_sq: f32 = qx * qx + qy * qy;
1433 if r_in >= 0.0 && d_sq <= r_in_sq {
1434 16
1435 } else if d_sq >= r_out_sq {
1436 0
1437 } else if !aa_enabled {
1438 if d_sq <= r_sq { 16 } else { 0 }
1439 } else {
1440 let color_item: f32 = rounded_box_supersampled_coverage(
1441 px,
1442 py,
1443 half_extent,
1444 half_extent,
1445 radius,
1446 0.0,
1447 )
1448 .0;
1449 (color_item * 16.0).round() as u8
1450 }
1451 };
1452 cov[row_off + mx] = hits;
1453 }
1454 let row_slice: &[u8] = &cov[row_off..row_off + dim];
1455 let span: CornerMaskRowSpan = if is_left {
1456 let dirty_end: usize = row_slice
1457 .iter()
1458 .rposition(|&cell_item: &u8| cell_item < 16)
1459 .map(|idx: usize| idx + 1)
1460 .unwrap_or(0);
1461 let ext_end: usize = row_slice
1462 .iter()
1463 .take(dirty_end)
1464 .take_while(|&&component_val: &&u8| component_val == 0)
1465 .count();
1466 CornerMaskRowSpan {
1467 ext_start: 0,
1468 ext_end: ext_end as u16,
1469 aa_start: ext_end as u16,
1470 aa_end: dirty_end as u16,
1471 dirty_start: 0,
1472 dirty_end: dirty_end as u16,
1473 }
1474 } else {
1475 let dirty_start: usize = row_slice
1476 .iter()
1477 .position(|&char_item_primary: &u8| char_item_primary < 16)
1478 .unwrap_or(dim);
1479 let trailing_zeros: usize = row_slice[dirty_start..]
1480 .iter()
1481 .rev()
1482 .take_while(|&&char_item_secondary: &&u8| char_item_secondary == 0)
1483 .count();
1484 let ext_start: usize = dim - trailing_zeros;
1485 CornerMaskRowSpan {
1486 ext_start: ext_start as u16,
1487 ext_end: dim as u16,
1488 aa_start: dirty_start as u16,
1489 aa_end: ext_start.max(dirty_start) as u16,
1490 dirty_start: dirty_start as u16,
1491 dirty_end: dim as u16,
1492 }
1493 };
1494 row_spans.push(span);
1495 }
1496 CachedCornerMask {
1497 radius_bits: radius.to_bits(),
1498 quadrant,
1499 aa_enabled,
1500 dim: dim as u16,
1501 cov,
1502 row_spans,
1503 }
1504 }
1505
1506 fn get_or_build(&mut self, radius: f32, quadrant: u8, aa_enabled: bool) -> u32 {
1519 let bits: u32 = radius.to_bits();
1520 let Self { entries } = self;
1521 for (idx, entry) in entries.iter().enumerate() {
1522 if entry.radius_bits == bits
1523 && entry.quadrant == quadrant
1524 && entry.aa_enabled == aa_enabled
1525 {
1526 return idx as u32;
1527 }
1528 }
1529 let idx: u32 = entries.len() as u32;
1530 entries.push(Self::build_quadrant(radius, quadrant, aa_enabled));
1531 idx
1532 }
1533
1534 pub(crate) fn resolve_quadrants(
1547 &mut self,
1548 rect: Rect,
1549 radius: CornerRadius,
1550 aa: AntialiasingMode,
1551 ) -> [u32; 4] {
1552 let mut ids: [u32; 4] = [u32::MAX; 4];
1553 let half_w: f32 = rect.get_width() * 0.5;
1554 let half_h: f32 = rect.get_height() * 0.5;
1555 let max_r: f32 = half_w.min(half_h).max(0.0);
1556 if max_r <= 0.25 {
1557 return ids;
1558 }
1559 let x0: f32 = rect.get_x();
1560 let y0: f32 = rect.get_y();
1561 let x1: f32 = rect.right();
1562 let y1: f32 = rect.bottom();
1563 if (x0 - x0.round()).abs() > 1e-4
1564 || (y0 - y0.round()).abs() > 1e-4
1565 || (x1 - x1.round()).abs() > 1e-4
1566 || (y1 - y1.round()).abs() > 1e-4
1567 {
1568 return ids;
1569 }
1570 let aa_enabled: bool = aa != AntialiasingMode::None;
1571 let radii: [f32; 4] = [
1572 radius.get_top_left().min(max_r),
1573 radius.get_top_right().min(max_r),
1574 radius.get_bottom_right().min(max_r),
1575 radius.get_bottom_left().min(max_r),
1576 ];
1577 for (query_val, red_val) in radii.into_iter().enumerate() {
1578 if red_val > 0.25 && red_val + 1.5 < half_w && red_val + 1.5 < half_h {
1579 let dim: u32 = (red_val + 1.0).ceil() as u32;
1580 if dim > 0 && dim <= CORNER_MASK_MAX_DIM {
1581 ids[query_val] = self.get_or_build(red_val, query_val as u8, aa_enabled);
1582 }
1583 }
1584 }
1585 ids
1586 }
1587}
1588
1589impl SoftwareRenderer {
1591 #[must_use]
1603 pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
1604 Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
1605 }
1606
1607 #[must_use]
1620 pub fn with_font_provider(
1621 width: u32,
1622 height: u32,
1623 config: RenderConfig,
1624 font_provider: NativeSystemFont,
1625 ) -> Self {
1626 let allocate_cpu_fb: bool = !config.get_direct_gpu_present() && width > 0 && height > 0;
1627 let (
1628 framebuffer,
1629 text_layout_cache,
1630 clip_cap,
1631 prepped_cap,
1632 rc_cap,
1633 glyph_cap,
1634 line_cap,
1635 caret_cap,
1636 ): (
1637 Option<Framebuffer>,
1638 TextLayoutCache,
1639 usize,
1640 usize,
1641 usize,
1642 usize,
1643 usize,
1644 usize,
1645 ) = if allocate_cpu_fb {
1646 (
1647 Some(Framebuffer::allocate(width, height)),
1648 TextLayoutCache::with_capacity(TEXT_LAYOUT_CACHE_SLOTS),
1649 16,
1650 256,
1651 32,
1652 2048,
1653 64,
1654 8,
1655 )
1656 } else {
1657 (None, TextLayoutCache::default(), 0, 0, 0, 0, 0, 0)
1658 };
1659 let cull_cap: usize = if allocate_cpu_fb { 256 } else { 0 };
1660 let sentinel_cap: usize = if allocate_cpu_fb { 32 } else { 0 };
1661 let (hash_tile_cap, hash_dirty_cap): (usize, usize) = if allocate_cpu_fb {
1662 let tx: usize = width.div_ceil(FB_HASH_TILE_W) as usize;
1663 let ty: usize = height.div_ceil(FB_HASH_TILE_H) as usize;
1664 let total: usize = tx.saturating_mul(ty);
1665 (total, total.div_ceil(64))
1666 } else {
1667 (0, 0)
1668 };
1669 Self {
1670 framebuffer,
1671 glyph_atlas: GlyphAtlas::default(),
1672 font_provider,
1673 measurer: DeterministicTextMeasurer,
1674 text_layout_cache,
1675 positioned_glyph_run_cache: PositionedGlyphRunCache::default(),
1676 blur_horiz_scratch: Vec::new(),
1677 cull_keep_scratch: Vec::with_capacity(cull_cap),
1678 cull_compacted_scratch: Vec::with_capacity(cull_cap),
1679 cull_sentinels_scratch: Vec::with_capacity(sentinel_cap),
1680 clip_stack: Vec::with_capacity(clip_cap),
1681 rounded_clip_stack: Vec::with_capacity(clip_cap),
1682 antialiasing: config.get_antialiasing(),
1683 tile_size: config.get_tile_size().max(16),
1684 base_cache_width: 0,
1685 base_cache_height: 0,
1686 base_cache_hash: 0,
1687 prev_base_hash: 0,
1688 base_cache_pixels: Vec::new(),
1689 prepped_scratch: Vec::with_capacity(prepped_cap),
1690 rounded_clips_scratch: Vec::with_capacity(rc_cap),
1691 positioned_glyphs_scratch: Vec::with_capacity(glyph_cap),
1692 line_glyphs_scratch: Vec::with_capacity(line_cap),
1693 caret_rects_scratch: Vec::with_capacity(caret_cap),
1694 corner_mask_cache: CornerMaskCache::default(),
1695 prev_portal_bounds: None,
1696 prev_portal_scrim: None,
1697 prepped_bounds: None,
1698 prepped_fg_bounds: None,
1699 clip_scope_scratch: Vec::with_capacity(clip_cap),
1700 cached_scrim_color: None,
1701 cached_scrim_luts: None,
1702 serial_dispatches: 0,
1703 parallel_dispatches: 0,
1704 culled_occluded_commands: 0,
1705 adaptive_parallel_threshold_pixels: ADAPTIVE_PARALLEL_DEFAULT_PIXELS,
1706 adaptive_threshold_override: 0,
1707 last_serial_us: 0,
1708 last_parallel_us: 0,
1709 rendered_frames: 0,
1710 telemetry_enabled: false,
1711 high_frequency_active: false,
1712 hash_tiles: Vec::with_capacity(hash_tile_cap),
1713 hash_dirty_bits: Vec::with_capacity(hash_dirty_cap),
1714 hash_tiles_w: 0,
1715 hash_tiles_h: 0,
1716 hash_tiles_valid: false,
1717 }
1718 }
1719
1720 fn mark_hash_dirty_rect(&mut self, rect: Rect) {
1727 let Self {
1728 hash_dirty_bits,
1729 hash_tiles_w,
1730 hash_tiles_h,
1731 hash_tiles_valid,
1732 ..
1733 } = self;
1734 if !*hash_tiles_valid || *hash_tiles_w == 0 || *hash_tiles_h == 0 {
1735 return;
1736 }
1737 let width_val: u32 = *hash_tiles_w;
1738 let height_val: u32 = *hash_tiles_h;
1739 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(width_val);
1740 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(height_val);
1741 let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(width_val);
1742 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(height_val);
1743 if x0 >= x1 || y0 >= y1 {
1744 return;
1745 }
1746 let tiles_x: u32 = width_val.div_ceil(FB_HASH_TILE_W);
1747 let tx0: u32 = x0 / FB_HASH_TILE_W;
1748 let tx1: u32 = (x1 - 1) / FB_HASH_TILE_W;
1749 let ty0: u32 = y0 / FB_HASH_TILE_H;
1750 let ty1: u32 = (y1 - 1) / FB_HASH_TILE_H;
1751 for ty in ty0..=ty1 {
1752 let row_base: usize = (ty as usize).saturating_mul(tiles_x as usize);
1753 for tx in tx0..=tx1 {
1754 let tile_idx: usize = row_base.saturating_add(tx as usize);
1755 let word_idx: usize = tile_idx >> 6;
1756 let bit_mask: u64 = 1_u64 << (tile_idx & 63);
1757 if let Some(word) = hash_dirty_bits.get_mut(word_idx) {
1758 *word |= bit_mask;
1759 }
1760 }
1761 }
1762 }
1763
1764 #[must_use]
1774 pub(crate) fn incremental_framebuffer_hash(&mut self) -> u64 {
1775 let Self {
1776 framebuffer,
1777 hash_tiles,
1778 hash_dirty_bits,
1779 hash_tiles_w,
1780 hash_tiles_h,
1781 hash_tiles_valid,
1782 ..
1783 } = self;
1784 let Some(frame_pixels) = framebuffer.as_ref() else {
1785 return EMPTY_FRAMEBUFFER.fnv1a_hash();
1786 };
1787 let width_val: u32 = frame_pixels.get_width();
1788 let height_val: u32 = frame_pixels.get_height();
1789 if width_val == 0 || height_val == 0 || frame_pixels.get_pixels().is_empty() {
1790 *hash_tiles_valid = false;
1791 return frame_pixels.fnv1a_hash();
1792 }
1793 let tiles_x: u32 = width_val.div_ceil(FB_HASH_TILE_W);
1794 let tiles_y: u32 = height_val.div_ceil(FB_HASH_TILE_H);
1795 let total_tiles: usize = (tiles_x as usize).saturating_mul(tiles_y as usize);
1796 if !*hash_tiles_valid
1797 || *hash_tiles_w != width_val
1798 || *hash_tiles_h != height_val
1799 || hash_tiles.len() != total_tiles
1800 {
1801 hash_tiles.resize(total_tiles, 0);
1802 let dirty_words: usize = total_tiles.div_ceil(64);
1803 hash_dirty_bits.clear();
1804 hash_dirty_bits.resize(dirty_words, 0);
1805 #[cfg(not(target_arch = "wasm32"))]
1806 let hashed_parallel: bool = if total_tiles >= 256
1807 && BAND_POOL_STATE.load(Ordering::Acquire) == BAND_POOL_READY
1808 && let Some(pool) = BAND_WORKER_POOL.get()
1809 {
1810 pool.execute_hash_tiles(frame_pixels, hash_tiles.as_mut_slice(), None, tiles_x);
1811 true
1812 } else {
1813 false
1814 };
1815 #[cfg(target_arch = "wasm32")]
1816 let hashed_parallel: bool = false;
1817 if !hashed_parallel {
1818 let mut idx: usize = 0;
1819 for ty in 0..tiles_y {
1820 for tx in 0..tiles_x {
1821 hash_tiles[idx] = frame_pixels.hash_tile_fnv1a(tx, ty);
1822 idx += 1;
1823 }
1824 }
1825 }
1826 *hash_tiles_w = width_val;
1827 *hash_tiles_h = height_val;
1828 *hash_tiles_valid = true;
1829 return Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice());
1830 }
1831 let mut dirty_tile_count: usize = 0;
1832 for &word in hash_dirty_bits.iter() {
1833 dirty_tile_count = dirty_tile_count.saturating_add(word.count_ones() as usize);
1834 }
1835 #[cfg(not(target_arch = "wasm32"))]
1836 if dirty_tile_count >= 256
1837 && BAND_POOL_STATE.load(Ordering::Acquire) == BAND_POOL_READY
1838 && let Some(pool) = BAND_WORKER_POOL.get()
1839 {
1840 pool.execute_hash_tiles(
1841 frame_pixels,
1842 hash_tiles.as_mut_slice(),
1843 Some(hash_dirty_bits.as_slice()),
1844 tiles_x,
1845 );
1846 hash_dirty_bits.fill(0);
1847 return Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice());
1848 }
1849 for (word_idx, word_ref) in hash_dirty_bits.iter_mut().enumerate() {
1850 let mut word: u64 = *word_ref;
1851 if word == 0 {
1852 continue;
1853 }
1854 *word_ref = 0;
1855 let base_tile: usize = word_idx << 6;
1856 while word != 0 {
1857 let bit: usize = word.trailing_zeros() as usize;
1858 word &= word - 1;
1859 let tile_idx: usize = base_tile.saturating_add(bit);
1860 if tile_idx < total_tiles {
1861 let ty: u32 = (tile_idx / (tiles_x as usize)) as u32;
1862 let tx: u32 = (tile_idx % (tiles_x as usize)) as u32;
1863 hash_tiles[tile_idx] = frame_pixels.hash_tile_fnv1a(tx, ty);
1864 }
1865 }
1866 }
1867 Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice())
1868 }
1869
1870 #[must_use]
1880 pub fn get_framebuffer(&self) -> &Framebuffer {
1881 self.framebuffer.as_ref().unwrap_or(&EMPTY_FRAMEBUFFER)
1882 }
1883
1884 #[must_use]
1894 pub fn framebuffer_opt(&self) -> Option<&Framebuffer> {
1895 let Self { framebuffer, .. } = self;
1896 framebuffer.as_ref()
1897 }
1898
1899 #[must_use]
1909 pub fn allocated_framebuffer_bytes(&self) -> usize {
1910 let Self { framebuffer, .. } = self;
1911 framebuffer.as_ref().map_or(0, Framebuffer::allocated_bytes)
1912 }
1913
1914 pub fn release_framebuffer(&mut self) {
1920 let Self {
1921 framebuffer,
1922 base_cache_width,
1923 base_cache_height,
1924 base_cache_hash,
1925 prev_base_hash,
1926 base_cache_pixels,
1927 prev_portal_bounds,
1928 prev_portal_scrim,
1929 ..
1930 } = self;
1931 *framebuffer = None;
1932 *base_cache_width = 0;
1933 *base_cache_height = 0;
1934 *base_cache_hash = 0;
1935 *prev_base_hash = 0;
1936 base_cache_pixels.clear();
1937 base_cache_pixels.shrink_to_fit();
1938 *prev_portal_bounds = None;
1939 *prev_portal_scrim = None;
1940 }
1941
1942 pub(crate) fn ensure_framebuffer(
1954 &mut self,
1955 width: u32,
1956 height: u32,
1957 ) -> (&mut Framebuffer, bool) {
1958 let Self { framebuffer, .. } = self;
1959 let mut resized: bool = false;
1960 let target_framebuffer: &mut Framebuffer = framebuffer.get_or_insert_with(|| {
1961 resized = true;
1962 Framebuffer::allocate(width, height)
1963 });
1964 if !resized {
1965 resized = target_framebuffer.resize(width, height);
1966 }
1967 (target_framebuffer, resized)
1968 }
1969
1970 pub fn set_font_provider(&mut self, font_provider: NativeSystemFont) -> &mut Self {
1981 let Self {
1982 font_provider: slot,
1983 positioned_glyph_run_cache,
1984 ..
1985 } = self;
1986 *slot = font_provider;
1987 positioned_glyph_run_cache.clear();
1988 self
1989 }
1990
1991 pub fn set_high_frequency_active(&mut self, active: bool) {
1998 let Self {
1999 high_frequency_active,
2000 ..
2001 } = self;
2002 *high_frequency_active = active;
2003 set_band_worker_spin_active(active);
2004 }
2005
2006 #[must_use]
2016 pub fn blur_scratch_capacity(&self) -> usize {
2017 self.get_blur_horiz_scratch().capacity()
2018 }
2019
2020 #[must_use]
2030 pub fn positioned_glyph_run_cache_stats(&self) -> (u64, u64, usize) {
2031 self.get_positioned_glyph_run_cache().stats()
2032 }
2033
2034 fn finish_frame_render(&mut self) {
2040 let was_first_frame: bool = self.get_rendered_frames() == 0;
2041 let Self {
2042 rendered_frames, ..
2043 } = self;
2044 *rendered_frames = rendered_frames.saturating_add(1);
2045 if was_first_frame {
2046 warm_band_worker_pool_async();
2047 }
2048 }
2049
2050 pub fn set_adaptive_parallel_threshold(&mut self, min_pixels: Option<usize>) {
2057 let Self {
2058 adaptive_threshold_override,
2059 adaptive_parallel_threshold_pixels,
2060 ..
2061 } = self;
2062 match min_pixels {
2063 Some(px) => {
2064 let clamped: usize = px.max(1);
2065 *adaptive_threshold_override = clamped;
2066 *adaptive_parallel_threshold_pixels = clamped;
2067 }
2068 None => {
2069 *adaptive_threshold_override = 0;
2070 *adaptive_parallel_threshold_pixels = ADAPTIVE_PARALLEL_DEFAULT_PIXELS;
2071 }
2072 }
2073 }
2074
2075 #[must_use]
2085 pub fn adaptive_parallel_threshold(&self) -> usize {
2086 if self.get_adaptive_threshold_override() > 0 {
2087 self.get_adaptive_threshold_override()
2088 } else if self.get_adaptive_parallel_threshold_pixels() > 0 {
2089 self.get_adaptive_parallel_threshold_pixels()
2090 } else {
2091 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
2092 }
2093 }
2094
2095 #[must_use]
2107 fn detect_full_viewport_scrim(
2108 commands: &[DrawCommand],
2109 prepped: &[PreppedCommand],
2110 dims: (u32, u32, f32),
2111 ) -> Option<Color> {
2112 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2113 let first: &PreppedCommand = prepped.first()?;
2114 if first.get_cmd_index() == usize::MAX || first.get_rounded_clip_len() != 0 {
2115 return None;
2116 }
2117 let clip: Rect = first.get_active_clip();
2118 let fw: f32 = phys_w as f32;
2119 let fh: f32 = phys_h as f32;
2120 if clip.get_x() > 0.0 || clip.get_y() > 0.0 || clip.right() < fw || clip.bottom() < fh {
2121 return None;
2122 }
2123 if let DrawCommand::FillRoundedRect {
2124 rect,
2125 color,
2126 radius,
2127 border,
2128 } = &commands[first.get_cmd_index()]
2129 {
2130 let sa: u8 = color.get_alpha();
2131 if sa > 0 && sa < 255 && radius.max_radius() <= 0.0 && border.get_width() <= 0.0 {
2132 let phys: Rect = snap_physical_rect(*rect, scale);
2133 if phys.get_x() <= 0.0
2134 && phys.get_y() <= 0.0
2135 && phys.right() >= fw
2136 && phys.bottom() >= fh
2137 {
2138 return Some(*color);
2139 }
2140 }
2141 }
2142 None
2143 }
2144
2145 #[must_use]
2157 fn rect_pixel_area(rect: Rect, phys_w: u32, phys_h: u32) -> usize {
2158 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(phys_w);
2159 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(phys_h);
2160 let x1: u32 = (rect.right().ceil().max(0.0) as u32).clamp(x0, phys_w);
2161 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).clamp(y0, phys_h);
2162 ((x1 - x0) as usize).saturating_mul((y1 - y0) as usize)
2163 }
2164
2165 pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
2177 let scale: f32 = display_list.get_scale_factor().max(0.5);
2178 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
2179 let phys_h: u32 =
2180 ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
2181 let (_, resized): (&mut Framebuffer, bool) = self.ensure_framebuffer(phys_w, phys_h);
2182 if resized {
2183 self.set_base_cache_hash(0);
2184 self.set_prev_base_hash(0);
2185 self.set_base_cache_width(0);
2186 self.set_base_cache_height(0);
2187 self.set_prev_portal_bounds(None);
2188 self.set_prev_portal_scrim(None);
2189 let Self {
2190 hash_tiles_valid, ..
2191 } = self;
2192 *hash_tiles_valid = false;
2193 }
2194 let effective_damage: DamageRegion = if resized {
2195 DamageRegion::full()
2196 } else {
2197 damage
2198 };
2199 let (norm_rects, norm_count): ([Rect; 8], usize) =
2200 effective_damage.normalized_rects(phys_w, phys_h);
2201 if norm_count == 0 {
2202 return (0, 0);
2203 }
2204 let tile_sz: u32 = self.get_tile_size().max(16);
2205 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
2206 let split: usize = display_list.get_portal_split_index().min(commands.len());
2207 let has_portals: bool = split > 0 && split < commands.len();
2208 if norm_count > 1 {
2209 let mut sum_area: usize = 0;
2210 for sub in norm_rects.iter().take(norm_count) {
2211 sum_area = sum_area.saturating_add(Self::rect_pixel_area(*sub, phys_w, phys_h));
2212 }
2213 let union_area: usize = effective_damage
2214 .resolve(phys_w, phys_h)
2215 .map_or(0, |rect_bounds: Rect| {
2216 Self::rect_pixel_area(rect_bounds, phys_w, phys_h)
2217 });
2218 if sum_area.saturating_mul(4) < union_area.saturating_mul(3) {
2219 if !has_portals {
2220 self.set_base_cache_hash(0);
2221 self.set_prev_base_hash(0);
2222 }
2223 self.set_prev_portal_bounds(None);
2224 self.set_prev_portal_scrim(None);
2225 let mut total_tiles: usize = 0;
2226 let mut total_shaded: usize = 0;
2227 for sub_clip in norm_rects.iter().take(norm_count).copied() {
2228 let tx: usize =
2229 ((sub_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
2230 let ty: usize =
2231 ((sub_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
2232 total_tiles = total_tiles.saturating_add(tx.saturating_mul(ty));
2233 self.prepare_frame_range(
2234 display_list,
2235 (0, commands.len()),
2236 sub_clip,
2237 (phys_w, phys_h, scale),
2238 );
2239 let shaded: usize = self.execute_prepared_bands(
2240 commands,
2241 sub_clip,
2242 (phys_w, phys_h, scale),
2243 (false, None, 0),
2244 );
2245 self.mark_hash_dirty_rect(sub_clip);
2246 total_shaded = total_shaded.saturating_add(shaded);
2247 }
2248 self.finish_frame_render();
2249 return (total_tiles, total_shaded);
2250 }
2251 }
2252 let root_clip: Rect = if norm_count == 1 {
2253 norm_rects[0]
2254 } else {
2255 let Some(resolved) = effective_damage.resolve(phys_w, phys_h) else {
2256 return (0, 0);
2257 };
2258 resolved
2259 };
2260 let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
2261 let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
2262 let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
2263 let is_full_frame: bool = root_clip.get_x() <= 0.0
2264 && root_clip.get_y() <= 0.0
2265 && root_clip.get_width() >= (phys_w as f32)
2266 && root_clip.get_height() >= (phys_h as f32);
2267 if has_portals && is_full_frame {
2268 let base_hash: u64 = display_list.base_layer_hash();
2269 let fb_len: usize = self
2270 .framebuffer_opt()
2271 .map_or(0, |target_framebuffer: &Framebuffer| {
2272 target_framebuffer.get_pixels().len()
2273 });
2274 let cache_hit: bool = base_hash != 0
2275 && self.get_base_cache_hash() == base_hash
2276 && self.get_base_cache_width() == phys_w
2277 && self.get_base_cache_height() == phys_h
2278 && self.get_base_cache_pixels().len() == fb_len;
2279 if cache_hit {
2280 self.prepare_frame_range(
2281 display_list,
2282 (split, commands.len()),
2283 root_clip,
2284 (phys_w, phys_h, scale),
2285 );
2286 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
2287 commands,
2288 self.get_prepped_scratch().as_slice(),
2289 (phys_w, phys_h, scale),
2290 );
2291 let (cur_fg_bounds, prev_scrim, prev_bounds): (
2292 Option<Rect>,
2293 Option<Color>,
2294 Option<Rect>,
2295 ) = {
2296 let Self {
2297 prepped_fg_bounds,
2298 prepped_bounds,
2299 prev_portal_scrim,
2300 prev_portal_bounds,
2301 ..
2302 } = self;
2303 let fg: Option<Rect> = if cur_scrim.is_some() {
2304 *prepped_fg_bounds
2305 } else {
2306 *prepped_bounds
2307 };
2308 (fg, *prev_portal_scrim, *prev_portal_bounds)
2309 };
2310 self.set_prev_portal_scrim(cur_scrim);
2311 self.set_prev_portal_bounds(cur_fg_bounds);
2312 let prepped_start: usize = usize::from(cur_scrim.is_some());
2313 let (portal_rects, portal_count): ([Rect; 8], usize) = if cur_scrim == prev_scrim {
2314 let mut portal_damage: DamageRegion = DamageRegion::default();
2315 if let Some(prev_r) = prev_bounds {
2316 portal_damage.add_rect(prev_r);
2317 }
2318 if let Some(cur_r) = cur_fg_bounds {
2319 portal_damage.add_rect(cur_r);
2320 }
2321 portal_damage.normalized_rects(phys_w, phys_h)
2322 } else {
2323 let mut full_arr: [Rect; 8] = [Rect::default(); 8];
2324 full_arr[0] = root_clip;
2325 (full_arr, 1)
2326 };
2327 if portal_count == 0 {
2328 self.finish_frame_render();
2329 return (tiles_updated, 1);
2330 }
2331 let mut total_portal_shaded: usize = 0;
2332 for dirty_clip in portal_rects.iter().take(portal_count).copied() {
2333 let scrim_shaded: usize = if cur_scrim.is_some() {
2334 Self::rect_pixel_area(dirty_clip, phys_w, phys_h)
2335 } else {
2336 0
2337 };
2338 let band_shaded: usize = self.execute_prepared_bands(
2339 commands,
2340 dirty_clip,
2341 (phys_w, phys_h, scale),
2342 (true, cur_scrim, prepped_start),
2343 );
2344 self.mark_hash_dirty_rect(dirty_clip);
2345 total_portal_shaded = total_portal_shaded
2346 .saturating_add(scrim_shaded)
2347 .saturating_add(band_shaded);
2348 }
2349 self.finish_frame_render();
2350 return (tiles_updated, total_portal_shaded.max(1));
2351 }
2352 self.prepare_frame_range(display_list, (0, split), root_clip, (phys_w, phys_h, scale));
2353 let base_shaded: usize = self.execute_prepared_bands(
2354 commands,
2355 root_clip,
2356 (phys_w, phys_h, scale),
2357 (false, None, 0),
2358 );
2359 let base_stable: bool = base_hash != 0 && self.get_prev_base_hash() == base_hash;
2360 self.set_prev_base_hash(base_hash);
2361 if base_stable {
2362 let Self {
2363 framebuffer,
2364 base_cache_pixels,
2365 base_cache_width,
2366 base_cache_height,
2367 base_cache_hash,
2368 ..
2369 } = self;
2370 if let Some(frame_pixels) = framebuffer.as_ref() {
2371 let src_pixels: &[u8] = frame_pixels.get_pixels().as_slice();
2372 if base_cache_pixels.len() != src_pixels.len() {
2373 base_cache_pixels.resize(src_pixels.len(), 0);
2374 }
2375 base_cache_pixels.copy_from_slice(src_pixels);
2376 *base_cache_width = phys_w;
2377 *base_cache_height = phys_h;
2378 *base_cache_hash = base_hash;
2379 }
2380 }
2381 self.prepare_frame_range(
2382 display_list,
2383 (split, commands.len()),
2384 root_clip,
2385 (phys_w, phys_h, scale),
2386 );
2387 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
2388 commands,
2389 self.get_prepped_scratch().as_slice(),
2390 (phys_w, phys_h, scale),
2391 );
2392 let cur_fg_bounds: Option<Rect> = {
2393 let Self {
2394 prepped_fg_bounds,
2395 prepped_bounds,
2396 ..
2397 } = self;
2398 if cur_scrim.is_some() {
2399 *prepped_fg_bounds
2400 } else {
2401 *prepped_bounds
2402 }
2403 };
2404 self.set_prev_portal_scrim(cur_scrim);
2405 self.set_prev_portal_bounds(cur_fg_bounds);
2406 let portal_shaded: usize = self.execute_prepared_bands(
2407 commands,
2408 root_clip,
2409 (phys_w, phys_h, scale),
2410 (false, None, 0),
2411 );
2412 let Self {
2413 hash_tiles_valid, ..
2414 } = self;
2415 *hash_tiles_valid = false;
2416 self.finish_frame_render();
2417 return (tiles_updated, base_shaded.saturating_add(portal_shaded));
2418 }
2419 if !has_portals {
2420 self.set_base_cache_hash(0);
2421 self.set_prev_base_hash(0);
2422 }
2423 self.set_prev_portal_bounds(None);
2424 self.set_prev_portal_scrim(None);
2425 self.prepare_frame_range(
2426 display_list,
2427 (0, commands.len()),
2428 root_clip,
2429 (phys_w, phys_h, scale),
2430 );
2431 let pixels_shaded: usize = self.execute_prepared_bands(
2432 commands,
2433 root_clip,
2434 (phys_w, phys_h, scale),
2435 (false, None, 0),
2436 );
2437 if is_full_frame {
2438 let Self {
2439 hash_tiles_valid, ..
2440 } = self;
2441 *hash_tiles_valid = false;
2442 } else {
2443 self.mark_hash_dirty_rect(root_clip);
2444 }
2445 self.finish_frame_render();
2446 (tiles_updated, pixels_shaded)
2447 }
2448
2449 fn execute_prepared_slice(
2465 framebuffer: &mut Framebuffer,
2466 clip_spec: (u32, u32, u32, u32, u32),
2467 cmd_slices: (&[DrawCommand], &[PreppedCommand]),
2468 aux: BandAuxSlices<'_>,
2469 atlas_ref: &GlyphAtlas,
2470 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>, bool, bool),
2471 dispatch_state: (&mut u64, &mut u64, &mut usize, usize, &mut u64, &mut u64),
2472 ) -> usize {
2473 let (phys_w, clip_x0, clip_y0, clip_x1, clip_y1): (u32, u32, u32, u32, u32) = clip_spec;
2474 let (commands, prepped_slice): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
2475 let (scale, aa, restore_spec, allow_parallel, telemetry_enabled): (
2476 f32,
2477 AntialiasingMode,
2478 BandRestoreSpec<'_>,
2479 bool,
2480 bool,
2481 ) = render_opts;
2482 let (
2483 serial_dispatches,
2484 parallel_dispatches,
2485 adaptive_parallel_threshold_pixels,
2486 adaptive_threshold_override,
2487 last_serial_us,
2488 last_parallel_us,
2489 ): (&mut u64, &mut u64, &mut usize, usize, &mut u64, &mut u64) = dispatch_state;
2490 let restore_base_cache: bool = restore_spec.base_pixels.is_some();
2491 if prepped_slice.is_empty() && !restore_base_cache {
2492 return 0;
2493 }
2494 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
2495 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
2496 if clip_w == 0 || clip_h == 0 {
2497 return 0;
2498 }
2499 #[cfg(not(target_arch = "wasm32"))]
2500 let mut has_backdrop_blur: bool = false;
2501 #[cfg(not(target_arch = "wasm32"))]
2502 let mut complexity_bonus: usize = aux.rounded_clips.len().saturating_mul(16_384);
2503 #[cfg(not(target_arch = "wasm32"))]
2504 for item in prepped_slice.iter() {
2505 let idx: usize = item.get_cmd_index();
2506 if idx != usize::MAX {
2507 match &commands[idx] {
2508 DrawCommand::BackdropBlur { .. } => {
2509 has_backdrop_blur = true;
2510 break;
2511 }
2512 DrawCommand::BoxShadow { .. } => {
2513 complexity_bonus = complexity_bonus.saturating_add(12_288);
2514 }
2515 DrawCommand::TextRun { .. } => {
2516 complexity_bonus = complexity_bonus.saturating_add(4_096);
2517 }
2518 _ => {}
2519 }
2520 }
2521 }
2522 #[cfg(not(target_arch = "wasm32"))]
2523 let pixel_area: usize = (clip_w as usize).saturating_mul(clip_h as usize);
2524 #[cfg(not(target_arch = "wasm32"))]
2525 let active_min_pixels: usize = if adaptive_threshold_override > 0 {
2526 adaptive_threshold_override
2527 } else if *adaptive_parallel_threshold_pixels > 0 {
2528 *adaptive_parallel_threshold_pixels
2529 } else {
2530 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
2531 };
2532 #[cfg(not(target_arch = "wasm32"))]
2533 {
2534 let many_cmds: bool =
2535 prepped_slice.len() >= BAND_DISPATCH_MIN_CMDS || restore_base_cache;
2536 let large_area: bool = pixel_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2);
2537 let enough_work: bool = many_cmds || large_area;
2538 if allow_parallel
2539 && !has_backdrop_blur
2540 && pixel_area >= active_min_pixels.max(SMALL_DAMAGE_SINGLE_THREAD_PIXELS)
2541 && clip_h >= BAND_DISPATCH_MIN_HEIGHT
2542 && enough_work
2543 {
2544 let effective_area: usize = pixel_area.saturating_add(complexity_bonus);
2545 if effective_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2)
2546 && let Some(pool) = try_get_ready_band_worker_pool()
2547 {
2548 let desired_threads: usize =
2549 (effective_area / BAND_DISPATCH_MIN_PIXELS).clamp(1, pool.total_threads());
2550 let strip_count: usize = (desired_threads.saturating_mul(2))
2551 .min((clip_h / 24) as usize)
2552 .max(1);
2553 if strip_count > 1 && desired_threads > 1 {
2554 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
2555 let t0_opt: Option<Instant> = if telemetry_enabled {
2556 Some(Instant::now())
2557 } else {
2558 None
2559 };
2560 let shaded: usize = pool.execute(
2561 framebuffer,
2562 (
2563 clip_y0,
2564 clip_y1,
2565 strip_count,
2566 desired_threads.saturating_sub(1),
2567 ),
2568 (commands, prepped_slice),
2569 aux,
2570 atlas_ref,
2571 (scale, aa, restore_spec),
2572 );
2573 if let Some(t0) = t0_opt {
2574 let elapsed_us: u64 = t0.elapsed().as_micros() as u64;
2575 *last_parallel_us = elapsed_us;
2576 if adaptive_threshold_override == 0 && elapsed_us < 280 {
2577 let step: usize = (active_min_pixels / 2).max(16_384);
2578 *adaptive_parallel_threshold_pixels = active_min_pixels
2579 .saturating_add(step)
2580 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
2581 }
2582 }
2583 return shaded;
2584 }
2585 }
2586 }
2587 }
2588 #[cfg(target_arch = "wasm32")]
2589 {
2590 let _: bool = allow_parallel;
2591 let _: bool = telemetry_enabled;
2592 let _: &mut u64 = parallel_dispatches;
2593 let _: &mut usize = adaptive_parallel_threshold_pixels;
2594 let _: usize = adaptive_threshold_override;
2595 let _: &mut u64 = last_serial_us;
2596 let _: &mut u64 = last_parallel_us;
2597 }
2598 *serial_dispatches = serial_dispatches.wrapping_add(1);
2599 #[cfg(not(target_arch = "wasm32"))]
2600 let serial_t0_opt: Option<Instant> = if telemetry_enabled {
2601 Some(Instant::now())
2602 } else {
2603 None
2604 };
2605 let row_stride: usize = (phys_w as usize) * 4;
2606 let start_byte: usize = (clip_y0 as usize) * row_stride;
2607 let end_byte: usize = (clip_y1 as usize) * row_stride;
2608 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
2609 return 0;
2610 };
2611 if let Some(src_buf) = restore_spec.base_pixels
2612 && let Some(src_slice) = src_buf.get(start_byte..end_byte)
2613 {
2614 restore_band_strip(
2615 slice,
2616 src_slice,
2617 (
2618 row_stride,
2619 clip_h as usize,
2620 (restore_spec.x0 as usize) * 4,
2621 (restore_spec.x1.saturating_sub(restore_spec.x0) as usize) * 4,
2622 ),
2623 restore_spec.scrim_luts,
2624 );
2625 }
2626 let mut band: PixelBand<'_> = PixelBand {
2627 width: phys_w,
2628 y_offset: clip_y0,
2629 height: clip_h,
2630 pixels: slice,
2631 };
2632 let shaded_serial: usize = Self::render_band(
2633 &mut band,
2634 commands,
2635 prepped_slice,
2636 aux,
2637 atlas_ref,
2638 (scale, aa),
2639 );
2640 #[cfg(not(target_arch = "wasm32"))]
2641 if let Some(serial_t0) = serial_t0_opt {
2642 let elapsed_us: u64 = serial_t0.elapsed().as_micros() as u64;
2643 *last_serial_us = elapsed_us;
2644 if adaptive_threshold_override == 0 && !has_backdrop_blur {
2645 if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us > 900 {
2646 let step: usize = (active_min_pixels / 8).max(4096);
2647 *adaptive_parallel_threshold_pixels = active_min_pixels
2648 .saturating_sub(step)
2649 .max(ADAPTIVE_PARALLEL_MIN_PIXELS);
2650 } else if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us < 220 {
2651 let step: usize = (active_min_pixels / 16).max(2048);
2652 *adaptive_parallel_threshold_pixels = active_min_pixels
2653 .saturating_add(step)
2654 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
2655 }
2656 }
2657 }
2658 shaded_serial
2659 }
2660
2661 fn execute_backdrop_blur_separable(
2677 framebuffer: &mut Framebuffer,
2678 blur_horiz_scratch: &mut Vec<[u8; 4]>,
2679 rect: Rect,
2680 radius: CornerRadius,
2681 blur_and_scale: (f32, f32),
2682 clip: Rect,
2683 dispatch_opts: (bool, &mut u64, &mut u64),
2684 ) -> usize {
2685 let (blur_radius, scale): (f32, f32) = blur_and_scale;
2686 let (allow_parallel, serial_dispatches, parallel_dispatches): (bool, &mut u64, &mut u64) =
2687 dispatch_opts;
2688 let phys_rect: Rect = snap_physical_rect(rect, scale);
2689 let phys_radius: CornerRadius = Self::scale_radius(radius, scale);
2690 let phys_blur: f32 = (blur_radius * scale).clamp(0.5, 48.0);
2691 let Some(vis) = phys_rect.intersect(clip) else {
2692 return 0;
2693 };
2694 let fb_w: u32 = framebuffer.get_width();
2695 let fb_h: u32 = framebuffer.get_height();
2696 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2697 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, fb_w);
2698 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(fb_h);
2699 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, fb_h);
2700 if x0 >= x1 || y0 >= y1 {
2701 return 0;
2702 }
2703 let rad: u32 = (phys_blur * 0.5).round().clamp(1.0, 24.0) as u32;
2704 let sx0: u32 = x0.saturating_sub(rad);
2705 let sx1: u32 = x1.saturating_add(rad).min(fb_w);
2706 let sy0: u32 = y0.saturating_sub(rad);
2707 let sy1: u32 = y1.saturating_add(rad).min(fb_h);
2708 let stroke_width: u32 = sx1.saturating_sub(sx0);
2709 let sh: u32 = sy1.saturating_sub(sy0);
2710 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
2711 if needed == 0 {
2712 return 0;
2713 }
2714 if blur_horiz_scratch.len() < needed {
2715 blur_horiz_scratch.resize(needed, [0, 0, 0, 0]);
2716 }
2717 let fb_pixels: &mut [u8] = framebuffer.get_mut_pixels().as_mut_slice();
2718 let desc: BlurPassDesc = BlurPassDesc {
2719 #[cfg(not(target_arch = "wasm32"))]
2720 fb_ptr: fb_pixels.as_mut_ptr() as usize,
2721 #[cfg(not(target_arch = "wasm32"))]
2722 fb_len: fb_pixels.len(),
2723 fb_w,
2724 #[cfg(not(target_arch = "wasm32"))]
2725 horiz_ptr: blur_horiz_scratch.as_mut_ptr() as usize,
2726 #[cfg(not(target_arch = "wasm32"))]
2727 horiz_len: needed,
2728 sx0,
2729 sy0,
2730 sw: stroke_width,
2731 sh,
2732 x0,
2733 x1,
2734 y0,
2735 y1,
2736 rad,
2737 inv_win_q24: blur_inv_window_q24(rad),
2738 has_radius: phys_radius.max_radius() > 0.25,
2739 rect: phys_rect,
2740 radius: phys_radius,
2741 #[cfg(not(target_arch = "wasm32"))]
2742 strip_count: 1,
2743 #[cfg(not(target_arch = "wasm32"))]
2744 strip_rows: 1,
2745 };
2746 #[cfg(not(target_arch = "wasm32"))]
2747 {
2748 let blur_h: u32 = y1.saturating_sub(y0);
2749 let blur_area: usize =
2750 ((x1.saturating_sub(x0)) as usize).saturating_mul(blur_h as usize);
2751 if allow_parallel
2752 && blur_area >= BLUR_PARALLEL_MIN_PIXELS
2753 && blur_h >= BLUR_PARALLEL_MIN_HEIGHT
2754 && let Some(pool) = try_get_ready_band_worker_pool()
2755 {
2756 let desired_threads: usize =
2757 (blur_area / BLUR_PARALLEL_MIN_PIXELS).clamp(1, pool.total_threads());
2758 if desired_threads > 1 {
2759 let mut pass_desc: BlurPassDesc = desc;
2760 let h_strips: usize = desired_threads
2761 .saturating_mul(2)
2762 .min((sh / 8).max(1) as usize)
2763 .max(1);
2764 if h_strips > 1 {
2765 pass_desc.strip_count = h_strips;
2766 pass_desc.strip_rows = sh.div_ceil(h_strips as u32).max(1);
2767 let _: usize = pool.execute_blur_pass(
2768 BandJobKind::BlurHoriz,
2769 pass_desc,
2770 desired_threads.saturating_sub(1),
2771 );
2772 } else {
2773 blur_horiz_strip(&pass_desc, 0, sh as usize);
2774 }
2775 let v_strips: usize = desired_threads
2776 .saturating_mul(2)
2777 .min((blur_h / 8).max(1) as usize)
2778 .max(1);
2779 if v_strips > 1 {
2780 pass_desc.strip_count = v_strips;
2781 pass_desc.strip_rows = blur_h.div_ceil(v_strips as u32).max(1);
2782 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
2783 return pool.execute_blur_pass(
2784 BandJobKind::BlurVert,
2785 pass_desc,
2786 desired_threads.saturating_sub(1),
2787 );
2788 }
2789 *serial_dispatches = serial_dispatches.wrapping_add(1);
2790 return blur_vert_strip(&pass_desc, y0, y1);
2791 }
2792 }
2793 }
2794 #[cfg(target_arch = "wasm32")]
2795 {
2796 let _: bool = allow_parallel;
2797 let _: &mut u64 = parallel_dispatches;
2798 }
2799 *serial_dispatches = serial_dispatches.wrapping_add(1);
2800 let horiz_slice: &mut [[u8; 4]] = &mut blur_horiz_scratch[..needed];
2801 blur_horiz_strip_slices(fb_pixels, horiz_slice, &desc, (0, sh as usize));
2802 let fb_stride: usize = (fb_w as usize) * 4;
2803 let strip_start: usize = (y0 as usize).saturating_mul(fb_stride);
2804 let strip_end: usize = (y1 as usize).saturating_mul(fb_stride);
2805 let Some(fb_strip) = fb_pixels.get_mut(strip_start..strip_end) else {
2806 return 0;
2807 };
2808 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0, y1))
2809 }
2810
2811 fn execute_prepared_bands(
2825 &mut self,
2826 commands: &[DrawCommand],
2827 root_clip: Rect,
2828 dims: (u32, u32, f32),
2829 restore_opts: (bool, Option<Color>, usize),
2830 ) -> usize {
2831 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2832 let (restore_base_cache, scrim_color, prepped_start): (bool, Option<Color>, usize) =
2833 restore_opts;
2834 let clip_x0: u32 = (root_clip.get_x().floor().max(0.0) as u32).min(phys_w);
2835 let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2836 let clip_x1: u32 = (root_clip.right().ceil().max(0.0) as u32).clamp(clip_x0, phys_w);
2837 let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, phys_h);
2838 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
2839 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
2840 if clip_w == 0 || clip_h == 0 {
2841 return 0;
2842 }
2843 let Self {
2844 framebuffer,
2845 glyph_atlas,
2846 blur_horiz_scratch,
2847 base_cache_pixels,
2848 prepped_scratch,
2849 positioned_glyphs_scratch,
2850 caret_rects_scratch,
2851 rounded_clips_scratch,
2852 corner_mask_cache,
2853 antialiasing,
2854 cached_scrim_color,
2855 cached_scrim_luts,
2856 serial_dispatches,
2857 parallel_dispatches,
2858 adaptive_parallel_threshold_pixels,
2859 adaptive_threshold_override,
2860 last_serial_us,
2861 last_parallel_us,
2862 rendered_frames,
2863 telemetry_enabled,
2864 ..
2865 } = self;
2866 let Some(frame_pixels) = framebuffer.as_mut() else {
2867 return 0;
2868 };
2869 let aa: AntialiasingMode = *antialiasing;
2870 let allow_parallel: bool = *rendered_frames > 0;
2871 let record_timing: bool = *telemetry_enabled;
2872 let threshold_override: usize = *adaptive_threshold_override;
2873 let clamped_start: usize = prepped_start.min(prepped_scratch.len());
2874 let prepped_slice: &[PreppedCommand] = &prepped_scratch.as_slice()[clamped_start..];
2875 if prepped_slice.is_empty() && !restore_base_cache {
2876 return 0;
2877 }
2878 let scrim_luts_ref: Option<&[[u8; 256]; 4]> = if let Some(scrim_c) = scrim_color {
2879 if *cached_scrim_color != Some(scrim_c) || cached_scrim_luts.is_none() {
2880 *cached_scrim_color = Some(scrim_c);
2881 *cached_scrim_luts = Some(Box::new(build_linear_blend_luts(scrim_c)));
2882 }
2883 cached_scrim_luts.as_deref()
2884 } else {
2885 None
2886 };
2887 let aux: BandAuxSlices<'_> = BandAuxSlices {
2888 positioned_glyphs: positioned_glyphs_scratch.as_slice(),
2889 caret_rects: caret_rects_scratch.as_slice(),
2890 rounded_clips: rounded_clips_scratch.as_slice(),
2891 corner_masks: corner_mask_cache.entries(),
2892 };
2893 let atlas_ref: &GlyphAtlas = glyph_atlas;
2894 let restore_spec: BandRestoreSpec<'_> = BandRestoreSpec {
2895 base_pixels: if restore_base_cache {
2896 Some(base_cache_pixels.as_slice())
2897 } else {
2898 None
2899 },
2900 x0: clip_x0,
2901 x1: clip_x1,
2902 scrim_luts: scrim_luts_ref,
2903 };
2904 let empty_restore: BandRestoreSpec<'_> = BandRestoreSpec {
2905 base_pixels: None,
2906 x0: clip_x0,
2907 x1: clip_x1,
2908 scrim_luts: None,
2909 };
2910 let mut total_shaded: usize = 0;
2911 let mut chunk_start: usize = 0;
2912 let mut pending_restore: bool = restore_base_cache;
2913 for (pos, item) in prepped_slice.iter().enumerate() {
2914 let cmd_idx: usize = item.get_cmd_index();
2915 if cmd_idx != usize::MAX
2916 && item.get_rounded_clip_len() == 0
2917 && let DrawCommand::BackdropBlur {
2918 rect,
2919 radius,
2920 blur_radius,
2921 } = &commands[cmd_idx]
2922 {
2923 if chunk_start < pos || pending_restore {
2924 let spec: BandRestoreSpec<'_> = if pending_restore {
2925 restore_spec
2926 } else {
2927 empty_restore
2928 };
2929 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2930 frame_pixels,
2931 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2932 (commands, &prepped_slice[chunk_start..pos]),
2933 aux,
2934 atlas_ref,
2935 (scale, aa, spec, allow_parallel, record_timing),
2936 (
2937 serial_dispatches,
2938 parallel_dispatches,
2939 adaptive_parallel_threshold_pixels,
2940 threshold_override,
2941 last_serial_us,
2942 last_parallel_us,
2943 ),
2944 ));
2945 pending_restore = false;
2946 }
2947 if let Some(blur_clip) = item.get_active_clip().intersect(root_clip) {
2948 total_shaded =
2949 total_shaded.saturating_add(Self::execute_backdrop_blur_separable(
2950 frame_pixels,
2951 blur_horiz_scratch,
2952 *rect,
2953 *radius,
2954 (*blur_radius, scale),
2955 blur_clip,
2956 (allow_parallel, serial_dispatches, parallel_dispatches),
2957 ));
2958 }
2959 chunk_start = pos + 1;
2960 }
2961 }
2962 if chunk_start < prepped_slice.len() || pending_restore {
2963 let spec: BandRestoreSpec<'_> = if pending_restore {
2964 restore_spec
2965 } else {
2966 empty_restore
2967 };
2968 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2969 frame_pixels,
2970 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2971 (commands, &prepped_slice[chunk_start..]),
2972 aux,
2973 atlas_ref,
2974 (scale, aa, spec, allow_parallel, record_timing),
2975 (
2976 serial_dispatches,
2977 parallel_dispatches,
2978 adaptive_parallel_threshold_pixels,
2979 threshold_override,
2980 last_serial_us,
2981 last_parallel_us,
2982 ),
2983 ));
2984 }
2985 total_shaded
2986 }
2987
2988 fn prepare_frame_range(
2998 &mut self,
2999 display_list: &DisplayList,
3000 range: (usize, usize),
3001 root_clip: Rect,
3002 dims: (u32, u32, f32),
3003 ) {
3004 let (start_idx, end_idx): (usize, usize) = range;
3005 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
3006 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
3007 let clamped_end: usize = end_idx.min(commands.len());
3008 let clamped_start: usize = start_idx.min(clamped_end);
3009 let Self {
3010 glyph_atlas,
3011 font_provider,
3012 measurer,
3013 text_layout_cache,
3014 positioned_glyph_run_cache,
3015 cull_keep_scratch,
3016 cull_compacted_scratch,
3017 cull_sentinels_scratch,
3018 clip_stack,
3019 rounded_clip_stack,
3020 prepped_scratch: prepped,
3021 rounded_clips_scratch: rounded_clips,
3022 positioned_glyphs_scratch: positioned_glyphs,
3023 line_glyphs_scratch: line_scratch,
3024 caret_rects_scratch: caret_rects,
3025 corner_mask_cache,
3026 prepped_bounds,
3027 prepped_fg_bounds,
3028 clip_scope_scratch: clip_scopes,
3029 antialiasing,
3030 culled_occluded_commands,
3031 ..
3032 } = self;
3033 let aa: AntialiasingMode = *antialiasing;
3034 prepped.clear();
3035 prepped.reserve(clamped_end - clamped_start);
3036 *prepped_bounds = None;
3037 *prepped_fg_bounds = None;
3038 rounded_clips.clear();
3039 positioned_glyphs.clear();
3040 caret_rects.clear();
3041 clip_stack.clear();
3042 clip_stack.push(root_clip);
3043 rounded_clip_stack.clear();
3044 rounded_clip_stack.push(None);
3045 let root_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
3046 let root_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
3047 clip_scopes.clear();
3048 clip_scopes.push((root_y0, root_y1, None));
3049 let mut empty_clip_depth: usize = 0;
3050 let mut has_first_cmd: bool = false;
3051 glyph_atlas.evict_if_over_budget();
3052 positioned_glyph_run_cache.sync_atlas_epoch(glyph_atlas);
3053 positioned_glyph_run_cache.begin_frame();
3054 glyph_atlas.set_slots_pinned(true);
3055 text_layout_cache.evict_lru_if_needed();
3056 positioned_glyph_run_cache.evict_lru_if_needed();
3057 if corner_mask_cache.len() > CORNER_MASK_CACHE_LIMIT {
3058 corner_mask_cache.clear();
3059 }
3060 for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
3061 if empty_clip_depth > 0 {
3062 match cmd {
3063 DrawCommand::PushClip(_) | DrawCommand::PushRoundedClip { .. } => {
3064 empty_clip_depth += 1;
3065 }
3066 DrawCommand::PopClip => {
3067 empty_clip_depth -= 1;
3068 }
3069 _ => {}
3070 }
3071 continue;
3072 }
3073 let cmd_index: usize = clamped_start + offset;
3074 let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
3075 match cmd {
3076 DrawCommand::PushClip(rect) => {
3077 let phys: Rect = snap_physical_rect(*rect, scale);
3078 let Some(next) = active_clip.intersect(phys) else {
3079 empty_clip_depth = 1;
3080 continue;
3081 };
3082 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
3083 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
3084 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
3085 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
3086 if nx0 >= nx1 || ny0 >= ny1 {
3087 empty_clip_depth = 1;
3088 continue;
3089 }
3090 clip_stack.push(next);
3091 rounded_clip_stack.push(None);
3092 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
3093 .last()
3094 .copied()
3095 .unwrap_or((root_y0, root_y1, None));
3096 if ny0 > parent_y0 || ny1 < parent_y1 {
3097 let slot_idx: usize = prepped.len();
3098 prepped.push(PreppedCommand {
3099 cmd_index: usize::MAX,
3100 active_clip: next,
3101 y0: ny0,
3102 y1: ny1,
3103 opaque_cutout_h: Rect::default(),
3104 opaque_cutout_v: Rect::default(),
3105 glyph_run_start: 0,
3106 glyph_run_len: 0,
3107 caret_rect_idx: u32::MAX,
3108 rounded_clip_start: 0,
3109 rounded_clip_len: 0,
3110 skip_delta: 1,
3111 });
3112 clip_scopes.push((ny0, ny1, Some(slot_idx)));
3113 } else {
3114 clip_scopes.push((parent_y0, parent_y1, None));
3115 }
3116 }
3117 DrawCommand::PushRoundedClip { rect, radius } => {
3118 let phys: Rect = snap_physical_rect(*rect, scale);
3119 let Some(next) = active_clip.intersect(phys) else {
3120 empty_clip_depth = 1;
3121 continue;
3122 };
3123 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
3124 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
3125 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
3126 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
3127 if nx0 >= nx1 || ny0 >= ny1 {
3128 empty_clip_depth = 1;
3129 continue;
3130 }
3131 clip_stack.push(next);
3132 let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
3133 if phys.get_width() > 0.0
3134 && phys.get_height() > 0.0
3135 && phys_r.max_radius() > 0.25
3136 {
3137 let corner_mask_ids: [u32; 4] =
3138 corner_mask_cache.resolve_quadrants(phys, phys_r, aa);
3139 rounded_clip_stack.push(Some(RoundedClipMask {
3140 rect: phys,
3141 radius: phys_r,
3142 corner_mask_ids,
3143 }));
3144 } else {
3145 rounded_clip_stack.push(None);
3146 }
3147 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
3148 .last()
3149 .copied()
3150 .unwrap_or((root_y0, root_y1, None));
3151 if ny0 > parent_y0 || ny1 < parent_y1 {
3152 let slot_idx: usize = prepped.len();
3153 prepped.push(PreppedCommand {
3154 cmd_index: usize::MAX,
3155 active_clip: next,
3156 y0: ny0,
3157 y1: ny1,
3158 opaque_cutout_h: Rect::default(),
3159 opaque_cutout_v: Rect::default(),
3160 glyph_run_start: 0,
3161 glyph_run_len: 0,
3162 caret_rect_idx: u32::MAX,
3163 rounded_clip_start: 0,
3164 rounded_clip_len: 0,
3165 skip_delta: 1,
3166 });
3167 clip_scopes.push((ny0, ny1, Some(slot_idx)));
3168 } else {
3169 clip_scopes.push((parent_y0, parent_y1, None));
3170 }
3171 }
3172 DrawCommand::PopClip => {
3173 if clip_stack.len() > 1 {
3174 clip_stack.pop();
3175 let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
3176 if let Some((_, _, Some(slot_idx))) = clip_scopes.pop() {
3177 let span_len: usize = prepped.len().saturating_sub(slot_idx);
3178 if span_len <= 1 {
3179 prepped.truncate(slot_idx);
3180 } else if span_len == 2 {
3181 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
3182 prepped[slot_idx] = only_cmd;
3183 let _: Option<PreppedCommand> = prepped.pop();
3184 } else {
3185 prepped[slot_idx].skip_delta = span_len as u32;
3186 }
3187 }
3188 }
3189 }
3190 DrawCommand::Clear(clear_color) => {
3191 let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
3192 let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
3193 if y0 < y1 {
3194 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3195 rounded_clip_stack.as_slice(),
3196 rounded_clips,
3197 active_clip,
3198 );
3199 let covers_root: bool = active_clip.get_x() <= root_clip.get_x()
3200 && active_clip.get_y() <= root_clip.get_y()
3201 && active_clip.right() >= root_clip.right()
3202 && active_clip.bottom() >= root_clip.bottom();
3203 let no_open_sentinels: bool = clip_scopes
3204 .iter()
3205 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3206 if clamped_start == 0
3207 && !prepped.is_empty()
3208 && rc_len == 0
3209 && clear_color.get_alpha() == 255
3210 && covers_root
3211 && no_open_sentinels
3212 {
3213 prepped.clear();
3214 rounded_clips.clear();
3215 positioned_glyphs.clear();
3216 caret_rects.clear();
3217 *prepped_bounds = None;
3218 *prepped_fg_bounds = None;
3219 has_first_cmd = false;
3220 rc_start = 0;
3221 }
3222 if has_first_cmd {
3223 expand_opt_rect(prepped_fg_bounds, active_clip);
3224 }
3225 has_first_cmd = true;
3226 expand_opt_rect(prepped_bounds, active_clip);
3227 let (cut_h, cut_v): (Rect, Rect) = if rc_len == 0
3228 && cmd_index + 1 < clamped_end
3229 && clear_color.get_alpha() == 255
3230 {
3231 Self::resolve_opaque_clear_cutout(commands.get(cmd_index + 1), scale)
3232 } else {
3233 (Rect::default(), Rect::default())
3234 };
3235 prepped.push(PreppedCommand {
3236 cmd_index,
3237 active_clip,
3238 y0,
3239 y1,
3240 opaque_cutout_h: cut_h,
3241 opaque_cutout_v: cut_v,
3242 glyph_run_start: 0,
3243 glyph_run_len: 0,
3244 caret_rect_idx: u32::MAX,
3245 rounded_clip_start: rc_start,
3246 rounded_clip_len: rc_len,
3247 skip_delta: 0,
3248 });
3249 }
3250 }
3251 DrawCommand::FillRoundedRect {
3252 rect,
3253 color,
3254 radius,
3255 border,
3256 } => {
3257 let phys: Rect = snap_physical_rect(*rect, scale);
3258 if let Some(vis) = phys.intersect(active_clip) {
3259 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3260 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3261 if y0 < y1 {
3262 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3263 rounded_clip_stack.as_slice(),
3264 rounded_clips,
3265 vis,
3266 );
3267 let no_border: bool =
3268 border.get_width() <= 0.0 || border.get_color().get_alpha() == 0;
3269 let covers_root: bool = vis.get_x() <= root_clip.get_x()
3270 && vis.get_y() <= root_clip.get_y()
3271 && vis.right() >= root_clip.right()
3272 && vis.bottom() >= root_clip.bottom();
3273 let no_open_sentinels: bool = clip_scopes
3274 .iter()
3275 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3276 if clamped_start == 0
3277 && !prepped.is_empty()
3278 && rc_len == 0
3279 && color.get_alpha() == 255
3280 && radius.max_radius() <= 0.0
3281 && no_border
3282 && covers_root
3283 && no_open_sentinels
3284 {
3285 prepped.clear();
3286 rounded_clips.clear();
3287 positioned_glyphs.clear();
3288 caret_rects.clear();
3289 *prepped_bounds = None;
3290 *prepped_fg_bounds = None;
3291 has_first_cmd = false;
3292 rc_start = 0;
3293 }
3294 if has_first_cmd {
3295 expand_opt_rect(prepped_fg_bounds, vis);
3296 }
3297 has_first_cmd = true;
3298 expand_opt_rect(prepped_bounds, vis);
3299 prepped.push(PreppedCommand {
3300 cmd_index,
3301 active_clip,
3302 y0,
3303 y1,
3304 opaque_cutout_h: Rect::default(),
3305 opaque_cutout_v: Rect::default(),
3306 glyph_run_start: 0,
3307 glyph_run_len: 0,
3308 caret_rect_idx: u32::MAX,
3309 rounded_clip_start: rc_start,
3310 rounded_clip_len: rc_len,
3311 skip_delta: 0,
3312 });
3313 }
3314 }
3315 }
3316 DrawCommand::LinearGradientRect { rect, .. }
3317 | DrawCommand::BackdropBlur { rect, .. }
3318 | DrawCommand::Image { rect, .. }
3319 | DrawCommand::SharedImage { rect, .. }
3320 | DrawCommand::SpriteRegion { rect, .. } => {
3321 let phys: Rect = snap_physical_rect(*rect, scale);
3322 if let Some(vis) = phys.intersect(active_clip) {
3323 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3324 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3325 if y0 < y1 {
3326 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3327 rounded_clip_stack.as_slice(),
3328 rounded_clips,
3329 vis,
3330 );
3331 if has_first_cmd {
3332 expand_opt_rect(prepped_fg_bounds, vis);
3333 }
3334 has_first_cmd = true;
3335 expand_opt_rect(prepped_bounds, vis);
3336 prepped.push(PreppedCommand {
3337 cmd_index,
3338 active_clip,
3339 y0,
3340 y1,
3341 opaque_cutout_h: Rect::default(),
3342 opaque_cutout_v: Rect::default(),
3343 glyph_run_start: 0,
3344 glyph_run_len: 0,
3345 caret_rect_idx: u32::MAX,
3346 rounded_clip_start: rc_start,
3347 rounded_clip_len: rc_len,
3348 skip_delta: 0,
3349 });
3350 }
3351 }
3352 }
3353 DrawCommand::BoxShadow { rect, shadow, .. } => {
3354 if shadow.get_color().get_alpha() == 0 {
3355 continue;
3356 }
3357 let spread: f32 = shadow.get_spread_radius() * scale;
3358 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3359 let sigma: f32 = (blur * 0.5).max(0.75);
3360 let pad: f32 = (sigma * 3.0).ceil();
3361 let base_rect: Rect = snap_physical_rect(*rect, scale);
3362 let caster_rect: Rect = Rect::new(
3363 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
3364 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
3365 (base_rect.get_width() + spread * 2.0).max(1.0),
3366 (base_rect.get_height() + spread * 2.0).max(1.0),
3367 );
3368 let shadow_rect: Rect = Rect::new(
3369 caster_rect.get_x() - pad,
3370 caster_rect.get_y() - pad,
3371 caster_rect.get_width() + pad * 2.0,
3372 caster_rect.get_height() + pad * 2.0,
3373 );
3374 if let Some(vis) = shadow_rect.intersect(active_clip) {
3375 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3376 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3377 if y0 < y1 {
3378 let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
3379 commands.get(cmd_index + 1),
3380 scale,
3381 );
3382 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3383 rounded_clip_stack.as_slice(),
3384 rounded_clips,
3385 vis,
3386 );
3387 if has_first_cmd {
3388 expand_opt_rect(prepped_fg_bounds, vis);
3389 }
3390 has_first_cmd = true;
3391 expand_opt_rect(prepped_bounds, vis);
3392 prepped.push(PreppedCommand {
3393 cmd_index,
3394 active_clip,
3395 y0,
3396 y1,
3397 opaque_cutout_h: cut_h,
3398 opaque_cutout_v: cut_v,
3399 glyph_run_start: 0,
3400 glyph_run_len: 0,
3401 caret_rect_idx: u32::MAX,
3402 rounded_clip_start: rc_start,
3403 rounded_clip_len: rc_len,
3404 skip_delta: 0,
3405 });
3406 }
3407 }
3408 }
3409 DrawCommand::TextRun { rect, text, style } => {
3410 if text.is_empty() || style.get_color().get_alpha() == 0 {
3411 continue;
3412 }
3413 let phys_rect: Rect = Self::scale_rect(*rect, scale);
3414 let pad: f32 = style.get_font_size() * scale * 0.5;
3415 let expanded: Rect = Rect::new(
3416 phys_rect.get_x() - pad,
3417 phys_rect.get_y() - pad,
3418 phys_rect.get_width() + pad * 2.0,
3419 phys_rect.get_height() + pad * 2.0,
3420 );
3421 let Some(vis) = expanded.intersect(active_clip) else {
3422 continue;
3423 };
3424 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3425 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3426 if vis_y0 >= vis_y1 {
3427 continue;
3428 }
3429 let key_hash: u64 = hash_text_layout_key(text, *style);
3430 let width_bits: u32 = rect.get_width().to_bits();
3431 let phys_scale_milli: u32 = (scale * 1000.0).round() as u32;
3432 let base_x_phys: f32 = (rect.get_x() * scale).round();
3433 let base_y_phys: f32 = (rect.get_y() * scale).round();
3434 let (glyph_run_start, glyph_run_len): (u32, u32) = if text.len()
3435 <= POSITIONED_RUN_MAX_TEXT_LEN
3436 {
3437 if let Some((cached_run, cached_glyphs)) = positioned_glyph_run_cache
3438 .lookup(key_hash, width_bits, phys_scale_milli)
3439 {
3440 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3441 Self::emit_cached_glyph_run(
3442 cached_glyphs,
3443 (base_x_phys as i32, base_y_phys as i32),
3444 (active_clip, phys_w, phys_h),
3445 positioned_glyphs,
3446 )
3447 } else {
3448 let max_w: f32 = rect.get_width().max(1.0);
3449 if let Some((line_str, line_h)) =
3450 measurer.try_single_line(text, *style, Some(max_w))
3451 {
3452 Self::resolve_single_line_glyphs(
3453 (line_str, line_h),
3454 *rect,
3455 *style,
3456 (active_clip, phys_w, phys_h, scale),
3457 (glyph_atlas, font_provider),
3458 positioned_glyphs,
3459 line_scratch,
3460 )
3461 } else {
3462 let width_key: u32 =
3463 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3464 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3465 key_hash,
3466 width_key,
3467 || measurer.measure(text, *style, Some(max_w)),
3468 );
3469 if let Some(layout) = text_layout_cache.get(layout_idx) {
3470 Self::resolve_text_run_glyphs(
3471 layout,
3472 *rect,
3473 *style,
3474 (active_clip, phys_w, phys_h, scale),
3475 (glyph_atlas, font_provider),
3476 positioned_glyphs,
3477 line_scratch,
3478 )
3479 } else {
3480 (0, 0)
3481 }
3482 }
3483 }
3484 } else {
3485 let max_w: f32 = rect.get_width().max(1.0);
3486 if let Some((line_str, line_h)) =
3487 measurer.try_single_line(text, *style, Some(max_w))
3488 {
3489 if style.get_align() == TextAlign::Left
3490 && line_str.is_ascii()
3491 && base_x_phys >= 0.0
3492 {
3493 let run_start: u32 = positioned_glyphs.len() as u32;
3494 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3495 let clip_y0_i: i32 = (active_clip.get_y().ceil().max(0.0)
3496 as i32)
3497 .min(phys_h as i32);
3498 let clip_x1_i: i32 = (active_clip.right().floor().max(0.0)
3499 as i32)
3500 .min(phys_w as i32);
3501 let clip_y1_i: i32 = (active_clip.bottom().floor().max(0.0)
3502 as i32)
3503 .min(phys_h as i32);
3504 let bx_i: i32 = base_x_phys as i32;
3505 let by_i: i32 = base_y_phys as i32;
3506 let phys_font_size: f32 = style.get_font_size() * scale;
3507 let size_tenths: u16 =
3508 (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
3509 let bold: bool = style.get_weight().is_bold();
3510 let monospace: bool =
3511 style.get_family() == FontFamily::Monospace;
3512 let italic: bool = style.get_italic();
3513 let key_meta: (u16, bool, bool, bool) =
3514 (size_tenths, bold, monospace, italic);
3515 let ascii_table_idx: usize = glyph_atlas.ascii_table_index(
3516 size_tenths,
3517 bold,
3518 monospace,
3519 italic,
3520 );
3521 let line_h_phys: f32 = line_h * scale;
3522 let letter_sp: f32 = style.get_letter_spacing() * scale;
3523 let space_step: f32 =
3524 measure_char_advance(' ', *style) * scale + letter_sp;
3525 let clip_ok: bool =
3526 clip_x0_i < clip_x1_i && clip_y0_i < clip_y1_i;
3527 if positioned_glyph_run_cache.is_streaming() {
3528 positioned_glyph_run_cache.record_streaming_miss();
3529 if clip_ok {
3530 let mut pen_x: f32 = 0.0;
3531 for &byte in line_str.as_bytes() {
3532 if byte == b' ' {
3533 pen_x += space_step;
3534 continue;
3535 }
3536 let gx0: i32 = bx_i + (pen_x.round() as i32);
3537 if gx0 >= clip_x1_i {
3538 break;
3539 }
3540 let slot: u32 = glyph_atlas
3541 .get_or_rasterize_ascii_slot_with(
3542 ascii_table_idx,
3543 byte,
3544 key_meta,
3545 font_provider,
3546 );
3547 let glyph: &RasterizedGlyph =
3548 glyph_atlas.glyph_by_slot(slot);
3549 let adv_phys: f32 = (glyph.get_advance() as f32)
3550 .max(1.0)
3551 + letter_sp;
3552 let gw_u32: u32 = glyph.get_width();
3553 let gh_u32: u32 = glyph.get_height();
3554 let gw_u16: u16 =
3555 gw_u32.min(u16::MAX as u32) as u16;
3556 let gh_u16: u16 =
3557 gh_u32.min(u16::MAX as u32) as u16;
3558 if gx0 + (gw_u16 as i32) > clip_x0_i {
3559 let gy0: i32 = by_i
3560 + (((line_h_phys - (gh_u32 as f32)) * 0.5)
3561 .round()
3562 as i32);
3563 if gy0 < clip_y1_i
3564 && gy0 + (gh_u16 as i32) > clip_y0_i
3565 {
3566 positioned_glyphs.push(
3567 PositionedGlyph::new(
3568 slot, gx0, gy0, gw_u16, gh_u16,
3569 ),
3570 );
3571 }
3572 }
3573 pen_x += adv_phys;
3574 }
3575 }
3576 } else {
3577 let (_, _): (CachedPositionedGlyphRun, &[PositionedGlyph]) =
3578 positioned_glyph_run_cache.insert_with(
3579 (key_hash, width_bits, phys_scale_milli),
3580 line_str.len(),
3581 |out_slab: &mut Vec<PositionedGlyph>| {
3582 let mut pen_x: f32 = 0.0;
3583 let mut has_frac: bool = false;
3584 let mut max_slot: u32 = 0;
3585 for &byte in line_str.as_bytes() {
3586 if byte == b' ' {
3587 pen_x += space_step;
3588 continue;
3589 }
3590 let slot: u32 = glyph_atlas
3591 .get_or_rasterize_ascii_slot_with(
3592 ascii_table_idx,
3593 byte,
3594 key_meta,
3595 font_provider,
3596 );
3597 max_slot = max_slot.max(slot);
3598 let glyph: &RasterizedGlyph =
3599 glyph_atlas.glyph_by_slot(slot);
3600 let adv_phys: f32 =
3601 (glyph.get_advance() as f32).max(1.0)
3602 + letter_sp;
3603 let pen_x_round: f32 = pen_x.round();
3604 if (pen_x - pen_x_round).abs() > 1e-4 {
3605 has_frac = true;
3606 }
3607 let gw_u32: u32 = glyph.get_width();
3608 let gh_u32: u32 = glyph.get_height();
3609 let gw_u16: u16 =
3610 gw_u32.min(u16::MAX as u32) as u16;
3611 let gh_u16: u16 =
3612 gh_u32.min(u16::MAX as u32) as u16;
3613 let rx: i32 = pen_x_round as i32;
3614 let ry: i32 =
3615 ((line_h_phys - (gh_u32 as f32)) * 0.5)
3616 .round()
3617 as i32;
3618 out_slab.push(PositionedGlyph::new(
3619 slot, rx, ry, gw_u16, gh_u16,
3620 ));
3621 if clip_ok {
3622 let gx0: i32 = bx_i + rx;
3623 let gy0: i32 = by_i + ry;
3624 if gx0 + (gw_u16 as i32) > clip_x0_i
3625 && gx0 < clip_x1_i
3626 && gy0 < clip_y1_i
3627 && gy0 + (gh_u16 as i32) > clip_y0_i
3628 {
3629 positioned_glyphs.push(
3630 PositionedGlyph::new(
3631 slot, gx0, gy0, gw_u16,
3632 gh_u16,
3633 ),
3634 );
3635 }
3636 }
3637 pen_x += adv_phys;
3638 }
3639 (has_frac, max_slot)
3640 },
3641 );
3642 }
3643 let run_len: u32 =
3644 (positioned_glyphs.len() as u32).saturating_sub(run_start);
3645 (run_start, run_len)
3646 } else {
3647 let (cached_run, cached_glyphs): (
3648 CachedPositionedGlyphRun,
3649 &[PositionedGlyph],
3650 ) = positioned_glyph_run_cache.insert_with(
3651 (key_hash, width_bits, phys_scale_milli),
3652 line_str.len(),
3653 |out_slab: &mut Vec<PositionedGlyph>| {
3654 Self::append_single_line_positioned_glyph_run(
3655 (line_str, line_h),
3656 *rect,
3657 *style,
3658 scale,
3659 (glyph_atlas, font_provider),
3660 line_scratch,
3661 out_slab,
3662 )
3663 },
3664 );
3665 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3666 Self::emit_cached_glyph_run(
3667 cached_glyphs,
3668 (base_x_phys as i32, base_y_phys as i32),
3669 (active_clip, phys_w, phys_h),
3670 positioned_glyphs,
3671 )
3672 } else {
3673 Self::resolve_single_line_glyphs(
3674 (line_str, line_h),
3675 *rect,
3676 *style,
3677 (active_clip, phys_w, phys_h, scale),
3678 (glyph_atlas, font_provider),
3679 positioned_glyphs,
3680 line_scratch,
3681 )
3682 }
3683 }
3684 } else {
3685 let width_key: u32 =
3686 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3687 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3688 key_hash,
3689 width_key,
3690 || measurer.measure(text, *style, Some(max_w)),
3691 );
3692 if let Some(layout) = text_layout_cache.get(layout_idx) {
3693 let (cached_run, cached_glyphs): (
3694 CachedPositionedGlyphRun,
3695 &[PositionedGlyph],
3696 ) = positioned_glyph_run_cache.insert_with(
3697 (key_hash, width_bits, phys_scale_milli),
3698 text.len(),
3699 |out_slab: &mut Vec<PositionedGlyph>| {
3700 Self::append_cached_positioned_glyph_run(
3701 layout,
3702 *rect,
3703 *style,
3704 scale,
3705 (glyph_atlas, font_provider),
3706 line_scratch,
3707 out_slab,
3708 )
3709 },
3710 );
3711 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3712 Self::emit_cached_glyph_run(
3713 cached_glyphs,
3714 (base_x_phys as i32, base_y_phys as i32),
3715 (active_clip, phys_w, phys_h),
3716 positioned_glyphs,
3717 )
3718 } else {
3719 Self::resolve_text_run_glyphs(
3720 layout,
3721 *rect,
3722 *style,
3723 (active_clip, phys_w, phys_h, scale),
3724 (glyph_atlas, font_provider),
3725 positioned_glyphs,
3726 line_scratch,
3727 )
3728 }
3729 } else {
3730 (0, 0)
3731 }
3732 }
3733 }
3734 } else {
3735 let max_w: f32 = rect.get_width().max(1.0);
3736 let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3737 let layout_idx: u32 =
3738 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3739 measurer.measure(text, *style, Some(max_w))
3740 });
3741 if let Some(layout) = text_layout_cache.get(layout_idx) {
3742 Self::resolve_text_run_glyphs(
3743 layout,
3744 *rect,
3745 *style,
3746 (active_clip, phys_w, phys_h, scale),
3747 (glyph_atlas, font_provider),
3748 positioned_glyphs,
3749 line_scratch,
3750 )
3751 } else {
3752 (0, 0)
3753 }
3754 };
3755 if glyph_run_len == 0 {
3756 continue;
3757 }
3758 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3759 let clip_y0_i: i32 =
3760 (active_clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
3761 let clip_x1_i: i32 =
3762 (active_clip.right().floor().max(0.0) as i32).min(phys_w as i32);
3763 let clip_y1_i: i32 =
3764 (active_clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
3765 let mut min_gx: i32 = i32::MAX;
3766 let mut min_gy: i32 = i32::MAX;
3767 let mut max_gx: i32 = i32::MIN;
3768 let mut max_gy: i32 = i32::MIN;
3769 let g_s: usize = glyph_run_start as usize;
3770 let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
3771 for green_val in positioned_glyphs[g_s..g_e].iter() {
3772 let gx0: i32 = green_val.x.max(clip_x0_i);
3773 let gx1: i32 = (green_val.x + green_val.width as i32).min(clip_x1_i);
3774 let gy0: i32 = green_val.y.max(clip_y0_i);
3775 let gy1: i32 = (green_val.y + green_val.height as i32).min(clip_y1_i);
3776 if gx0 < gx1 && gy0 < gy1 {
3777 min_gx = min_gx.min(gx0);
3778 min_gy = min_gy.min(gy0);
3779 max_gx = max_gx.max(gx1);
3780 max_gy = max_gy.max(gy1);
3781 }
3782 }
3783 let (y0, y1, run_vis): (u32, u32, Rect) = if min_gx < max_gx && min_gy < max_gy
3784 {
3785 let ty0: u32 = (min_gy.max(0) as u32).min(phys_h);
3786 let ty1: u32 = (max_gy.max(0) as u32).min(phys_h);
3787 if ty0 >= ty1 {
3788 continue;
3789 }
3790 (
3791 ty0,
3792 ty1,
3793 Rect::new(
3794 min_gx as f32,
3795 min_gy as f32,
3796 (max_gx - min_gx) as f32,
3797 (max_gy - min_gy) as f32,
3798 ),
3799 )
3800 } else {
3801 (vis_y0, vis_y1, vis)
3802 };
3803 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3804 rounded_clip_stack.as_slice(),
3805 rounded_clips,
3806 run_vis,
3807 );
3808 if has_first_cmd {
3809 expand_opt_rect(prepped_fg_bounds, run_vis);
3810 }
3811 has_first_cmd = true;
3812 expand_opt_rect(prepped_bounds, run_vis);
3813 prepped.push(PreppedCommand {
3814 cmd_index,
3815 active_clip,
3816 y0,
3817 y1,
3818 opaque_cutout_h: Rect::default(),
3819 opaque_cutout_v: Rect::default(),
3820 glyph_run_start,
3821 glyph_run_len,
3822 caret_rect_idx: u32::MAX,
3823 rounded_clip_start: rc_start,
3824 rounded_clip_len: rc_len,
3825 skip_delta: 0,
3826 });
3827 }
3828 DrawCommand::TextCaret {
3829 text_rect,
3830 content_rect,
3831 text,
3832 style,
3833 caret_height,
3834 color,
3835 multiline,
3836 } => {
3837 if color.get_alpha() == 0 {
3838 continue;
3839 }
3840 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
3841 let Some(vis) = phys_content.intersect(active_clip) else {
3842 continue;
3843 };
3844 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3845 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3846 if vis_y0 >= vis_y1 {
3847 continue;
3848 }
3849 let (max_w, width_key): (Option<f32>, u32) = if *multiline {
3850 let width_val: f32 = content_rect.get_width().max(1.0);
3851 (
3852 Some(width_val),
3853 ((width_val * 10.0).round() as u32).min(u32::MAX - 1),
3854 )
3855 } else {
3856 (None, u32::MAX)
3857 };
3858 let key_hash: u64 = hash_text_layout_key(text, *style);
3859 let layout_idx: u32 =
3860 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3861 measurer.measure(text, *style, max_w)
3862 });
3863 let caret_rect: Rect = Self::resolve_text_caret_rect(
3864 text_layout_cache.get(layout_idx),
3865 (*text_rect, *content_rect),
3866 *style,
3867 (*caret_height, scale, *multiline),
3868 (glyph_atlas, font_provider),
3869 );
3870 let Some(caret_vis) = caret_rect.intersect(active_clip) else {
3871 continue;
3872 };
3873 let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
3874 let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3875 if y0 >= y1 {
3876 continue;
3877 }
3878 let caret_rect_idx: u32 = caret_rects.len() as u32;
3879 caret_rects.push(caret_rect);
3880 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3881 rounded_clip_stack.as_slice(),
3882 rounded_clips,
3883 caret_vis,
3884 );
3885 if has_first_cmd {
3886 expand_opt_rect(prepped_fg_bounds, caret_vis);
3887 }
3888 has_first_cmd = true;
3889 expand_opt_rect(prepped_bounds, caret_vis);
3890 prepped.push(PreppedCommand {
3891 cmd_index,
3892 active_clip,
3893 y0,
3894 y1,
3895 opaque_cutout_h: Rect::default(),
3896 opaque_cutout_v: Rect::default(),
3897 glyph_run_start: 0,
3898 glyph_run_len: 0,
3899 caret_rect_idx,
3900 rounded_clip_start: rc_start,
3901 rounded_clip_len: rc_len,
3902 skip_delta: 0,
3903 });
3904 }
3905 DrawCommand::Line {
3906 from, to, width, ..
3907 } => {
3908 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
3909 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
3910 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
3911 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
3912 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
3913 if let Some(vis) =
3914 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3915 {
3916 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3917 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3918 if y0 < y1 {
3919 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3920 rounded_clip_stack.as_slice(),
3921 rounded_clips,
3922 vis,
3923 );
3924 if has_first_cmd {
3925 expand_opt_rect(prepped_fg_bounds, vis);
3926 }
3927 has_first_cmd = true;
3928 expand_opt_rect(prepped_bounds, vis);
3929 prepped.push(PreppedCommand {
3930 cmd_index,
3931 active_clip,
3932 y0,
3933 y1,
3934 opaque_cutout_h: Rect::default(),
3935 opaque_cutout_v: Rect::default(),
3936 glyph_run_start: 0,
3937 glyph_run_len: 0,
3938 caret_rect_idx: u32::MAX,
3939 rounded_clip_start: rc_start,
3940 rounded_clip_len: rc_len,
3941 skip_delta: 0,
3942 });
3943 }
3944 }
3945 }
3946 DrawCommand::Circle { center, radius, .. } => {
3947 let red_val: f32 = radius * scale + 1.0;
3948 let bounds: Rect = Rect::new(
3949 center.get_x() * scale - red_val,
3950 center.get_y() * scale - red_val,
3951 red_val * 2.0,
3952 red_val * 2.0,
3953 );
3954 if let Some(vis) = bounds.intersect(active_clip) {
3955 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3956 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3957 if y0 < y1 {
3958 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3959 rounded_clip_stack.as_slice(),
3960 rounded_clips,
3961 vis,
3962 );
3963 if has_first_cmd {
3964 expand_opt_rect(prepped_fg_bounds, vis);
3965 }
3966 has_first_cmd = true;
3967 expand_opt_rect(prepped_bounds, vis);
3968 prepped.push(PreppedCommand {
3969 cmd_index,
3970 active_clip,
3971 y0,
3972 y1,
3973 opaque_cutout_h: Rect::default(),
3974 opaque_cutout_v: Rect::default(),
3975 glyph_run_start: 0,
3976 glyph_run_len: 0,
3977 caret_rect_idx: u32::MAX,
3978 rounded_clip_start: rc_start,
3979 rounded_clip_len: rc_len,
3980 skip_delta: 0,
3981 });
3982 }
3983 }
3984 }
3985 DrawCommand::Triangle { p0, p1, p2, .. } => {
3986 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
3987 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
3988 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
3989 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
3990 if let Some(vis) =
3991 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3992 {
3993 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3994 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3995 if y0 < y1 {
3996 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3997 rounded_clip_stack.as_slice(),
3998 rounded_clips,
3999 vis,
4000 );
4001 if has_first_cmd {
4002 expand_opt_rect(prepped_fg_bounds, vis);
4003 }
4004 has_first_cmd = true;
4005 expand_opt_rect(prepped_bounds, vis);
4006 prepped.push(PreppedCommand {
4007 cmd_index,
4008 active_clip,
4009 y0,
4010 y1,
4011 opaque_cutout_h: Rect::default(),
4012 opaque_cutout_v: Rect::default(),
4013 glyph_run_start: 0,
4014 glyph_run_len: 0,
4015 caret_rect_idx: u32::MAX,
4016 rounded_clip_start: rc_start,
4017 rounded_clip_len: rc_len,
4018 skip_delta: 0,
4019 });
4020 }
4021 }
4022 }
4023 }
4024 }
4025 while let Some((_, _, opt_slot)) = clip_scopes.pop() {
4026 if let Some(slot_idx) = opt_slot {
4027 let span_len: usize = prepped.len().saturating_sub(slot_idx);
4028 if span_len <= 1 {
4029 prepped.truncate(slot_idx);
4030 } else if span_len == 2 {
4031 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
4032 prepped[slot_idx] = only_cmd;
4033 let _: Option<PreppedCommand> = prepped.pop();
4034 } else {
4035 prepped[slot_idx].skip_delta = span_len as u32;
4036 }
4037 }
4038 }
4039 let culled_now: usize = Self::cull_occluded_prepped_commands(
4040 commands,
4041 prepped,
4042 (phys_w, phys_h, scale),
4043 cull_keep_scratch,
4044 cull_compacted_scratch,
4045 cull_sentinels_scratch,
4046 );
4047 *culled_occluded_commands = culled_occluded_commands.saturating_add(culled_now as u64);
4048 glyph_atlas.set_slots_pinned(false);
4049 }
4050
4051 #[must_use]
4063 fn command_cull_bounds(cmd: &DrawCommand, active_clip: Rect, scale: f32) -> Option<Rect> {
4064 let raw: Rect = match cmd {
4065 DrawCommand::Clear(_) => active_clip,
4066 DrawCommand::FillRoundedRect { rect, .. }
4067 | DrawCommand::LinearGradientRect { rect, .. }
4068 | DrawCommand::Image { rect, .. }
4069 | DrawCommand::SharedImage { rect, .. }
4070 | DrawCommand::SpriteRegion { rect, .. }
4071 | DrawCommand::BackdropBlur { rect, .. } => snap_physical_rect(*rect, scale),
4072 DrawCommand::BoxShadow { rect, shadow, .. } => {
4073 let spread: f32 = shadow.get_spread_radius() * scale;
4074 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
4075 let sigma: f32 = (blur * 0.5).max(0.75);
4076 let pad: f32 = (sigma * 3.0).ceil();
4077 let base: Rect = snap_physical_rect(*rect, scale);
4078 Rect::new(
4079 base.get_x() + (shadow.get_offset_x() * scale).round() - spread - pad,
4080 base.get_y() + (shadow.get_offset_y() * scale).round() - spread - pad,
4081 (base.get_width() + spread * 2.0).max(1.0) + pad * 2.0,
4082 (base.get_height() + spread * 2.0).max(1.0) + pad * 2.0,
4083 )
4084 }
4085 DrawCommand::TextRun { rect, style, .. } => {
4086 let phys: Rect = Self::scale_rect(*rect, scale);
4087 let pad: f32 = style.get_font_size() * scale * 0.5 + 2.0;
4088 Rect::new(
4089 phys.get_x() - pad,
4090 phys.get_y() - pad,
4091 phys.get_width() + pad * 2.0,
4092 phys.get_height() + pad * 2.0,
4093 )
4094 }
4095 DrawCommand::TextCaret { content_rect, .. } => snap_physical_rect(*content_rect, scale),
4096 DrawCommand::Line {
4097 from, to, width, ..
4098 } => {
4099 let pad: f32 = (width * scale).max(1.0) + 2.0;
4100 let x0: f32 = from.get_x().min(to.get_x()) * scale - pad;
4101 let y0: f32 = from.get_y().min(to.get_y()) * scale - pad;
4102 let x1: f32 = from.get_x().max(to.get_x()) * scale + pad;
4103 let y1: f32 = from.get_y().max(to.get_y()) * scale + pad;
4104 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
4105 }
4106 DrawCommand::Circle { center, radius, .. } => {
4107 let red_val: f32 = radius * scale + 2.0;
4108 Rect::new(
4109 center.get_x() * scale - red_val,
4110 center.get_y() * scale - red_val,
4111 red_val * 2.0,
4112 red_val * 2.0,
4113 )
4114 }
4115 DrawCommand::Triangle { p0, p1, p2, .. } => {
4116 let x0: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 2.0;
4117 let y0: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 2.0;
4118 let x1: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 2.0;
4119 let y1: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 2.0;
4120 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
4121 }
4122 DrawCommand::PushClip(_)
4123 | DrawCommand::PushRoundedClip { .. }
4124 | DrawCommand::PopClip => {
4125 return None;
4126 }
4127 };
4128 raw.intersect(active_clip)
4129 }
4130
4131 #[must_use]
4143 fn opaque_inscribed_rect(cmd: &DrawCommand, item: PreppedCommand, scale: f32) -> Option<Rect> {
4144 if item.get_rounded_clip_len() != 0 {
4145 return None;
4146 }
4147 let (rect, radius): (Rect, CornerRadius) = match cmd {
4148 DrawCommand::FillRoundedRect {
4149 rect,
4150 color,
4151 radius,
4152 border,
4153 } if color.get_alpha() == 255
4154 && (border.get_width() <= 0.0 || border.get_color().get_alpha() == 255) =>
4155 {
4156 (*rect, *radius)
4157 }
4158 DrawCommand::LinearGradientRect {
4159 rect,
4160 gradient,
4161 radius,
4162 } if gradient.get_start_color().get_alpha() == 255
4163 && gradient.get_end_color().get_alpha() == 255 =>
4164 {
4165 (*rect, *radius)
4166 }
4167 _ => return None,
4168 };
4169 let phys: Rect = snap_physical_rect(rect, scale);
4170 let phys_r: CornerRadius = Self::scale_radius(radius, scale);
4171 let max_r: f32 = phys_r
4172 .max_radius()
4173 .min(phys.get_width() * 0.5)
4174 .min(phys.get_height() * 0.5);
4175 let inscribed: Rect = if max_r > 0.0 {
4176 phys.inset(Edges::all(max_r.ceil()))
4177 } else {
4178 phys
4179 };
4180 if inscribed.get_width() < 1.0 || inscribed.get_height() < 1.0 {
4181 return None;
4182 }
4183 let occ: Rect = inscribed.intersect(item.get_active_clip())?;
4184 if occ.get_width() >= 1.0 && occ.get_height() >= 1.0 {
4185 Some(occ)
4186 } else {
4187 None
4188 }
4189 }
4190
4191 fn cull_occluded_prepped_commands(
4206 commands: &[DrawCommand],
4207 prepped: &mut Vec<PreppedCommand>,
4208 dims: (u32, u32, f32),
4209 keep: &mut Vec<bool>,
4210 compacted: &mut Vec<PreppedCommand>,
4211 open_sentinels: &mut Vec<(usize, usize)>,
4212 ) -> usize {
4213 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
4214 let len: usize = prepped.len();
4215 if len < 2 {
4216 return 0;
4217 }
4218 keep.clear();
4219 keep.resize(len, true);
4220 let mut occluders: [Rect; OCCLUSION_MAX_OCCLUDERS] =
4221 [Rect::default(); OCCLUSION_MAX_OCCLUDERS];
4222 let mut occluder_count: usize = 0;
4223 let mut combined_tile_mask: u64 = 0;
4224 let mut culled: usize = 0;
4225 for idx in (0..len).rev() {
4226 let item: PreppedCommand = prepped[idx];
4227 if item.get_cmd_index() == usize::MAX {
4228 continue;
4229 }
4230 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
4231 if matches!(cmd, DrawCommand::BackdropBlur { .. }) {
4232 occluder_count = 0;
4233 combined_tile_mask = 0;
4234 continue;
4235 }
4236 if (occluder_count > 0 || combined_tile_mask != 0)
4237 && let Some(vis) = Self::command_cull_bounds(cmd, item.get_active_clip(), scale)
4238 {
4239 let vis_mask: u64 = occlusion_tile_mask_overlapped(vis, phys_w, phys_h);
4240 let mut covered: bool =
4241 vis_mask != 0 && (vis_mask & combined_tile_mask) == vis_mask;
4242 if !covered {
4243 for occ in occluders.iter().take(occluder_count) {
4244 if vis.get_x() >= occ.get_x()
4245 && vis.get_y() >= occ.get_y()
4246 && vis.right() <= occ.right()
4247 && vis.bottom() <= occ.bottom()
4248 {
4249 covered = true;
4250 break;
4251 }
4252 }
4253 }
4254 if covered {
4255 keep[idx] = false;
4256 culled += 1;
4257 continue;
4258 }
4259 }
4260 if let Some(occ) = Self::opaque_inscribed_rect(cmd, item, scale) {
4261 combined_tile_mask |= occlusion_tile_mask_contained(occ, phys_w, phys_h);
4262 if occluder_count < OCCLUSION_MAX_OCCLUDERS {
4263 occluders[occluder_count] = occ;
4264 occluder_count += 1;
4265 } else {
4266 let occ_area: f32 = occ.get_width() * occ.get_height();
4267 let mut min_i: usize = 0;
4268 let mut min_area: f32 = occluders[0].get_width() * occluders[0].get_height();
4269 for (slot, occ_ref) in occluders
4270 .iter()
4271 .enumerate()
4272 .take(OCCLUSION_MAX_OCCLUDERS)
4273 .skip(1)
4274 {
4275 let area: f32 = occ_ref.get_width() * occ_ref.get_height();
4276 if area < min_area {
4277 min_area = area;
4278 min_i = slot;
4279 }
4280 }
4281 if occ_area > min_area {
4282 occluders[min_i] = occ;
4283 }
4284 }
4285 }
4286 }
4287 if culled == 0 {
4288 return 0;
4289 }
4290 compacted.clear();
4291 compacted.reserve(len.saturating_sub(culled));
4292 open_sentinels.clear();
4293 for (old_idx, &kept) in keep.iter().enumerate() {
4294 while let Some(&(new_s, old_end)) = open_sentinels.last() {
4295 if old_end <= old_idx {
4296 let _: Option<(usize, usize)> = open_sentinels.pop();
4297 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4298 compacted[new_s].set_skip_delta(span);
4299 } else {
4300 break;
4301 }
4302 }
4303 if kept {
4304 let item: PreppedCommand = prepped[old_idx];
4305 if item.get_cmd_index() == usize::MAX {
4306 let old_end: usize = old_idx.saturating_add(item.get_skip_delta() as usize);
4307 open_sentinels.push((compacted.len(), old_end));
4308 }
4309 compacted.push(item);
4310 }
4311 }
4312 while let Some((new_s, _)) = open_sentinels.pop() {
4313 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4314 compacted[new_s].set_skip_delta(span);
4315 }
4316 swap(prepped, compacted);
4317 culled
4318 }
4319
4320 fn raster_backdrop_blur(
4334 band: &mut PixelBand<'_>,
4335 rect: Rect,
4336 radius: CornerRadius,
4337 blur_radius: f32,
4338 clip: Rect,
4339 ) -> usize {
4340 let Some(vis) = rect.intersect(clip) else {
4341 return 0;
4342 };
4343 let border_width: u32 = band.width();
4344 let band_y0: u32 = band.y_offset();
4345 let band_y1: u32 = band.y_end();
4346 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(border_width);
4347 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, border_width);
4348 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4349 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, band_y1);
4350 if x0 >= x1 || y0 >= y1 {
4351 return 0;
4352 }
4353 let rad: u32 = (blur_radius * 0.5).round().clamp(1.0, 24.0) as u32;
4354 let sx0: u32 = x0.saturating_sub(rad);
4355 let sx1: u32 = x1.saturating_add(rad).min(border_width);
4356 let sy0: u32 = y0.saturating_sub(rad).max(band_y0);
4357 let sy1: u32 = y1.saturating_add(rad).min(band_y1);
4358 let stroke_width: u32 = sx1.saturating_sub(sx0);
4359 let sh: u32 = sy1.saturating_sub(sy0);
4360 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
4361 if needed == 0 {
4362 return 0;
4363 }
4364 let mut horiz: Vec<[u8; 4]> = BAND_BLUR_HORIZ_SCRATCH
4365 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4366 cell.try_borrow_mut()
4367 .ok()
4368 .map(|mut guard: RefMut<'_, Vec<[u8; 4]>>| take(&mut *guard))
4369 })
4370 .ok()
4371 .flatten()
4372 .unwrap_or_default();
4373 if horiz.len() < needed {
4374 horiz.resize(needed, [0, 0, 0, 0]);
4375 }
4376 let y0_rel: u32 = y0.saturating_sub(band_y0);
4377 let y1_rel: u32 = y1.saturating_sub(band_y0);
4378 let sy0_rel: u32 = sy0.saturating_sub(band_y0);
4379 let shifted_rect: Rect = Rect::new(
4380 rect.get_x(),
4381 rect.get_y() - (band_y0 as f32),
4382 rect.get_width(),
4383 rect.get_height(),
4384 );
4385 let desc: BlurPassDesc = BlurPassDesc {
4386 #[cfg(not(target_arch = "wasm32"))]
4387 fb_ptr: 0,
4388 #[cfg(not(target_arch = "wasm32"))]
4389 fb_len: 0,
4390 fb_w: border_width,
4391 #[cfg(not(target_arch = "wasm32"))]
4392 horiz_ptr: 0,
4393 #[cfg(not(target_arch = "wasm32"))]
4394 horiz_len: needed,
4395 sx0,
4396 sy0: sy0_rel,
4397 sw: stroke_width,
4398 sh,
4399 x0,
4400 x1,
4401 y0: y0_rel,
4402 y1: y1_rel,
4403 rad,
4404 inv_win_q24: blur_inv_window_q24(rad),
4405 has_radius: radius.max_radius() > 0.25,
4406 rect: shifted_rect,
4407 radius,
4408 #[cfg(not(target_arch = "wasm32"))]
4409 strip_count: 1,
4410 #[cfg(not(target_arch = "wasm32"))]
4411 strip_rows: sh.max(1),
4412 };
4413 let horiz_slice: &mut [[u8; 4]] = &mut horiz[..needed];
4414 blur_horiz_strip_slices(band.pixels, horiz_slice, &desc, (0, sh as usize));
4415 let fb_stride: usize = (border_width as usize) * 4;
4416 let strip_start: usize = (y0_rel as usize).saturating_mul(fb_stride);
4417 let strip_end: usize = (y1_rel as usize).saturating_mul(fb_stride);
4418 let shaded: usize = if let Some(fb_strip) = band.pixels.get_mut(strip_start..strip_end) {
4419 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0_rel, y1_rel))
4420 } else {
4421 0
4422 };
4423 let _: bool = BAND_BLUR_HORIZ_SCRATCH
4424 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4425 if let Ok(mut guard) = cell.try_borrow_mut() {
4426 *guard = horiz;
4427 }
4428 })
4429 .is_ok();
4430 shaded
4431 }
4432
4433 #[must_use]
4443 pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
4444 self.get_text_layout_cache().stats()
4445 }
4446
4447 fn append_relative_line_glyphs(
4459 line_info: (&str, f32),
4460 metrics: (f32, f32, f32, f32),
4461 font_meta: (TextAlign, usize, (u16, bool, bool, bool)),
4462 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4463 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4464 out_glyphs: &mut Vec<PositionedGlyph>,
4465 state: (&mut bool, &mut u32),
4466 ) {
4467 let (line_str, line_off_y): (&str, f32) = line_info;
4468 let (line_h_phys, box_w_phys, letter_sp, space_step): (f32, f32, f32, f32) = metrics;
4469 let (align, ascii_table_idx, key_meta): (TextAlign, usize, (u16, bool, bool, bool)) =
4470 font_meta;
4471 let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
4472 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4473 let (has_fractional_x, max_glyph_slot): (&mut bool, &mut u32) = state;
4474 line_scratch.clear();
4475 let mut line_w_phys: f32 = 0.0;
4476 if line_str.is_ascii() {
4477 for &byte in line_str.as_bytes() {
4478 if byte == b' ' {
4479 line_w_phys += space_step;
4480 line_scratch.push((u32::MAX, space_step, 0, 0));
4481 } else {
4482 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4483 ascii_table_idx,
4484 byte,
4485 key_meta,
4486 font_provider,
4487 );
4488 *max_glyph_slot = (*max_glyph_slot).max(slot);
4489 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4490 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4491 line_w_phys += adv_phys;
4492 line_scratch.push((
4493 slot,
4494 adv_phys,
4495 glyph.get_width().min(u16::MAX as u32) as u16,
4496 glyph.get_height().min(u16::MAX as u32) as u16,
4497 ));
4498 }
4499 }
4500 } else {
4501 for ch in line_str.chars() {
4502 if ch == ' ' {
4503 line_w_phys += space_step;
4504 line_scratch.push((u32::MAX, space_step, 0, 0));
4505 } else {
4506 let slot: u32 = if ch.is_ascii() {
4507 glyph_atlas.get_or_rasterize_ascii_slot_with(
4508 ascii_table_idx,
4509 ch as u8,
4510 key_meta,
4511 font_provider,
4512 )
4513 } else {
4514 let key: GlyphKey = GlyphKey {
4515 codepoint: ch,
4516 size_tenths,
4517 bold,
4518 monospace,
4519 italic,
4520 };
4521 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4522 };
4523 *max_glyph_slot = (*max_glyph_slot).max(slot);
4524 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4525 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4526 line_w_phys += adv_phys;
4527 line_scratch.push((
4528 slot,
4529 adv_phys,
4530 glyph.get_width().min(u16::MAX as u32) as u16,
4531 glyph.get_height().min(u16::MAX as u32) as u16,
4532 ));
4533 }
4534 }
4535 }
4536 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4537 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4538 } else {
4539 1.0
4540 };
4541 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4542 let align_x: f32 = match align {
4543 TextAlign::Left => 0.0,
4544 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4545 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4546 };
4547 let mut pen_x: f32 = align_x.round();
4548 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4549 if slot == u32::MAX {
4550 pen_x += adv_phys * fit_scale;
4551 continue;
4552 }
4553 let pen_x_round: f32 = pen_x.round();
4554 if (pen_x - pen_x_round).abs() > 1e-4 {
4555 *has_fractional_x = true;
4556 }
4557 let glyph_v_off: f32 = ((line_h_phys - (gh_u16 as f32)) * 0.5).round();
4558 out_glyphs.push(PositionedGlyph::new(
4559 slot,
4560 pen_x_round as i32,
4561 (line_off_y + glyph_v_off) as i32,
4562 gw_u16,
4563 gh_u16,
4564 ));
4565 pen_x += adv_phys * fit_scale;
4566 }
4567 }
4568
4569 fn append_single_line_positioned_glyph_run(
4585 line_info: (&str, f32),
4586 rect: Rect,
4587 style: TextStyle,
4588 scale: f32,
4589 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4590 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4591 out_glyphs: &mut Vec<PositionedGlyph>,
4592 ) -> (bool, u32) {
4593 let (line_str, line_height_px): (&str, f32) = line_info;
4594 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4595 let phys_font_size: f32 = style.get_font_size() * scale;
4596 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4597 let bold: bool = style.get_weight().is_bold();
4598 let monospace: bool = style.get_family() == FontFamily::Monospace;
4599 let italic: bool = style.get_italic();
4600 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4601 let ascii_table_idx: usize =
4602 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4603 let line_h_phys: f32 = line_height_px * scale;
4604 let box_w_phys: f32 = rect.get_width() * scale;
4605 let letter_sp: f32 = style.get_letter_spacing() * scale;
4606 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4607 let mut has_fractional_x: bool = false;
4608 let mut max_glyph_slot: u32 = 0;
4609 Self::append_relative_line_glyphs(
4610 (line_str, 0.0),
4611 (line_h_phys, box_w_phys, letter_sp, space_step),
4612 (style.get_align(), ascii_table_idx, key_meta),
4613 (glyph_atlas, font_provider),
4614 line_scratch,
4615 out_glyphs,
4616 (&mut has_fractional_x, &mut max_glyph_slot),
4617 );
4618 (has_fractional_x, max_glyph_slot)
4619 }
4620
4621 fn append_cached_positioned_glyph_run(
4637 layout: &TextLayoutResult,
4638 rect: Rect,
4639 style: TextStyle,
4640 scale: f32,
4641 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4642 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4643 out_glyphs: &mut Vec<PositionedGlyph>,
4644 ) -> (bool, u32) {
4645 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4646 let phys_font_size: f32 = style.get_font_size() * scale;
4647 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4648 let bold: bool = style.get_weight().is_bold();
4649 let monospace: bool = style.get_family() == FontFamily::Monospace;
4650 let italic: bool = style.get_italic();
4651 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4652 let ascii_table_idx: usize =
4653 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4654 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4655 let box_w_phys: f32 = rect.get_width() * scale;
4656 let letter_sp: f32 = style.get_letter_spacing() * scale;
4657 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4658 let align: TextAlign = style.get_align();
4659 let mut has_fractional_x: bool = false;
4660 let mut max_glyph_slot: u32 = 0;
4661 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4662 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4663 Self::append_relative_line_glyphs(
4664 (line.get_text().as_str(), line_off_y),
4665 (line_h_phys, box_w_phys, letter_sp, space_step),
4666 (align, ascii_table_idx, key_meta),
4667 (glyph_atlas, font_provider),
4668 line_scratch,
4669 out_glyphs,
4670 (&mut has_fractional_x, &mut max_glyph_slot),
4671 );
4672 }
4673 (has_fractional_x, max_glyph_slot)
4674 }
4675
4676 fn emit_cached_glyph_run(
4689 cached_glyphs: &[PositionedGlyph],
4690 origin: (i32, i32),
4691 clip_dims: (Rect, u32, u32),
4692 out_glyphs: &mut Vec<PositionedGlyph>,
4693 ) -> (u32, u32) {
4694 let (base_x, base_y): (i32, i32) = origin;
4695 let (clip, phys_w, phys_h): (Rect, u32, u32) = clip_dims;
4696 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4697 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4698 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4699 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4700 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4701 return (0, 0);
4702 }
4703 let run_start: u32 = out_glyphs.len() as u32;
4704 for green_val in cached_glyphs.iter() {
4705 let gx0: i32 = base_x + green_val.get_x();
4706 let gw: i32 = green_val.get_width() as i32;
4707 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4708 let gy0: i32 = base_y + green_val.get_y();
4709 let gh: i32 = green_val.get_height() as i32;
4710 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4711 out_glyphs.push(PositionedGlyph::new(
4712 green_val.get_glyph_idx(),
4713 gx0,
4714 gy0,
4715 green_val.get_width(),
4716 green_val.get_height(),
4717 ));
4718 }
4719 }
4720 }
4721 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4722 (run_start, run_len)
4723 }
4724
4725 fn resolve_single_line_glyphs(
4741 line_info: (&str, f32),
4742 rect: Rect,
4743 style: TextStyle,
4744 clip_dims: (Rect, u32, u32, f32),
4745 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4746 out_glyphs: &mut Vec<PositionedGlyph>,
4747 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4748 ) -> (u32, u32) {
4749 let (line_str, line_height_px): (&str, f32) = line_info;
4750 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4751 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4752 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4753 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4754 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4755 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4756 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4757 return (0, 0);
4758 }
4759 let line_h_phys: f32 = line_height_px * scale;
4760 let base_x_phys: f32 = (rect.get_x() * scale).round();
4761 let base_y_phys: f32 = (rect.get_y() * scale).round();
4762 if (base_y_phys + line_h_phys) < (clip_y0 as f32) || base_y_phys > (clip_y1 as f32) {
4763 return (0, 0);
4764 }
4765 let phys_font_size: f32 = style.get_font_size() * scale;
4766 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4767 let bold: bool = style.get_weight().is_bold();
4768 let monospace: bool = style.get_family() == FontFamily::Monospace;
4769 let italic: bool = style.get_italic();
4770 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4771 let ascii_table_idx: usize =
4772 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4773 let box_w_phys: f32 = rect.get_width() * scale;
4774 let letter_sp: f32 = style.get_letter_spacing() * scale;
4775 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4776 let align: TextAlign = style.get_align();
4777 let run_start: u32 = out_glyphs.len() as u32;
4778 let clip_x1_f: f32 = clip_x1 as f32;
4779 line_scratch.clear();
4780 let mut line_w_phys: f32 = 0.0;
4781 for ch in line_str.chars() {
4782 if ch == ' ' {
4783 line_w_phys += space_step;
4784 line_scratch.push((u32::MAX, space_step, 0, 0));
4785 } else {
4786 let slot: u32 = if ch.is_ascii() {
4787 glyph_atlas.get_or_rasterize_ascii_slot_with(
4788 ascii_table_idx,
4789 ch as u8,
4790 key_meta,
4791 font_provider,
4792 )
4793 } else {
4794 let key: GlyphKey = GlyphKey {
4795 codepoint: ch,
4796 size_tenths,
4797 bold,
4798 monospace,
4799 italic,
4800 };
4801 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4802 };
4803 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4804 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4805 line_w_phys += adv_phys;
4806 line_scratch.push((
4807 slot,
4808 adv_phys,
4809 glyph.get_width().min(u16::MAX as u32) as u16,
4810 glyph.get_height().min(u16::MAX as u32) as u16,
4811 ));
4812 }
4813 }
4814 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4815 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4816 } else {
4817 1.0
4818 };
4819 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4820 let align_x: f32 = match align {
4821 TextAlign::Left => 0.0,
4822 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4823 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4824 };
4825 let mut pen_x: f32 = base_x_phys + align_x.round();
4826 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4827 if pen_x > clip_x1_f {
4828 break;
4829 }
4830 if slot == u32::MAX {
4831 pen_x += adv_phys * fit_scale;
4832 continue;
4833 }
4834 let gx0: i32 = pen_x.round() as i32;
4835 let gw: i32 = gw_u16 as i32;
4836 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4837 let gy0: i32 =
4838 (base_y_phys + ((line_h_phys - (gh_u16 as f32)) * 0.5).round()) as i32;
4839 if gy0 < clip_y1 && gy0 + (gh_u16 as i32) > clip_y0 {
4840 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4841 }
4842 }
4843 pen_x += adv_phys * fit_scale;
4844 }
4845 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4846 (run_start, run_len)
4847 }
4848
4849 fn resolve_text_run_glyphs(
4865 layout: &TextLayoutResult,
4866 rect: Rect,
4867 style: TextStyle,
4868 clip_dims: (Rect, u32, u32, f32),
4869 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4870 out_glyphs: &mut Vec<PositionedGlyph>,
4871 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4872 ) -> (u32, u32) {
4873 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4874 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4875 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4876 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4877 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4878 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4879 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4880 return (0, 0);
4881 }
4882 let phys_font_size: f32 = style.get_font_size() * scale;
4883 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4884 let bold: bool = style.get_weight().is_bold();
4885 let monospace: bool = style.get_family() == FontFamily::Monospace;
4886 let italic: bool = style.get_italic();
4887 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4888 let ascii_table_idx: usize =
4889 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4890 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4891 let box_w_phys: f32 = rect.get_width() * scale;
4892 let letter_sp: f32 = style.get_letter_spacing() * scale;
4893 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4894 let base_x_phys: f32 = (rect.get_x() * scale).round();
4895 let base_y_phys: f32 = (rect.get_y() * scale).round();
4896 let clip_x1_f: f32 = clip_x1 as f32;
4897 let clip_y0_f: f32 = clip_y0 as f32;
4898 let clip_y1_f: f32 = clip_y1 as f32;
4899 let align: TextAlign = style.get_align();
4900 let run_start: u32 = out_glyphs.len() as u32;
4901 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4902 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4903 let pen_y: f32 = base_y_phys + line_off_y;
4904 if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
4905 continue;
4906 }
4907 let line_str: &str = line.get_text().as_str();
4908 line_scratch.clear();
4909 let mut line_w_phys: f32 = 0.0;
4910 if line_str.is_ascii() {
4911 for &byte in line_str.as_bytes() {
4912 if byte == b' ' {
4913 line_w_phys += space_step;
4914 line_scratch.push((u32::MAX, space_step, 0, 0));
4915 } else {
4916 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4917 ascii_table_idx,
4918 byte,
4919 key_meta,
4920 font_provider,
4921 );
4922 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4923 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4924 line_w_phys += adv_phys;
4925 line_scratch.push((
4926 slot,
4927 adv_phys,
4928 glyph.get_width().min(u16::MAX as u32) as u16,
4929 glyph.get_height().min(u16::MAX as u32) as u16,
4930 ));
4931 }
4932 }
4933 } else {
4934 for ch in line_str.chars() {
4935 if ch == ' ' {
4936 line_w_phys += space_step;
4937 line_scratch.push((u32::MAX, space_step, 0, 0));
4938 } else {
4939 let slot: u32 = if ch.is_ascii() {
4940 glyph_atlas.get_or_rasterize_ascii_slot_with(
4941 ascii_table_idx,
4942 ch as u8,
4943 key_meta,
4944 font_provider,
4945 )
4946 } else {
4947 let key: GlyphKey = GlyphKey {
4948 codepoint: ch,
4949 size_tenths,
4950 bold,
4951 monospace,
4952 italic,
4953 };
4954 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4955 };
4956 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4957 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4958 line_w_phys += adv_phys;
4959 line_scratch.push((
4960 slot,
4961 adv_phys,
4962 glyph.get_width().min(u16::MAX as u32) as u16,
4963 glyph.get_height().min(u16::MAX as u32) as u16,
4964 ));
4965 }
4966 }
4967 }
4968 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4969 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4970 } else {
4971 1.0
4972 };
4973 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4974 let align_x: f32 = match align {
4975 TextAlign::Left => 0.0,
4976 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4977 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4978 };
4979 let mut pen_x: f32 = base_x_phys + align_x.round();
4980 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4981 if slot == u32::MAX {
4982 pen_x += adv_phys * fit_scale;
4983 continue;
4984 }
4985 if pen_x > clip_x1_f {
4986 break;
4987 }
4988 let gx0: i32 = pen_x.round() as i32;
4989 let gw: i32 = gw_u16 as i32;
4990 let gh: i32 = gh_u16 as i32;
4991 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4992 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
4993 let gy0: i32 = (pen_y + glyph_v_off) as i32;
4994 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4995 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4996 }
4997 }
4998 pen_x += adv_phys * fit_scale;
4999 }
5000 }
5001 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
5002 (run_start, run_len)
5003 }
5004
5005 #[must_use]
5019 fn resolve_text_caret_rect(
5020 layout_opt: Option<&TextLayoutResult>,
5021 rects: (Rect, Rect),
5022 style: TextStyle,
5023 caret_opts: (f32, f32, bool),
5024 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
5025 ) -> Rect {
5026 let (text_rect, content_rect): (Rect, Rect) = rects;
5027 let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
5028 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
5029 let phys_font_size: f32 = style.get_font_size() * scale;
5030 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
5031 let bold: bool = style.get_weight().is_bold();
5032 let monospace: bool = style.get_family() == FontFamily::Monospace;
5033 let italic: bool = style.get_italic();
5034 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
5035 let letter_sp: f32 = style.get_letter_spacing() * scale;
5036 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
5037 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
5038 if let Some(layout) = layout_opt {
5039 let lh: f32 = layout.get_line_height_px() * scale;
5040 let idx: usize = layout.get_lines().len().saturating_sub(1);
5041 let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
5042 let ascii_table_idx: usize =
5043 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
5044 let mut acc: f32 = 0.0;
5045 for ch in line.get_text().chars() {
5046 if ch == ' ' {
5047 acc += space_step;
5048 } else {
5049 let slot: u32 = if ch.is_ascii() {
5050 glyph_atlas.get_or_rasterize_ascii_slot_with(
5051 ascii_table_idx,
5052 ch as u8,
5053 key_meta,
5054 font_provider,
5055 )
5056 } else {
5057 let key: GlyphKey = GlyphKey {
5058 codepoint: ch,
5059 size_tenths,
5060 bold,
5061 monospace,
5062 italic,
5063 };
5064 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
5065 };
5066 let adv: f32 =
5067 (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
5068 acc += adv + letter_sp;
5069 }
5070 }
5071 acc
5072 } else {
5073 0.0
5074 };
5075 (w_phys, idx, lh)
5076 } else {
5077 (
5078 0.0,
5079 0,
5080 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
5081 )
5082 };
5083 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
5084 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
5085 let min_x: f32 = content_rect.get_x() * scale;
5086 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
5087 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
5088 let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
5089 .min(max_x)
5090 .max(min_x);
5091 let caret_y_phys: f32 = if multiline {
5092 let raw_y: f32 = content_rect.get_y() * scale
5093 + (line_idx as f32) * line_h_phys
5094 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
5095 raw_y
5096 .min(content_rect.bottom() * scale - caret_h_phys)
5097 .max(content_rect.get_y() * scale)
5098 } else {
5099 content_rect.get_y() * scale
5100 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
5101 };
5102 Rect::new(
5103 caret_x_phys.round(),
5104 caret_y_phys.round(),
5105 caret_w_phys.round().max(1.0),
5106 caret_h_phys.round().max(2.0),
5107 )
5108 }
5109
5110 #[must_use]
5122 fn collect_active_rounded(
5123 stack: &[Option<RoundedClipMask>],
5124 out: &mut Vec<RoundedClipMask>,
5125 vis: Rect,
5126 ) -> (u32, u16) {
5127 let start: u32 = out.len() as u32;
5128 for entry in stack.iter().copied().flatten() {
5129 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
5130 out.push(entry);
5131 }
5132 }
5133 let len: u16 = (out.len() as u32)
5134 .saturating_sub(start)
5135 .min(u16::MAX as u32) as u16;
5136 (start, len)
5137 }
5138
5139 #[must_use]
5150 fn resolve_opaque_clear_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5151 let Some(DrawCommand::FillRoundedRect {
5152 rect,
5153 color,
5154 radius,
5155 border,
5156 }) = next_cmd
5157 else {
5158 return (Rect::default(), Rect::default());
5159 };
5160 if color.get_alpha() != 255 {
5161 return (Rect::default(), Rect::default());
5162 }
5163 let border_width: f32 = if border.get_width() > 0.0 && border.get_color().get_alpha() < 255
5164 {
5165 (border.get_width() * scale).max(1.0)
5166 } else {
5167 0.0
5168 };
5169 let phys: Rect = snap_physical_rect(*rect, scale);
5170 let r_max: f32 = Self::scale_radius(*radius, scale)
5171 .max_radius()
5172 .min(phys.get_width() * 0.5)
5173 .min(phys.get_height() * 0.5);
5174 let pad: f32 = 1.5 + border_width;
5175 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5176 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5177 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5178 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5179 } else {
5180 Rect::default()
5181 };
5182 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5183 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5184 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5185 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5186 } else {
5187 Rect::default()
5188 };
5189 (cut_h, cut_v)
5190 }
5191
5192 #[must_use]
5203 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5204 let Some(DrawCommand::FillRoundedRect {
5205 rect,
5206 color,
5207 radius,
5208 ..
5209 }) = next_cmd
5210 else {
5211 return (Rect::default(), Rect::default());
5212 };
5213 if color.get_alpha() != 255 {
5214 return (Rect::default(), Rect::default());
5215 }
5216 let phys: Rect = snap_physical_rect(*rect, scale);
5217 let r_max: f32 = Self::scale_radius(*radius, scale)
5218 .max_radius()
5219 .min(phys.get_width() * 0.5)
5220 .min(phys.get_height() * 0.5);
5221 let pad: f32 = 1.5;
5222 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5223 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5224 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5225 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5226 } else {
5227 Rect::default()
5228 };
5229 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5230 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5231 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5232 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5233 } else {
5234 Rect::default()
5235 };
5236 (cut_h, cut_v)
5237 }
5238
5239 fn save_single_cached_rounded_corners(
5254 band: &mut PixelBand<'_>,
5255 mask: RoundedClipMask,
5256 clip: Rect,
5257 band_bounds: (u32, u32, u32),
5258 corner_masks: &[CachedCornerMask],
5259 scratch: &mut BandCornerScratch,
5260 ) -> bool {
5261 let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
5262 let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
5263 let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5264 let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
5265 let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5266 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5267 return false;
5268 }
5269 let rect: Rect = mask.get_rect();
5270 let rx0_i: i32 = rect.get_x().round() as i32;
5271 let ry0_i: i32 = rect.get_y().round() as i32;
5272 let rx1_i: i32 = rect.right().round() as i32;
5273 let ry1_i: i32 = rect.bottom().round() as i32;
5274 let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
5275 scratch.saved_bytes.clear();
5276 scratch.saved_rows.clear();
5277 for (query_val, &mask_id) in mask_ids.iter().enumerate() {
5278 if mask_id == u32::MAX {
5279 continue;
5280 }
5281 let Some(cm) = corner_masks.get(mask_id as usize) else {
5282 continue;
5283 };
5284 let dim_i: i32 = cm.dim as i32;
5285 let origin_x: i32 = if query_val == 0 || query_val == 3 {
5286 rx0_i
5287 } else {
5288 rx1_i - dim_i
5289 };
5290 let origin_y: i32 = if query_val == 0 || query_val == 1 {
5291 ry0_i
5292 } else {
5293 ry1_i - dim_i
5294 };
5295 let bx0: i32 = origin_x.max(clip_x0);
5296 let bx1: i32 = (origin_x + dim_i).min(clip_x1);
5297 let by0: i32 = origin_y.max(clip_y0);
5298 let by1: i32 = (origin_y + dim_i).min(clip_y1);
5299 if bx0 >= bx1 || by0 >= by1 {
5300 continue;
5301 }
5302 for y_i in by0..by1 {
5303 let my: usize = (y_i - origin_y) as usize;
5304 let span: CornerMaskRowSpan = cm.row_spans[my];
5305 if span.dirty_start >= span.dirty_end {
5306 continue;
5307 }
5308 let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
5309 let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
5310 if sx0_i >= sx1_i {
5311 continue;
5312 }
5313 let pos_y: u32 = y_i as u32;
5314 let sx0: u32 = sx0_i as u32;
5315 let sx1: u32 = sx1_i as u32;
5316 if let Some(row) = band.row_slice_mut(pos_y) {
5317 let b0: usize = (sx0 as usize) * 4;
5318 let b1: usize = (sx1 as usize) * 4;
5319 let byte_off: usize = scratch.saved_bytes.len();
5320 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5321 scratch.saved_rows.push(SavedCornerRow {
5322 y: pos_y,
5323 sx0,
5324 sx1,
5325 byte_off,
5326 mask_id,
5327 origin_x,
5328 origin_y,
5329 });
5330 }
5331 }
5332 }
5333 !scratch.saved_rows.is_empty()
5334 }
5335
5336 fn restore_single_cached_rounded_corners(
5344 band: &mut PixelBand<'_>,
5345 corner_masks: &[CachedCornerMask],
5346 scratch: &BandCornerScratch,
5347 ) {
5348 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5349 for entry in scratch.saved_rows.iter() {
5350 let Some(row) = band.row_slice_mut(entry.y) else {
5351 continue;
5352 };
5353 let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
5354 let dim: usize = cm.dim as usize;
5355 let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
5356 let span: CornerMaskRowSpan = cm.row_spans[my];
5357 let sx0_i: i32 = entry.sx0 as i32;
5358 let sx1_i: i32 = entry.sx1 as i32;
5359 if span.ext_start < span.ext_end {
5360 let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
5361 let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
5362 if ex0 < ex1 {
5363 let dst_b0: usize = (ex0 as usize) * 4;
5364 let dst_b1: usize = (ex1 as usize) * 4;
5365 let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
5366 let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
5367 row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
5368 }
5369 }
5370 if span.aa_start < span.aa_end {
5371 let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
5372 let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
5373 if ax0 < ax1 {
5374 let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
5375 for x_i in ax0..ax1 {
5376 let mx: usize = (x_i - entry.origin_x) as usize;
5377 let cov_u8: u8 = cov_row[mx];
5378 if cov_u8 >= 16 {
5379 continue;
5380 }
5381 let dst_off: usize = (x_i as usize) * 4;
5382 let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
5383 let saved_rgba: [u8; 4] = [
5384 saved_bytes[src_off],
5385 saved_bytes[src_off + 1],
5386 saved_bytes[src_off + 2],
5387 saved_bytes[src_off + 3],
5388 ];
5389 if cov_u8 == 0 {
5390 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5391 } else {
5392 let cov: f32 = (cov_u8 as f32) * 0.0625;
5393 lerp_pixel_slice_from_saved_linear(
5394 &mut row[dst_off..dst_off + 4],
5395 saved_rgba,
5396 cov,
5397 );
5398 }
5399 }
5400 }
5401 }
5402 }
5403 }
5404
5405 pub(crate) fn render_band(
5420 band: &mut PixelBand<'_>,
5421 commands: &[DrawCommand],
5422 prepped: &[PreppedCommand],
5423 aux: BandAuxSlices<'_>,
5424 glyph_atlas: &GlyphAtlas,
5425 render_opts: (f32, AntialiasingMode),
5426 ) -> usize {
5427 let BandAuxSlices {
5428 positioned_glyphs,
5429 caret_rects,
5430 rounded_clips,
5431 corner_masks,
5432 } = aux;
5433 let (scale, aa): (f32, AntialiasingMode) = render_opts;
5434 let band_y0: u32 = band.y_offset();
5435 let band_y1: u32 = band.y_end();
5436 let fb_w: u32 = band.width();
5437 let band_rect: Rect =
5438 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
5439 let has_any_rounded: bool = !rounded_clips.is_empty();
5440 let mut scratch: BandCornerScratch = if has_any_rounded {
5441 BAND_CORNER_SCRATCH
5442 .try_with(|cell: &RefCell<BandCornerScratch>| {
5443 cell.try_borrow_mut()
5444 .ok()
5445 .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
5446 })
5447 .ok()
5448 .flatten()
5449 .unwrap_or_default()
5450 } else {
5451 BandCornerScratch::default()
5452 };
5453 let mut shaded: usize = 0;
5454 let prepped_len: usize = prepped.len();
5455 let mut idx: usize = 0;
5456 while idx < prepped_len {
5457 let item: &PreppedCommand = &prepped[idx];
5458 if item.get_cmd_index() == usize::MAX {
5459 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5460 idx += (item.get_skip_delta() as usize).max(1);
5461 } else {
5462 idx += 1;
5463 }
5464 continue;
5465 }
5466 idx += 1;
5467 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5468 continue;
5469 }
5470 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
5471 continue;
5472 };
5473 let rc_len: usize = item.get_rounded_clip_len() as usize;
5474 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
5475 let start: usize = item.get_rounded_clip_start() as usize;
5476 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
5477 &rounded_clips[start..end]
5478 } else {
5479 &[]
5480 };
5481 let mut corner_mode: u8 = 0;
5482 if item_masks.len() == 1 {
5483 let mask: RoundedClipMask = item_masks[0];
5484 let rect: Rect = mask.get_rect();
5485 let max_r: f32 = (rect.get_width() * 0.5)
5486 .min(rect.get_height() * 0.5)
5487 .max(0.0);
5488 let radius: CornerRadius = mask.get_radius();
5489 let radii: [f32; 4] = [
5490 radius.get_top_left().min(max_r),
5491 radius.get_top_right().min(max_r),
5492 radius.get_bottom_right().min(max_r),
5493 radius.get_bottom_left().min(max_r),
5494 ];
5495 let ids: [u32; 4] = mask.get_corner_mask_ids();
5496 let all_cached: bool =
5497 radii
5498 .iter()
5499 .zip(ids.iter())
5500 .all(|(&red_val, &id): (&f32, &u32)| {
5501 red_val <= 0.25 || (id as usize) < corner_masks.len()
5502 });
5503 if all_cached {
5504 if Self::save_single_cached_rounded_corners(
5505 band,
5506 mask,
5507 active_clip,
5508 (fb_w, band_y0, band_y1),
5509 corner_masks,
5510 &mut scratch,
5511 ) {
5512 corner_mode = 1;
5513 }
5514 } else {
5515 scratch.corner_boxes.clear();
5516 scratch.saved_bytes.clear();
5517 collect_rounded_clip_boxes(
5518 mask,
5519 active_clip,
5520 (fb_w, band_y0, band_y1),
5521 &mut scratch.corner_boxes,
5522 );
5523 if !scratch.corner_boxes.is_empty() {
5524 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5525 let b0: usize = (bx0 as usize) * 4;
5526 let b1: usize = (bx1 as usize) * 4;
5527 for pos_y in by0..by1 {
5528 if let Some(row) = band.row_slice_mut(pos_y) {
5529 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5530 }
5531 }
5532 }
5533 corner_mode = 2;
5534 }
5535 }
5536 } else if !item_masks.is_empty() {
5537 scratch.corner_boxes.clear();
5538 scratch.saved_bytes.clear();
5539 for mask in item_masks.iter().copied() {
5540 collect_rounded_clip_boxes(
5541 mask,
5542 active_clip,
5543 (fb_w, band_y0, band_y1),
5544 &mut scratch.corner_boxes,
5545 );
5546 }
5547 if !scratch.corner_boxes.is_empty() {
5548 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5549 let b0: usize = (bx0 as usize) * 4;
5550 let b1: usize = (bx1 as usize) * 4;
5551 for coord_y in by0..by1 {
5552 if let Some(row) = band.row_slice_mut(coord_y) {
5553 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5554 }
5555 }
5556 }
5557 corner_mode = 2;
5558 }
5559 }
5560 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
5561 shaded += match cmd {
5562 DrawCommand::Clear(color) => {
5563 let cutouts: (Rect, Rect) =
5564 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v());
5565 if cutouts.0.get_width() > 0.0 || cutouts.1.get_width() > 0.0 {
5566 let cx0: u32 = (active_clip.get_x().floor().max(0.0) as u32).min(fb_w);
5567 let cx1: u32 = (active_clip.right().ceil().max(0.0) as u32).min(fb_w);
5568 let cy0: u32 = (active_clip.get_y().floor().max(0.0) as u32)
5569 .max(band_y0)
5570 .min(band_y1);
5571 let cy1: u32 = (active_clip.bottom().ceil().max(0.0) as u32)
5572 .max(band_y0)
5573 .min(band_y1);
5574 let rgba: [u8; 4] = [
5575 color.get_red(),
5576 color.get_green(),
5577 color.get_blue(),
5578 color.get_alpha(),
5579 ];
5580 let mut count: usize = 0;
5581 if cx0 < cx1 && cy0 < cy1 {
5582 for sample_y in cy0..cy1 {
5583 let (cut0, cut1): (u32, u32) =
5584 Self::shadow_row_cutout(sample_y, cutouts, cx0, cx1);
5585 if cut0 <= cx0 && cut1 >= cx1 {
5586 continue;
5587 }
5588 if let Some(row) = band.row_slice_mut(sample_y) {
5589 if cut0 < cut1 {
5590 if cx0 < cut0 {
5591 fill_rgba_span_32(
5592 &mut row[(cx0 as usize) * 4..(cut0 as usize) * 4],
5593 rgba,
5594 );
5595 count += (cut0 - cx0) as usize;
5596 }
5597 if cut1 < cx1 {
5598 fill_rgba_span_32(
5599 &mut row[(cut1 as usize) * 4..(cx1 as usize) * 4],
5600 rgba,
5601 );
5602 count += (cx1 - cut1) as usize;
5603 }
5604 } else {
5605 fill_rgba_span_32(
5606 &mut row[(cx0 as usize) * 4..(cx1 as usize) * 4],
5607 rgba,
5608 );
5609 count += (cx1 - cx0) as usize;
5610 }
5611 }
5612 }
5613 }
5614 count
5615 } else if active_clip.get_x() <= 0.0
5616 && active_clip.get_width() >= (band.width() as f32)
5617 && active_clip.get_y() <= (band_y0 as f32)
5618 && active_clip.bottom() >= (band_y1 as f32)
5619 {
5620 band.clear(*color);
5621 (band.width() as usize) * ((band_y1 - band_y0) as usize)
5622 } else {
5623 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
5624 }
5625 }
5626 DrawCommand::FillRoundedRect {
5627 rect,
5628 color,
5629 radius,
5630 border,
5631 } => {
5632 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5633 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5634 let border_width: f32 = if border.get_width() > 0.0 {
5635 (border.get_width() * scale).max(1.0)
5636 } else {
5637 0.0
5638 };
5639 let phys_border: Border = Border::new(border_width, border.get_color());
5640 Self::raster_rounded_rect(
5641 band,
5642 phys_rect,
5643 *color,
5644 phys_radius,
5645 phys_border,
5646 active_clip,
5647 aa,
5648 )
5649 }
5650 DrawCommand::LinearGradientRect {
5651 rect,
5652 gradient,
5653 radius,
5654 } => {
5655 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5656 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5657 Self::raster_gradient_rect(
5658 band,
5659 phys_rect,
5660 *gradient,
5661 phys_radius,
5662 active_clip,
5663 aa,
5664 )
5665 }
5666 DrawCommand::BoxShadow {
5667 rect,
5668 radius,
5669 shadow,
5670 } => {
5671 let spread: f32 = shadow.get_spread_radius() * scale;
5672 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5673 let sigma: f32 = (blur * 0.5).max(0.75);
5674 let pad: f32 = (sigma * 3.0).ceil();
5675 let base_rect: Rect = snap_physical_rect(*rect, scale);
5676 let caster_rect: Rect = Rect::new(
5677 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
5678 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
5679 (base_rect.get_width() + spread * 2.0).max(1.0),
5680 (base_rect.get_height() + spread * 2.0).max(1.0),
5681 );
5682 let shadow_rect: Rect = Rect::new(
5683 caster_rect.get_x() - pad,
5684 caster_rect.get_y() - pad,
5685 caster_rect.get_width() + pad * 2.0,
5686 caster_rect.get_height() + pad * 2.0,
5687 );
5688 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
5689 let phys_radius: CornerRadius = CornerRadius::new(
5690 (raw_r.get_top_left() + spread).max(0.0),
5691 (raw_r.get_top_right() + spread).max(0.0),
5692 (raw_r.get_bottom_right() + spread).max(0.0),
5693 (raw_r.get_bottom_left() + spread).max(0.0),
5694 );
5695 Self::raster_shadow(
5696 band,
5697 (shadow_rect, caster_rect, active_clip),
5698 phys_radius,
5699 sigma,
5700 shadow.get_color(),
5701 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
5702 )
5703 }
5704 DrawCommand::BackdropBlur {
5705 rect,
5706 radius,
5707 blur_radius,
5708 } => {
5709 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5710 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5711 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 48.0);
5712 Self::raster_backdrop_blur(band, phys_rect, phys_radius, phys_blur, active_clip)
5713 }
5714 DrawCommand::TextRun { style, .. } => {
5715 let g_start: usize = item.get_glyph_run_start() as usize;
5716 let g_len: usize = item.get_glyph_run_len() as usize;
5717 if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
5718 Self::raster_text_run_band(
5719 band,
5720 run_slice,
5721 style.get_color(),
5722 active_clip,
5723 glyph_atlas,
5724 )
5725 } else {
5726 0
5727 }
5728 }
5729 DrawCommand::TextCaret { color, .. } => {
5730 let cidx: usize = item.get_caret_rect_idx() as usize;
5731 if let Some(&caret_rect) = caret_rects.get(cidx) {
5732 Self::raster_rounded_rect(
5733 band,
5734 caret_rect,
5735 *color,
5736 CornerRadius::all(0.5 * scale),
5737 Border::default(),
5738 active_clip,
5739 aa,
5740 )
5741 } else {
5742 0
5743 }
5744 }
5745 DrawCommand::Image {
5746 rect,
5747 buffer,
5748 radius,
5749 } => {
5750 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5751 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5752 Self::raster_rgba_bytes(
5753 band,
5754 phys_rect,
5755 (buffer.get_width(), buffer.get_height(), buffer.get_pixels()),
5756 phys_radius,
5757 active_clip,
5758 aa,
5759 )
5760 }
5761 DrawCommand::SharedImage {
5762 rect,
5763 width,
5764 height,
5765 pixels,
5766 radius,
5767 } => {
5768 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5769 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5770 Self::raster_rgba_bytes(
5771 band,
5772 phys_rect,
5773 (*width, *height, pixels.as_slice()),
5774 phys_radius,
5775 active_clip,
5776 aa,
5777 )
5778 }
5779 DrawCommand::Line {
5780 from,
5781 to,
5782 color,
5783 width,
5784 } => {
5785 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
5786 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
5787 Self::raster_line(
5788 band,
5789 p0,
5790 p1,
5791 *color,
5792 (width * scale).max(1.0),
5793 active_clip,
5794 aa,
5795 )
5796 }
5797 DrawCommand::Circle {
5798 center,
5799 radius,
5800 color,
5801 } => {
5802 let point_coords: Point =
5803 Point::new(center.get_x() * scale, center.get_y() * scale);
5804 Self::raster_circle(band, point_coords, radius * scale, *color, active_clip, aa)
5805 }
5806 DrawCommand::Triangle { p0, p1, p2, color } => {
5807 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
5808 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
5809 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
5810 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
5811 }
5812 DrawCommand::SpriteRegion {
5813 rect,
5814 buffer,
5815 src_rect,
5816 tint,
5817 } => {
5818 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5819 Self::raster_sprite_region(
5820 band,
5821 phys_rect,
5822 buffer,
5823 *src_rect,
5824 *tint,
5825 active_clip,
5826 aa,
5827 )
5828 }
5829 DrawCommand::PushClip(_)
5830 | DrawCommand::PushRoundedClip { .. }
5831 | DrawCommand::PopClip => 0,
5832 };
5833 if corner_mode == 1 {
5834 Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
5835 } else if corner_mode == 2 {
5836 let multi_mask: bool = item_masks.len() > 1;
5837 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5838 let mut byte_cursor: usize = 0;
5839 for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
5840 for value_y in by0..by1 {
5841 let Some(row) = band.row_slice_mut(value_y) else {
5842 byte_cursor += ((bx1 - bx0) as usize) * 4;
5843 continue;
5844 };
5845 for pos_x in bx0..bx1 {
5846 let saved_rgba: [u8; 4] = [
5847 saved_bytes[byte_cursor],
5848 saved_bytes[byte_cursor + 1],
5849 saved_bytes[byte_cursor + 2],
5850 saved_bytes[byte_cursor + 3],
5851 ];
5852 byte_cursor += 4;
5853 if multi_mask
5854 && scratch.corner_boxes[..box_idx].iter().any(
5855 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
5856 pos_x >= px0
5857 && pos_x < px1
5858 && value_y >= py0
5859 && value_y < py1
5860 },
5861 )
5862 {
5863 continue;
5864 }
5865 let mut cov: f32 = 1.0;
5866 for mask in item_masks.iter().copied() {
5867 cov *= rounded_clip_coverage_cached(
5868 pos_x,
5869 value_y,
5870 mask,
5871 corner_masks,
5872 aa,
5873 );
5874 if cov <= 0.0005 {
5875 break;
5876 }
5877 }
5878 let dst_off: usize = (pos_x as usize) * 4;
5879 if cov <= 0.0005 {
5880 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5881 } else if cov < 0.9995 {
5882 lerp_pixel_slice_from_saved_linear(
5883 &mut row[dst_off..dst_off + 4],
5884 saved_rgba,
5885 cov,
5886 );
5887 }
5888 }
5889 }
5890 }
5891 }
5892 }
5893 if has_any_rounded {
5894 let _: bool = BAND_CORNER_SCRATCH
5895 .try_with(|cell: &RefCell<BandCornerScratch>| {
5896 if let Ok(mut guard) = cell.try_borrow_mut() {
5897 *guard = scratch;
5898 }
5899 })
5900 .is_ok();
5901 }
5902 shaded
5903 }
5904
5905 fn scale_rect(rect: Rect, scale: f32) -> Rect {
5916 Rect::new(
5917 rect.get_x() * scale,
5918 rect.get_y() * scale,
5919 rect.get_width() * scale,
5920 rect.get_height() * scale,
5921 )
5922 }
5923
5924 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
5935 CornerRadius::new(
5936 radius.get_top_left() * scale,
5937 radius.get_top_right() * scale,
5938 radius.get_bottom_right() * scale,
5939 radius.get_bottom_left() * scale,
5940 )
5941 }
5942
5943 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
5956 if color.get_alpha() == 0 {
5957 return 0;
5958 }
5959 let Some(vis) = rect.intersect(clip) else {
5960 return 0;
5961 };
5962 let fb_w: u32 = band.width();
5963 let band_y0: u32 = band.y_offset();
5964 let band_y1: u32 = band.y_end();
5965 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5966 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5967 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5968 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5969 if x0 >= x1 || y0 >= y1 {
5970 return 0;
5971 }
5972 let span_len: usize = (x1 - x0) as usize;
5973 let rows: usize = (y1 - y0) as usize;
5974 let sa: u8 = color.get_alpha();
5975 if sa == 255 {
5976 band.fill_rect_opaque_preclipped(
5977 x0,
5978 x1,
5979 y0,
5980 y1,
5981 [color.get_red(), color.get_green(), color.get_blue(), 255],
5982 );
5983 } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
5984 let bx0: usize = (x0 as usize) * 4;
5985 let bx1: usize = (x1 as usize) * 4;
5986 if span_len.saturating_mul(rows) >= 512 {
5987 let luts: [[u8; 256]; 4] = build_linear_blend_luts(color);
5988 for row in rows_buf.chunks_exact_mut(row_stride) {
5989 fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
5990 }
5991 } else {
5992 for row in rows_buf.chunks_exact_mut(row_stride) {
5993 fill_span_linear_slice(&mut row[bx0..bx1], color);
5994 }
5995 }
5996 }
5997 span_len * rows
5998 }
5999
6000 #[must_use]
6015 fn build_vertical_edge_strip(
6016 x_span: (u32, u32),
6017 geom: (f32, f32, f32, f32),
6018 colors: (Color, Border),
6019 lin_colors: ([f32; 4], [f32; 4]),
6020 aa: AntialiasingMode,
6021 out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
6022 ) -> (usize, usize) {
6023 let (x_start, x_end): (u32, u32) = x_span;
6024 let (cx, half_w, half_h, border_width): (f32, f32, f32, f32) = geom;
6025 let (color, border): (Color, Border) = colors;
6026 let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
6027 let has_border: bool = border_width > 0.0 && border.get_color().get_alpha() > 0;
6028 let inner_hw: f32 = (half_w - border_width).max(0.0);
6029 let inner_hh: f32 = (half_h - border_width).max(0.0);
6030 let mut len: usize = 0;
6031 let mut shaded: usize = 0;
6032 for pos_x in x_start..x_end {
6033 let px: f32 = (pos_x as f32) + 0.5 - cx;
6034 let dist: f32 = px.abs() - half_w;
6035 if dist > 0.85 {
6036 continue;
6037 }
6038 if !has_border {
6039 if dist < -0.85 {
6040 let sa: u8 = color.get_alpha();
6041 if sa > 0 {
6042 let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
6043 out[len] = EdgeBlendSample {
6044 x: pos_x,
6045 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
6046 sr_a: fill_lin[0] * alpha_val,
6047 sg_a: fill_lin[1] * alpha_val,
6048 sb_a: fill_lin[2] * alpha_val,
6049 inv_a: 1.0 - alpha_val,
6050 sa_u32: sa as u32,
6051 is_opaque: sa == 255,
6052 };
6053 len += 1;
6054 shaded += 1;
6055 }
6056 continue;
6057 }
6058 let outer_cov: f32 = sdf_coverage(dist, aa);
6059 if outer_cov > 0.0 && color.get_alpha() > 0 {
6060 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
6061 shaded += 1;
6062 if alpha_f > 0.0002 {
6063 let first_val: f32 = alpha_f.clamp(0.0, 1.0);
6064 out[len] = EdgeBlendSample {
6065 x: pos_x,
6066 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
6067 sr_a: fill_lin[0] * first_val,
6068 sg_a: fill_lin[1] * first_val,
6069 sb_a: fill_lin[2] * first_val,
6070 inv_a: 1.0 - first_val,
6071 sa_u32: (first_val * 255.0) as u32,
6072 is_opaque: first_val >= 0.9995,
6073 };
6074 len += 1;
6075 }
6076 }
6077 continue;
6078 }
6079 if dist < -(border_width + 0.85) {
6080 let sa: u8 = color.get_alpha();
6081 if sa > 0 {
6082 let area_val: f32 = (sa as f32) * (1.0 / 255.0);
6083 out[len] = EdgeBlendSample {
6084 x: pos_x,
6085 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
6086 sr_a: fill_lin[0] * area_val,
6087 sg_a: fill_lin[1] * area_val,
6088 sb_a: fill_lin[2] * area_val,
6089 inv_a: 1.0 - area_val,
6090 sa_u32: sa as u32,
6091 is_opaque: sa == 255,
6092 };
6093 len += 1;
6094 shaded += 1;
6095 }
6096 continue;
6097 }
6098 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6099 px.abs() - inner_hw
6100 } else {
6101 2.0
6102 };
6103 if dist < -0.85 && inner_dist > 0.85 {
6104 let bc: Color = border.get_color();
6105 let sa: u8 = bc.get_alpha();
6106 let alpha_val_primary: f32 = (sa as f32) * (1.0 / 255.0);
6107 out[len] = EdgeBlendSample {
6108 x: pos_x,
6109 rgba: [bc.get_red(), bc.get_green(), bc.get_blue(), 255],
6110 sr_a: border_lin[0] * alpha_val_primary,
6111 sg_a: border_lin[1] * alpha_val_primary,
6112 sb_a: border_lin[2] * alpha_val_primary,
6113 inv_a: 1.0 - alpha_val_primary,
6114 sa_u32: sa as u32,
6115 is_opaque: sa == 255,
6116 };
6117 len += 1;
6118 shaded += 1;
6119 continue;
6120 }
6121 let outer_cov: f32 = sdf_coverage(dist, aa);
6122 if outer_cov <= 0.0 {
6123 continue;
6124 }
6125 let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6126 sdf_coverage(inner_dist, aa)
6127 } else {
6128 0.0
6129 };
6130 let mixed: Color =
6131 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6132 let sa: u8 = mixed.get_alpha();
6133 if sa > 0 {
6134 let alpha_val_secondary: f32 = (sa as f32) * (1.0 / 255.0);
6135 out[len] = EdgeBlendSample {
6136 x: pos_x,
6137 rgba: [mixed.get_red(), mixed.get_green(), mixed.get_blue(), 255],
6138 sr_a: SRGB_TO_LIN_LUT[mixed.get_red() as usize] * alpha_val_secondary,
6139 sg_a: SRGB_TO_LIN_LUT[mixed.get_green() as usize] * alpha_val_secondary,
6140 sb_a: SRGB_TO_LIN_LUT[mixed.get_blue() as usize] * alpha_val_secondary,
6141 inv_a: 1.0 - alpha_val_secondary,
6142 sa_u32: sa as u32,
6143 is_opaque: sa == 255,
6144 };
6145 len += 1;
6146 shaded += 1;
6147 }
6148 }
6149 (len, shaded)
6150 }
6151
6152 fn raster_rounded_rect(
6168 band: &mut PixelBand<'_>,
6169 rect: Rect,
6170 color: Color,
6171 radius: CornerRadius,
6172 border: Border,
6173 clip: Rect,
6174 aa: AntialiasingMode,
6175 ) -> usize {
6176 let Some(vis) = rect.intersect(clip) else {
6177 return 0;
6178 };
6179 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6180 if radius.max_radius() <= 0.0 && !has_border {
6181 return Self::fill_rect_clipped(band, rect, color, clip);
6182 }
6183 if radius.max_radius() <= 0.0 && has_border && aa != AntialiasingMode::Msaa4x {
6184 let border_width: f32 = border.get_width();
6185 let bw_r: f32 = border_width.round();
6186 let rx: f32 = rect.get_x();
6187 let ry: f32 = rect.get_y();
6188 let rw: f32 = rect.get_width();
6189 let rh: f32 = rect.get_height();
6190 let int_aligned: bool = bw_r >= 1.0
6191 && (border_width - bw_r).abs() < 1e-4
6192 && (rx - rx.round()).abs() < 1e-4
6193 && (ry - ry.round()).abs() < 1e-4
6194 && (rw - rw.round()).abs() < 1e-4
6195 && (rh - rh.round()).abs() < 1e-4
6196 && rw >= bw_r * 2.0
6197 && rh >= bw_r * 2.0;
6198 if int_aligned {
6199 let bc: Color = border.get_color();
6200 let exact_border: Color = if bw_r < 2.0 {
6201 let b_lin: [f32; 4] = [
6202 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6203 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6204 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6205 (bc.get_alpha() as f32) / 255.0,
6206 ];
6207 composite_fill_and_border_precomputed([0.0; 4], b_lin, 1.0, 0.0)
6208 } else {
6209 bc
6210 };
6211 let mut shaded_fast: usize = 0;
6212 shaded_fast +=
6213 Self::fill_rect_clipped(band, Rect::new(rx, ry, rw, bw_r), exact_border, clip);
6214 shaded_fast += Self::fill_rect_clipped(
6215 band,
6216 Rect::new(rx, ry + rh - bw_r, rw, bw_r),
6217 exact_border,
6218 clip,
6219 );
6220 let mid_h: f32 = rh - bw_r * 2.0;
6221 if mid_h > 0.0 {
6222 shaded_fast += Self::fill_rect_clipped(
6223 band,
6224 Rect::new(rx, ry + bw_r, bw_r, mid_h),
6225 exact_border,
6226 clip,
6227 );
6228 shaded_fast += Self::fill_rect_clipped(
6229 band,
6230 Rect::new(rx + rw - bw_r, ry + bw_r, bw_r, mid_h),
6231 exact_border,
6232 clip,
6233 );
6234 let mid_w: f32 = rw - bw_r * 2.0;
6235 if mid_w > 0.0 && color.get_alpha() > 0 {
6236 shaded_fast += Self::fill_rect_clipped(
6237 band,
6238 Rect::new(rx + bw_r, ry + bw_r, mid_w, mid_h),
6239 color,
6240 clip,
6241 );
6242 }
6243 }
6244 return shaded_fast;
6245 }
6246 }
6247 let half_w: f32 = rect.get_width() * 0.5;
6248 let half_h: f32 = rect.get_height() * 0.5;
6249 let cx: f32 = rect.get_x() + half_w;
6250 let cy: f32 = rect.get_y() + half_h;
6251 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6252 let fb_w: u32 = band.width();
6253 let band_y0: u32 = band.y_offset();
6254 let band_y1: u32 = band.y_end();
6255 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6256 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6257 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6258 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6259 if x0 >= x1 || y0 >= y1 {
6260 return 0;
6261 }
6262 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
6263 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
6264 let edge_inset: f32 = border_w + 1.5;
6265 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
6266 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
6267 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6268 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
6269 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6270 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
6271 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
6272 let has_center_band: bool = cx0 < cx1;
6273 let fill_lin: [f32; 4] = [
6274 SRGB_TO_LIN_LUT[color.get_red() as usize],
6275 SRGB_TO_LIN_LUT[color.get_green() as usize],
6276 SRGB_TO_LIN_LUT[color.get_blue() as usize],
6277 (color.get_alpha() as f32) / 255.0,
6278 ];
6279 let bc: Color = border.get_color();
6280 let border_lin: [f32; 4] = [
6281 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6282 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6283 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6284 (bc.get_alpha() as f32) / 255.0,
6285 ];
6286 let interior_luts: Option<[[u8; 256]; 4]> = if has_interior
6287 && color.get_alpha() > 0
6288 && color.get_alpha() < 255
6289 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
6290 {
6291 Some(build_linear_blend_luts(color))
6292 } else {
6293 None
6294 };
6295 let mut shaded: usize = 0;
6296 if has_interior {
6297 for pos_y in y0..iy0 {
6298 let py: f32 = (pos_y as f32) + 0.5 - cy;
6299 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6300 if has_center_band {
6301 shaded += Self::raster_rounded_corner_band_row(
6302 band,
6303 pos_y,
6304 (x0, cx0, cx1, x1),
6305 box_geom,
6306 radius,
6307 (color, border, fill_lin, border_lin),
6308 (interior_luts.as_ref(), aa),
6309 );
6310 } else if let Some(row) = band.row_slice_mut(pos_y) {
6311 for pos_x in x0..x1 {
6312 shaded += Self::shade_rounded_pixel_row(
6313 row,
6314 pos_x,
6315 box_geom,
6316 radius,
6317 (color, border, fill_lin, border_lin),
6318 aa,
6319 );
6320 }
6321 }
6322 }
6323 let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
6324 && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
6325 if use_1d_strip {
6326 let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6327 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6328 let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6329 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6330 let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
6331 Self::build_vertical_edge_strip(
6332 (x0, ix0),
6333 (cx, half_w, half_h, border_w),
6334 (color, border),
6335 (fill_lin, border_lin),
6336 aa,
6337 &mut left_strip,
6338 )
6339 } else {
6340 (0, 0)
6341 };
6342 let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
6343 Self::build_vertical_edge_strip(
6344 (ix1, x1),
6345 (cx, half_w, half_h, border_w),
6346 (color, border),
6347 (fill_lin, border_lin),
6348 aa,
6349 &mut right_strip,
6350 )
6351 } else {
6352 (0, 0)
6353 };
6354 let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
6355 let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
6356 let edge_shaded: usize = left_shaded + right_shaded;
6357 let has_edges: bool = left_len > 0 || right_len > 0;
6358 let fill_visible: bool = color.get_alpha() > 0;
6359 let fill_opaque: bool = color.get_alpha() == 255;
6360 let fill_rgba: [u8; 4] =
6361 [color.get_red(), color.get_green(), color.get_blue(), 255];
6362 let interior_span: usize = (ix1 - ix0) as usize;
6363 let ix0_b: usize = (ix0 as usize) * 4;
6364 let ix1_b: usize = (ix1 as usize) * 4;
6365 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6366 for row in rows_buf.chunks_exact_mut(row_stride) {
6367 if fill_visible {
6368 if fill_opaque {
6369 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6370 } else if let Some(ref luts) = interior_luts {
6371 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6372 } else {
6373 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6374 }
6375 shaded += interior_span;
6376 }
6377 if has_edges {
6378 if left_len > 0 {
6379 apply_edge_strip_row(row, left_slice);
6380 }
6381 if right_len > 0 {
6382 apply_edge_strip_row(row, right_slice);
6383 }
6384 shaded += edge_shaded;
6385 }
6386 }
6387 }
6388 } else {
6389 let fill_visible: bool = color.get_alpha() > 0;
6390 let fill_opaque: bool = color.get_alpha() == 255;
6391 let fill_rgba: [u8; 4] =
6392 [color.get_red(), color.get_green(), color.get_blue(), 255];
6393 let interior_span: usize = (ix1 - ix0) as usize;
6394 let ix0_b: usize = (ix0 as usize) * 4;
6395 let ix1_b: usize = (ix1 as usize) * 4;
6396 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6397 for (coord_y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
6398 let py: f32 = (coord_y as f32) + 0.5 - cy;
6399 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6400 if fill_visible {
6401 if fill_opaque {
6402 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6403 } else if let Some(ref luts) = interior_luts {
6404 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6405 } else {
6406 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6407 }
6408 shaded += interior_span;
6409 }
6410 for coord_x in x0..ix0 {
6411 shaded += Self::shade_rounded_pixel_row(
6412 row,
6413 coord_x,
6414 box_geom,
6415 radius,
6416 (color, border, fill_lin, border_lin),
6417 aa,
6418 );
6419 }
6420 for sample_x in ix1..x1 {
6421 shaded += Self::shade_rounded_pixel_row(
6422 row,
6423 sample_x,
6424 box_geom,
6425 radius,
6426 (color, border, fill_lin, border_lin),
6427 aa,
6428 );
6429 }
6430 }
6431 }
6432 }
6433 for sample_y in iy1..y1 {
6434 let py: f32 = (sample_y as f32) + 0.5 - cy;
6435 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6436 if has_center_band {
6437 shaded += Self::raster_rounded_corner_band_row(
6438 band,
6439 sample_y,
6440 (x0, cx0, cx1, x1),
6441 box_geom,
6442 radius,
6443 (color, border, fill_lin, border_lin),
6444 (interior_luts.as_ref(), aa),
6445 );
6446 } else if let Some(row) = band.row_slice_mut(sample_y) {
6447 for value_x in x0..x1 {
6448 shaded += Self::shade_rounded_pixel_row(
6449 row,
6450 value_x,
6451 box_geom,
6452 radius,
6453 (color, border, fill_lin, border_lin),
6454 aa,
6455 );
6456 }
6457 }
6458 }
6459 return shaded;
6460 }
6461 for value_y in y0..y1 {
6462 let py: f32 = (value_y as f32) + 0.5 - cy;
6463 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6464 if has_center_band {
6465 shaded += Self::raster_rounded_corner_band_row(
6466 band,
6467 value_y,
6468 (x0, cx0, cx1, x1),
6469 box_geom,
6470 radius,
6471 (color, border, fill_lin, border_lin),
6472 (interior_luts.as_ref(), aa),
6473 );
6474 } else if let Some(row) = band.row_slice_mut(value_y) {
6475 for pos_x_primary in x0..x1 {
6476 shaded += Self::shade_rounded_pixel_row(
6477 row,
6478 pos_x_primary,
6479 box_geom,
6480 radius,
6481 (color, border, fill_lin, border_lin),
6482 aa,
6483 );
6484 }
6485 }
6486 }
6487 shaded
6488 }
6489
6490 #[inline(always)]
6506 fn raster_rounded_corner_band_row(
6507 band: &mut PixelBand<'_>,
6508 pos_y: u32,
6509 x_bounds: (u32, u32, u32, u32),
6510 geom: (f32, f32, f32, f32),
6511 radius: CornerRadius,
6512 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6513 opts: (Option<&[[u8; 256]; 4]>, AntialiasingMode),
6514 ) -> usize {
6515 let (interior_luts, aa): (Option<&[[u8; 256]; 4]>, AntialiasingMode) = opts;
6516 let Some(row) = band.row_slice_mut(pos_y) else {
6517 return 0;
6518 };
6519 let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
6520 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6521 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6522 style_colors;
6523 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6524 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6525 let inner_thresh: f32 = if has_border {
6526 -(border_w + 0.85)
6527 } else {
6528 -0.85
6529 };
6530 let py_abs: f32 = py.abs();
6531 let fill_visible: bool = color.get_alpha() > 0;
6532 let fill_opaque: bool = color.get_alpha() == 255;
6533 let fill_rgba: [u8; 4] = [color.get_red(), color.get_green(), color.get_blue(), 255];
6534 let mut shaded: usize = 0;
6535 if x0 < cx0 {
6536 let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
6537 if pure_left {
6538 let r_l: f32 = (if py < 0.0 {
6539 radius.get_top_left()
6540 } else {
6541 radius.get_bottom_left()
6542 })
6543 .min(half_w)
6544 .min(half_h)
6545 .max(0.0);
6546 let qy: f32 = py_abs - half_h + r_l;
6547 let r_out: f32 = r_l + 0.85;
6548 if qy <= r_out + 0.05 {
6549 let vis_l0: u32 = if qy > 0.0 {
6550 let max_vis_abs: f32 =
6551 (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6552 ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
6553 } else {
6554 x0
6555 };
6556 let r_in: f32 = r_l + inner_thresh;
6557 let max_in_abs: f32 = if qy <= 0.0 {
6558 if qy < r_in - 0.05 {
6559 half_w + inner_thresh - 1.0
6560 } else {
6561 -1.0
6562 }
6563 } else if r_in > 0.0 && qy < r_in - 0.05 {
6564 (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6565 } else {
6566 -1.0
6567 };
6568 let in_l0: u32 = if max_in_abs > 0.0 {
6569 ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
6570 } else {
6571 cx0
6572 };
6573 for pos_x in vis_l0..in_l0 {
6574 shaded += Self::shade_rounded_pixel_row(
6575 row,
6576 pos_x,
6577 geom,
6578 radius,
6579 style_colors,
6580 aa,
6581 );
6582 }
6583 if in_l0 < cx0 && fill_visible {
6584 let b0: usize = (in_l0 as usize) * 4;
6585 let b1: usize = (cx0 as usize) * 4;
6586 if fill_opaque {
6587 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6588 } else if let Some(luts) = interior_luts {
6589 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6590 } else {
6591 fill_span_linear_slice(&mut row[b0..b1], color);
6592 }
6593 shaded += (cx0 - in_l0) as usize;
6594 }
6595 }
6596 } else {
6597 for coord_x in x0..cx0 {
6598 shaded +=
6599 Self::shade_rounded_pixel_row(row, coord_x, geom, radius, style_colors, aa);
6600 }
6601 }
6602 }
6603 if cx1 < x1 {
6604 let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
6605 if pure_right {
6606 let r_r: f32 = (if py < 0.0 {
6607 radius.get_top_right()
6608 } else {
6609 radius.get_bottom_right()
6610 })
6611 .min(half_w)
6612 .min(half_h)
6613 .max(0.0);
6614 let qy: f32 = py_abs - half_h + r_r;
6615 let r_out: f32 = r_r + 0.85;
6616 if qy <= r_out + 0.05 {
6617 let vis_r1: u32 = if qy > 0.0 {
6618 let max_vis_abs: f32 =
6619 (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6620 ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
6621 } else {
6622 x1
6623 };
6624 let r_in: f32 = r_r + inner_thresh;
6625 let max_in_abs: f32 = if qy <= 0.0 {
6626 if qy < r_in - 0.05 {
6627 half_w + inner_thresh - 1.0
6628 } else {
6629 -1.0
6630 }
6631 } else if r_in > 0.0 && qy < r_in - 0.05 {
6632 (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6633 } else {
6634 -1.0
6635 };
6636 let in_r1: u32 = if max_in_abs > 0.0 {
6637 ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
6638 } else {
6639 cx1
6640 };
6641 if cx1 < in_r1 && fill_visible {
6642 let b0: usize = (cx1 as usize) * 4;
6643 let b1: usize = (in_r1 as usize) * 4;
6644 if fill_opaque {
6645 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6646 } else if let Some(luts) = interior_luts {
6647 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6648 } else {
6649 fill_span_linear_slice(&mut row[b0..b1], color);
6650 }
6651 shaded += (in_r1 - cx1) as usize;
6652 }
6653 for sample_x in in_r1..vis_r1 {
6654 shaded += Self::shade_rounded_pixel_row(
6655 row,
6656 sample_x,
6657 geom,
6658 radius,
6659 style_colors,
6660 aa,
6661 );
6662 }
6663 }
6664 } else {
6665 for value_x in cx1..x1 {
6666 shaded +=
6667 Self::shade_rounded_pixel_row(row, value_x, geom, radius, style_colors, aa);
6668 }
6669 }
6670 }
6671 let dist_y: f32 = py_abs - half_h;
6672 let outer_cov: f32 = sdf_coverage(dist_y, aa);
6673 if outer_cov > 0.0 {
6674 let b0: usize = (cx0 as usize) * 4;
6675 let b1: usize = (cx1 as usize) * 4;
6676 if has_border {
6677 let inner_hh: f32 = (half_h - border_w).max(0.0);
6678 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
6679 sdf_coverage(py_abs - inner_hh, aa)
6680 } else {
6681 0.0
6682 };
6683 let mixed: Color = composite_fill_and_border_precomputed(
6684 fill_lin, border_lin, outer_cov, inner_cov,
6685 );
6686 if mixed.get_alpha() > 0 {
6687 fill_span_linear_slice(&mut row[b0..b1], mixed);
6688 }
6689 shaded += (cx1 - cx0) as usize;
6690 } else if fill_visible {
6691 let row_color: Color = color.multiply_alpha(outer_cov);
6692 if row_color == color
6693 && let Some(luts) = interior_luts
6694 {
6695 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6696 } else {
6697 fill_span_linear_slice(&mut row[b0..b1], row_color);
6698 }
6699 shaded += (cx1 - cx0) as usize;
6700 }
6701 }
6702 shaded
6703 }
6704
6705 #[inline(always)]
6720 fn shade_rounded_pixel_row(
6721 row: &mut [u8],
6722 pos_x: u32,
6723 geom: (f32, f32, f32, f32),
6724 radius: CornerRadius,
6725 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6726 aa: AntialiasingMode,
6727 ) -> usize {
6728 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6729 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6730 style_colors;
6731 let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
6732 let px: f32 = (pos_x as f32) + 0.5 - cx;
6733 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
6734 .min(half_w)
6735 .min(half_h);
6736 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
6737 if dist > 0.85 {
6738 return 0;
6739 }
6740 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6741 let border_width: f32 = if has_border { border.get_width() } else { 0.0 };
6742 if !has_border {
6743 if dist < -0.85 {
6744 if color.get_alpha() > 0 {
6745 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6746 return 1;
6747 }
6748 return 0;
6749 }
6750 let in_corner_edge: bool = aa != AntialiasingMode::None
6751 && corner_r > 0.5
6752 && px.abs() > (half_w - corner_r - 1.5)
6753 && py.abs() > (half_h - corner_r - 1.5);
6754 let outer_cov: f32 = if in_corner_edge {
6755 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
6756 } else {
6757 sdf_coverage(dist, aa)
6758 };
6759 if outer_cov > 0.0 && color.get_alpha() > 0 {
6760 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
6761 blend_row_pixel_f32_precomputed(row, pos_x, color, fill_rgb, alpha_f);
6762 return 1;
6763 }
6764 return 0;
6765 }
6766 if dist < -(border_width + 0.85) {
6767 if color.get_alpha() > 0 {
6768 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6769 return 1;
6770 }
6771 return 0;
6772 }
6773 let inner_hw: f32 = (half_w - border_width).max(0.0);
6774 let inner_hh: f32 = (half_h - border_width).max(0.0);
6775 let inner_r: f32 = (corner_r - border_width).max(0.0);
6776 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6777 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
6778 } else {
6779 2.0
6780 };
6781 if dist < -0.85 && inner_dist > 0.85 {
6782 let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
6783 blend_row_pixel_linear_precomputed(row, pos_x, border.get_color(), border_rgb);
6784 return 1;
6785 }
6786 let in_corner_zone: bool = aa != AntialiasingMode::None
6787 && corner_r > 0.5
6788 && px.abs() > (half_w - corner_r - 1.5)
6789 && py.abs() > (half_h - corner_r - 1.5);
6790 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
6791 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, border_width)
6792 } else {
6793 let oc: f32 = sdf_coverage(dist, aa);
6794 if oc <= 0.0 {
6795 return 0;
6796 }
6797 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6798 sdf_coverage(inner_dist, aa)
6799 } else {
6800 0.0
6801 };
6802 (oc, ic)
6803 };
6804 if outer_cov <= 0.0 {
6805 return 0;
6806 }
6807 let mixed: Color =
6808 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6809 if mixed.get_alpha() > 0 {
6810 let mixed_rgb: [f32; 3] = [
6811 SRGB_TO_LIN_LUT[mixed.get_red() as usize],
6812 SRGB_TO_LIN_LUT[mixed.get_green() as usize],
6813 SRGB_TO_LIN_LUT[mixed.get_blue() as usize],
6814 ];
6815 blend_row_pixel_linear_precomputed(row, pos_x, mixed, mixed_rgb);
6816 return 1;
6817 }
6818 0
6819 }
6820
6821 #[inline(always)]
6834 fn fill_vertical_gradient_span(
6835 band: &mut PixelBand<'_>,
6836 coords: (u32, u32, u32),
6837 sample: Color,
6838 cov: f32,
6839 ) -> usize {
6840 let (sx0, sx1, pos_y): (u32, u32, u32) = coords;
6841 if sx0 >= sx1 || cov <= 0.0 {
6842 return 0;
6843 }
6844 let alpha_f: f32 = ((sample.get_alpha() as f32) * (1.0 / 255.0)) * cov;
6845 if alpha_f >= 0.9995 {
6846 band.fill_span(
6847 sx0,
6848 sx1,
6849 pos_y,
6850 Color::new(sample.get_red(), sample.get_green(), sample.get_blue(), 255),
6851 );
6852 } else if alpha_f > 0.0005 {
6853 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, sample, alpha_f);
6854 } else if alpha_f > 0.0002
6855 && let Some(row) = band.row_slice_mut(pos_y)
6856 {
6857 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
6858 for pos_x in sx0..sx1 {
6859 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6860 }
6861 }
6862 (sx1 - sx0) as usize
6863 }
6864
6865 #[inline(always)]
6878 fn fill_angled_gradient_span(
6879 row: &mut [u8],
6880 coords: (u32, u32, f32),
6881 step: (f32, f32, f32),
6882 stops: (Color, Color),
6883 ) -> usize {
6884 let (sx0, sx1, y_term): (u32, u32, f32) = coords;
6885 let (t_start, dt_dx, cov): (f32, f32, f32) = step;
6886 let (start_c, end_c): (Color, Color) = stops;
6887 if sx0 >= sx1 || cov <= 0.0 {
6888 return 0;
6889 }
6890 let byte_start: usize = (sx0 as usize) * 4;
6891 let byte_end: usize = (sx1 as usize) * 4;
6892 if byte_end > row.len() {
6893 return 0;
6894 }
6895 let sr_f: f32 = start_c.get_red() as f32;
6896 let sg_f: f32 = start_c.get_green() as f32;
6897 let sb_f: f32 = start_c.get_blue() as f32;
6898 let er_f: f32 = end_c.get_red() as f32;
6899 let eg_f: f32 = end_c.get_green() as f32;
6900 let eb_f: f32 = end_c.get_blue() as f32;
6901 let both_opaque: bool = start_c.get_alpha() == 255 && end_c.get_alpha() == 255;
6902 let mut t_cur: f32 = t_start;
6903 if both_opaque && cov >= 0.9995 {
6904 let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
6905 for px in chunks.iter_mut() {
6906 let factor_val: f32 = t_cur.clamp(0.0, 1.0);
6907 let inv: f32 = 1.0 - factor_val;
6908 px[0] = (sr_f * inv + er_f * factor_val + 0.5) as u8;
6909 px[1] = (sg_f * inv + eg_f * factor_val + 0.5) as u8;
6910 px[2] = (sb_f * inv + eb_f * factor_val + 0.5) as u8;
6911 px[3] = 255;
6912 t_cur += dt_dx;
6913 }
6914 return (sx1 - sx0) as usize;
6915 }
6916 let sa_f: f32 = start_c.get_alpha() as f32;
6917 let ea_f: f32 = end_c.get_alpha() as f32;
6918 for pos_x in sx0..sx1 {
6919 let callback_ref: f32 = t_cur.clamp(0.0, 1.0);
6920 let inv: f32 = 1.0 - callback_ref;
6921 let sample: Color = Color::new(
6922 (sr_f * inv + er_f * callback_ref + 0.5) as u8,
6923 (sg_f * inv + eg_f * callback_ref + 0.5) as u8,
6924 (sb_f * inv + eb_f * callback_ref + 0.5) as u8,
6925 (sa_f * inv + ea_f * callback_ref + 0.5) as u8,
6926 );
6927 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6928 t_cur += dt_dx;
6929 }
6930 (sx1 - sx0) as usize
6931 }
6932
6933 fn raster_gradient_rect(
6948 band: &mut PixelBand<'_>,
6949 rect: Rect,
6950 gradient: LinearGradient,
6951 radius: CornerRadius,
6952 clip: Rect,
6953 aa: AntialiasingMode,
6954 ) -> usize {
6955 let Some(vis) = rect.intersect(clip) else {
6956 return 0;
6957 };
6958 let fb_w: u32 = band.width();
6959 let band_y0: u32 = band.y_offset();
6960 let band_y1: u32 = band.y_end();
6961 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6962 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6963 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6964 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6965 if x0 >= x1 || y0 >= y1 {
6966 return 0;
6967 }
6968 let rad: f32 = gradient.get_angle_deg().to_radians();
6969 let dir_x: f32 = rad.sin();
6970 let dir_y: f32 = rad.cos();
6971 let start_c: Color = gradient.get_start_color();
6972 let end_c: Color = gradient.get_end_color();
6973 let half_w: f32 = rect.get_width() * 0.5;
6974 let half_h: f32 = rect.get_height() * 0.5;
6975 let cx: f32 = rect.get_x() + half_w;
6976 let cy: f32 = rect.get_y() + half_h;
6977 let inv_w: f32 = if rect.get_width() > 0.0 {
6978 1.0 / rect.get_width()
6979 } else {
6980 0.0
6981 };
6982 let inv_h: f32 = if rect.get_height() > 0.0 {
6983 1.0 / rect.get_height()
6984 } else {
6985 0.0
6986 };
6987 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
6988 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6989 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6990 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6991 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6992 let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6993 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
6994 let is_vertical: bool = dir_x.abs() < 1e-5;
6995 let dt_dx: f32 = inv_w * dir_x;
6996 let rect_x: f32 = rect.get_x();
6997 let rect_y: f32 = rect.get_y();
6998 let mut shaded: usize = 0;
6999 if is_vertical {
7000 for pos_y in y0..iy0 {
7001 let py: f32 = (pos_y as f32) + 0.5 - cy;
7002 let ny: f32 = ((pos_y as f32) - rect_y) * inv_h;
7003 let blend_factor: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7004 let sample: Color = start_c.lerp(end_c, blend_factor);
7005 let dist_y: f32 = py.abs() - half_h;
7006 let mid_cov: f32 = if dist_y > 0.85 {
7007 0.0
7008 } else if dist_y < -0.85 {
7009 1.0
7010 } else {
7011 sdf_coverage(dist_y, aa)
7012 };
7013 if cx0 < cx1 && mid_cov > 0.0 {
7014 shaded +=
7015 Self::fill_vertical_gradient_span(band, (cx0, cx1, pos_y), sample, mid_cov);
7016 }
7017 if (x0 < cx0 || cx1 < x1)
7018 && let Some(row) = band.row_slice_mut(pos_y)
7019 {
7020 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7021 for pos_x in x0..cx0 {
7022 let px: f32 = (pos_x as f32) + 0.5 - cx;
7023 let cov: f32 =
7024 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7025 if cov > 0.0 {
7026 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
7027 shaded += 1;
7028 }
7029 }
7030 for coord_x in cx1..x1 {
7031 let px: f32 = (coord_x as f32) + 0.5 - cx;
7032 let cov: f32 =
7033 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7034 if cov > 0.0 {
7035 blend_gradient_row_pixel(row, coord_x, y_term, sample, cov);
7036 shaded += 1;
7037 }
7038 }
7039 }
7040 }
7041 for coord_y in iy0..iy1 {
7042 let ny: f32 = ((coord_y as f32) - rect_y) * inv_h;
7043 let time_step: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7044 let sample: Color = start_c.lerp(end_c, time_step);
7045 if ix0 < ix1 {
7046 shaded +=
7047 Self::fill_vertical_gradient_span(band, (ix0, ix1, coord_y), sample, 1.0);
7048 }
7049 if (x0 < ix0 || ix1 < x1)
7050 && let Some(row) = band.row_slice_mut(coord_y)
7051 {
7052 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
7053 for sample_x in x0..ix0 {
7054 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
7055 if dist <= 0.85 {
7056 let cov: f32 = if dist < -0.85 {
7057 1.0
7058 } else {
7059 sdf_coverage(dist, aa)
7060 };
7061 if cov > 0.0 {
7062 blend_gradient_row_pixel(row, sample_x, y_term, sample, cov);
7063 shaded += 1;
7064 }
7065 }
7066 }
7067 for value_x in ix1..x1 {
7068 let dist: f32 = ((value_x as f32) + 0.5 - cx).abs() - half_w;
7069 if dist <= 0.85 {
7070 let cov: f32 = if dist < -0.85 {
7071 1.0
7072 } else {
7073 sdf_coverage(dist, aa)
7074 };
7075 if cov > 0.0 {
7076 blend_gradient_row_pixel(row, value_x, y_term, sample, cov);
7077 shaded += 1;
7078 }
7079 }
7080 }
7081 }
7082 }
7083 for sample_y in iy1..y1 {
7084 let py: f32 = (sample_y as f32) + 0.5 - cy;
7085 let ny: f32 = ((sample_y as f32) - rect_y) * inv_h;
7086 let token_val: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7087 let sample: Color = start_c.lerp(end_c, token_val);
7088 let dist_y: f32 = py.abs() - half_h;
7089 let mid_cov: f32 = if dist_y > 0.85 {
7090 0.0
7091 } else if dist_y < -0.85 {
7092 1.0
7093 } else {
7094 sdf_coverage(dist_y, aa)
7095 };
7096 if cx0 < cx1 && mid_cov > 0.0 {
7097 shaded += Self::fill_vertical_gradient_span(
7098 band,
7099 (cx0, cx1, sample_y),
7100 sample,
7101 mid_cov,
7102 );
7103 }
7104 if (x0 < cx0 || cx1 < x1)
7105 && let Some(row) = band.row_slice_mut(sample_y)
7106 {
7107 let y_term: f32 = (sample_y as f32) * 0.005_837_15;
7108 for pos_x_primary in x0..cx0 {
7109 let px: f32 = (pos_x_primary as f32) + 0.5 - cx;
7110 let cov: f32 =
7111 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7112 if cov > 0.0 {
7113 blend_gradient_row_pixel(row, pos_x_primary, y_term, sample, cov);
7114 shaded += 1;
7115 }
7116 }
7117 for pos_x_secondary in cx1..x1 {
7118 let px: f32 = (pos_x_secondary as f32) + 0.5 - cx;
7119 let cov: f32 =
7120 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7121 if cov > 0.0 {
7122 blend_gradient_row_pixel(row, pos_x_secondary, y_term, sample, cov);
7123 shaded += 1;
7124 }
7125 }
7126 }
7127 }
7128 return shaded;
7129 }
7130 for value_y in y0..iy0 {
7131 let Some(row) = band.row_slice_mut(value_y) else {
7132 continue;
7133 };
7134 let py: f32 = (value_y as f32) + 0.5 - cy;
7135 let ny: f32 = ((value_y as f32) - rect_y) * inv_h;
7136 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7137 let y_term: f32 = (value_y as f32) * 0.005_837_15;
7138 let dist_y: f32 = py.abs() - half_h;
7139 let mid_cov: f32 = if dist_y > 0.85 {
7140 0.0
7141 } else if dist_y < -0.85 {
7142 1.0
7143 } else {
7144 sdf_coverage(dist_y, aa)
7145 };
7146 if cx0 < cx1 && mid_cov > 0.0 {
7147 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7148 shaded += Self::fill_angled_gradient_span(
7149 row,
7150 (cx0, cx1, y_term),
7151 (t_start, dt_dx, mid_cov),
7152 (start_c, end_c),
7153 );
7154 }
7155 for pos_x_next in x0..cx0 {
7156 let px: f32 = (pos_x_next as f32) + 0.5 - cx;
7157 let cov: f32 =
7158 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7159 if cov > 0.0 {
7160 let nx: f32 = ((pos_x_next as f32) - rect_x) * inv_w;
7161 let target_val: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7162 blend_gradient_row_pixel(
7163 row,
7164 pos_x_next,
7165 y_term,
7166 start_c.lerp(end_c, target_val),
7167 cov,
7168 );
7169 shaded += 1;
7170 }
7171 }
7172 for pos_x_alt in cx1..x1 {
7173 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
7174 let cov: f32 =
7175 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7176 if cov > 0.0 {
7177 let nx: f32 = ((pos_x_alt as f32) - rect_x) * inv_w;
7178 let blend_factor_primary: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7179 blend_gradient_row_pixel(
7180 row,
7181 pos_x_alt,
7182 y_term,
7183 start_c.lerp(end_c, blend_factor_primary),
7184 cov,
7185 );
7186 shaded += 1;
7187 }
7188 }
7189 }
7190 for pos_y_primary in iy0..iy1 {
7191 let Some(row) = band.row_slice_mut(pos_y_primary) else {
7192 continue;
7193 };
7194 let ny: f32 = ((pos_y_primary as f32) - rect_y) * inv_h;
7195 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7196 let y_term: f32 = (pos_y_primary as f32) * 0.005_837_15;
7197 if ix0 < ix1 {
7198 let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7199 shaded += Self::fill_angled_gradient_span(
7200 row,
7201 (ix0, ix1, y_term),
7202 (t_start, dt_dx, 1.0),
7203 (start_c, end_c),
7204 );
7205 }
7206 for pos_x_inner in x0..ix0 {
7207 let dist: f32 = ((pos_x_inner as f32) + 0.5 - cx).abs() - half_w;
7208 if dist <= 0.85 {
7209 let cov: f32 = if dist < -0.85 {
7210 1.0
7211 } else {
7212 sdf_coverage(dist, aa)
7213 };
7214 if cov > 0.0 {
7215 let nx: f32 = ((pos_x_inner as f32) - rect_x) * inv_w;
7216 let blend_factor_secondary: f32 =
7217 ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7218 blend_gradient_row_pixel(
7219 row,
7220 pos_x_inner,
7221 y_term,
7222 start_c.lerp(end_c, blend_factor_secondary),
7223 cov,
7224 );
7225 shaded += 1;
7226 }
7227 }
7228 }
7229 for pos_x_local in ix1..x1 {
7230 let dist: f32 = ((pos_x_local as f32) + 0.5 - cx).abs() - half_w;
7231 if dist <= 0.85 {
7232 let cov: f32 = if dist < -0.85 {
7233 1.0
7234 } else {
7235 sdf_coverage(dist, aa)
7236 };
7237 if cov > 0.0 {
7238 let nx: f32 = ((pos_x_local as f32) - rect_x) * inv_w;
7239 let blend_factor_next: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7240 blend_gradient_row_pixel(
7241 row,
7242 pos_x_local,
7243 y_term,
7244 start_c.lerp(end_c, blend_factor_next),
7245 cov,
7246 );
7247 shaded += 1;
7248 }
7249 }
7250 }
7251 }
7252 for pos_y_secondary in iy1..y1 {
7253 let Some(row) = band.row_slice_mut(pos_y_secondary) else {
7254 continue;
7255 };
7256 let py: f32 = (pos_y_secondary as f32) + 0.5 - cy;
7257 let ny: f32 = ((pos_y_secondary as f32) - rect_y) * inv_h;
7258 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7259 let y_term: f32 = (pos_y_secondary as f32) * 0.005_837_15;
7260 let dist_y: f32 = py.abs() - half_h;
7261 let mid_cov: f32 = if dist_y > 0.85 {
7262 0.0
7263 } else if dist_y < -0.85 {
7264 1.0
7265 } else {
7266 sdf_coverage(dist_y, aa)
7267 };
7268 if cx0 < cx1 && mid_cov > 0.0 {
7269 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7270 shaded += Self::fill_angled_gradient_span(
7271 row,
7272 (cx0, cx1, y_term),
7273 (t_start, dt_dx, mid_cov),
7274 (start_c, end_c),
7275 );
7276 }
7277 for pos_x_cur in x0..cx0 {
7278 let px: f32 = (pos_x_cur as f32) + 0.5 - cx;
7279 let cov: f32 =
7280 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7281 if cov > 0.0 {
7282 let nx: f32 = ((pos_x_cur as f32) - rect_x) * inv_w;
7283 let blend_factor_alt: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7284 blend_gradient_row_pixel(
7285 row,
7286 pos_x_cur,
7287 y_term,
7288 start_c.lerp(end_c, blend_factor_alt),
7289 cov,
7290 );
7291 shaded += 1;
7292 }
7293 }
7294 for pos_x_slot in cx1..x1 {
7295 let px: f32 = (pos_x_slot as f32) + 0.5 - cx;
7296 let cov: f32 =
7297 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7298 if cov > 0.0 {
7299 let nx: f32 = ((pos_x_slot as f32) - rect_x) * inv_w;
7300 let blend_factor_inner: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7301 blend_gradient_row_pixel(
7302 row,
7303 pos_x_slot,
7304 y_term,
7305 start_c.lerp(end_c, blend_factor_inner),
7306 cov,
7307 );
7308 shaded += 1;
7309 }
7310 }
7311 }
7312 shaded
7313 }
7314
7315 #[must_use]
7328 fn shadow_row_cutout(pos_y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
7329 let (cut_h, cut_v): (Rect, Rect) = cutouts;
7330 let yf: f32 = (pos_y as f32) + 0.5;
7331 if cut_h.get_width() > 0.0
7332 && cut_h.get_height() > 0.0
7333 && yf >= cut_h.get_y()
7334 && yf < cut_h.bottom()
7335 {
7336 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7337 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
7338 return (cx0, cx1);
7339 }
7340 if cut_v.get_width() > 0.0
7341 && cut_v.get_height() > 0.0
7342 && yf >= cut_v.get_y()
7343 && yf < cut_v.bottom()
7344 {
7345 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7346 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
7347 return (cx0, cx1);
7348 }
7349 (x1, x1)
7350 }
7351
7352 #[inline(always)]
7366 fn raster_shadow_middle_span(
7367 band: &mut PixelBand<'_>,
7368 ctx: &ShadowRenderContext,
7369 pos_y: u32,
7370 cutout: (u32, u32),
7371 mid_alpha: f32,
7372 ) -> usize {
7373 if !ctx.has_mid_x || mid_alpha <= 0.0005 {
7374 return 0;
7375 }
7376 let (cut0, cut1): (u32, u32) = cutout;
7377 let sx0: u32 = ctx.lx1;
7378 let sx1: u32 = ctx.rx0;
7379 let mut shaded: usize = 0;
7380 if cut0 < cut1 {
7381 let m0_end: u32 = cut0.min(sx1);
7382 if sx0 < m0_end {
7383 band.blend_shadow_span_const_alpha(sx0, m0_end, pos_y, ctx.color, mid_alpha);
7384 shaded += (m0_end - sx0) as usize;
7385 }
7386 let m1_start: u32 = cut1.max(sx0);
7387 if m1_start < sx1 {
7388 band.blend_shadow_span_const_alpha(m1_start, sx1, pos_y, ctx.color, mid_alpha);
7389 shaded += (sx1 - m1_start) as usize;
7390 }
7391 } else {
7392 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, ctx.color, mid_alpha);
7393 shaded += (sx1 - sx0) as usize;
7394 }
7395 shaded
7396 }
7397
7398 fn raster_shadow_corner_row_symmetric(
7411 band: &mut PixelBand<'_>,
7412 ctx: &ShadowRenderContext,
7413 pos_y: u32,
7414 cutouts: (Rect, Rect),
7415 ) -> usize {
7416 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7417 let py_abs: f32 = py.abs();
7418 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7419 let mut shaded: usize = 0;
7420 if ctx.has_mid_x {
7421 let dist_y: f32 = py_abs - ctx.half_h;
7422 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7423 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7424 } else {
7425 0.0
7426 };
7427 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7428 }
7429 let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
7430 let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
7431 let mut u0: i32 = i32::MAX;
7432 let mut u1: i32 = i32::MIN;
7433 if la0 < la1 {
7434 u0 = u0.min(la0 as i32);
7435 u1 = u1.max(la1 as i32);
7436 }
7437 if ra0 < ra1 {
7438 u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
7439 u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
7440 }
7441 if u0 >= u1 {
7442 return shaded;
7443 }
7444 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7445 let qy_pos: f32 = qy.max(0.0);
7446 let qy_pos_sq: f32 = qy_pos * qy_pos;
7447 if qy > 0.0 {
7448 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7449 return shaded;
7450 }
7451 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7452 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7453 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7454 u0 = u0.max(tight_u0);
7455 if u0 >= u1 {
7456 return shaded;
7457 }
7458 }
7459 let Some(row) = band.row_slice_mut(pos_y) else {
7460 return shaded;
7461 };
7462 let sdf_geom: (f32, f32, f32, f32) =
7463 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7464 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7465 let x0_i: i32 = ctx.x0 as i32;
7466 let lx1_i: i32 = ctx.lx1 as i32;
7467 let rx0_i: i32 = ctx.rx0 as i32;
7468 let x1_i: i32 = ctx.x1 as i32;
7469 let cut0_i: i32 = cut0 as i32;
7470 let cut1_i: i32 = cut1 as i32;
7471 for xl_i in u0..u1 {
7472 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7473 let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
7474 let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
7475 if !do_l && !do_r {
7476 continue;
7477 }
7478 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7479 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7480 if dist >= ctx.cutoff {
7481 continue;
7482 }
7483 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7484 if alpha_f <= 0.0005 {
7485 continue;
7486 }
7487 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7488 if alpha_val >= 0.9995 {
7489 if do_l {
7490 let off: usize = (xl_i as usize) * 4;
7491 row[off] = ctx.color_rgb[0];
7492 row[off + 1] = ctx.color_rgb[1];
7493 row[off + 2] = ctx.color_rgb[2];
7494 row[off + 3] = 255;
7495 shaded += 1;
7496 }
7497 if do_r {
7498 let off: usize = (xr_i as usize) * 4;
7499 row[off] = ctx.color_rgb[0];
7500 row[off + 1] = ctx.color_rgb[1];
7501 row[off + 2] = ctx.color_rgb[2];
7502 row[off + 3] = 255;
7503 shaded += 1;
7504 }
7505 } else {
7506 let inv_a: f32 = 1.0 - alpha_val;
7507 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7508 let params: ShadowStripParams = ShadowStripParams {
7509 sr_a: ctx.lin_rgb[0] * alpha_val,
7510 sg_a: ctx.lin_rgb[1] * alpha_val,
7511 sb_a: ctx.lin_rgb[2] * alpha_val,
7512 inv_a,
7513 sa_u32,
7514 inv_a_u32: 255 - sa_u32,
7515 };
7516 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7517 if do_l {
7518 blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
7519 shaded += 1;
7520 }
7521 if do_r {
7522 blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
7523 shaded += 1;
7524 }
7525 }
7526 }
7527 shaded
7528 }
7529
7530 fn raster_shadow_corner_pair_symmetric(
7544 band: &mut PixelBand<'_>,
7545 ctx: &ShadowRenderContext,
7546 y_t: u32,
7547 y_b: u32,
7548 cutouts: (Rect, Rect),
7549 ) -> usize {
7550 let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
7551 let py_abs: f32 = py.abs();
7552 let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
7553 let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
7554 let mut shaded: usize = 0;
7555 if ctx.has_mid_x {
7556 let dist_y: f32 = py_abs - ctx.half_h;
7557 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7558 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7559 } else {
7560 0.0
7561 };
7562 if mid_alpha > 0.0005 {
7563 shaded +=
7564 Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
7565 shaded +=
7566 Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
7567 }
7568 }
7569 let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
7570 let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
7571 let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
7572 let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
7573 let mut u0: i32 = i32::MAX;
7574 let mut u1: i32 = i32::MIN;
7575 if lat0 < lat1 {
7576 u0 = u0.min(lat0 as i32);
7577 u1 = u1.max(lat1 as i32);
7578 }
7579 if rat0 < rat1 {
7580 u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
7581 u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
7582 }
7583 if lab0 < lab1 {
7584 u0 = u0.min(lab0 as i32);
7585 u1 = u1.max(lab1 as i32);
7586 }
7587 if rab0 < rab1 {
7588 u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
7589 u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
7590 }
7591 if u0 >= u1 {
7592 return shaded;
7593 }
7594 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7595 let qy_pos: f32 = qy.max(0.0);
7596 let qy_pos_sq: f32 = qy_pos * qy_pos;
7597 if qy > 0.0 {
7598 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7599 return shaded;
7600 }
7601 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7602 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7603 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7604 u0 = u0.max(tight_u0);
7605 if u0 >= u1 {
7606 return shaded;
7607 }
7608 }
7609 let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
7610 return shaded;
7611 };
7612 let sdf_geom: (f32, f32, f32, f32) =
7613 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7614 let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
7615 let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
7616 let x0_i: i32 = ctx.x0 as i32;
7617 let lx1_i: i32 = ctx.lx1 as i32;
7618 let rx0_i: i32 = ctx.rx0 as i32;
7619 let x1_i: i32 = ctx.x1 as i32;
7620 let cut0_ti: i32 = cut0_t as i32;
7621 let cut1_ti: i32 = cut1_t as i32;
7622 let cut0_bi: i32 = cut0_b as i32;
7623 let cut1_bi: i32 = cut1_b as i32;
7624 for xl_i in u0..u1 {
7625 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7626 let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
7627 let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
7628 let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
7629 let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
7630 let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
7631 let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
7632 if !do_lt && !do_rt && !do_lb && !do_rb {
7633 continue;
7634 }
7635 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7636 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7637 if dist >= ctx.cutoff {
7638 continue;
7639 }
7640 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7641 if alpha_f <= 0.0005 {
7642 continue;
7643 }
7644 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7645 if alpha_val >= 0.9995 {
7646 if do_lt {
7647 let off: usize = (xl_i as usize) * 4;
7648 row_t[off] = ctx.color_rgb[0];
7649 row_t[off + 1] = ctx.color_rgb[1];
7650 row_t[off + 2] = ctx.color_rgb[2];
7651 row_t[off + 3] = 255;
7652 shaded += 1;
7653 }
7654 if do_rt {
7655 let off: usize = (xr_i as usize) * 4;
7656 row_t[off] = ctx.color_rgb[0];
7657 row_t[off + 1] = ctx.color_rgb[1];
7658 row_t[off + 2] = ctx.color_rgb[2];
7659 row_t[off + 3] = 255;
7660 shaded += 1;
7661 }
7662 if do_lb {
7663 let off: usize = (xl_i as usize) * 4;
7664 row_b[off] = ctx.color_rgb[0];
7665 row_b[off + 1] = ctx.color_rgb[1];
7666 row_b[off + 2] = ctx.color_rgb[2];
7667 row_b[off + 3] = 255;
7668 shaded += 1;
7669 }
7670 if do_rb {
7671 let off: usize = (xr_i as usize) * 4;
7672 row_b[off] = ctx.color_rgb[0];
7673 row_b[off + 1] = ctx.color_rgb[1];
7674 row_b[off + 2] = ctx.color_rgb[2];
7675 row_b[off + 3] = 255;
7676 shaded += 1;
7677 }
7678 } else {
7679 let inv_a: f32 = 1.0 - alpha_val;
7680 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7681 let params: ShadowStripParams = ShadowStripParams {
7682 sr_a: ctx.lin_rgb[0] * alpha_val,
7683 sg_a: ctx.lin_rgb[1] * alpha_val,
7684 sb_a: ctx.lin_rgb[2] * alpha_val,
7685 inv_a,
7686 sa_u32,
7687 inv_a_u32: 255 - sa_u32,
7688 };
7689 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7690 if do_lt {
7691 blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
7692 shaded += 1;
7693 }
7694 if do_rt {
7695 blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
7696 shaded += 1;
7697 }
7698 if do_lb {
7699 blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
7700 shaded += 1;
7701 }
7702 if do_rb {
7703 blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
7704 shaded += 1;
7705 }
7706 }
7707 }
7708 shaded
7709 }
7710
7711 fn raster_shadow_corner_row_general(
7725 band: &mut PixelBand<'_>,
7726 ctx: &ShadowRenderContext,
7727 radius: CornerRadius,
7728 pos_y: u32,
7729 cutouts: (Rect, Rect),
7730 ) -> usize {
7731 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7732 let py_abs: f32 = py.abs();
7733 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7734 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7735 [(ctx.x0, cut0), (cut1, ctx.x1)]
7736 } else {
7737 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7738 };
7739 let mut shaded: usize = 0;
7740 if ctx.has_mid_x {
7741 let dist_y: f32 = py_abs - ctx.half_h;
7742 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7743 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7744 } else {
7745 0.0
7746 };
7747 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7748 }
7749 let Some(row) = band.row_slice_mut(pos_y) else {
7750 return shaded;
7751 };
7752 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7753 let r_l: f32 = (if py < 0.0 {
7754 radius.get_top_left()
7755 } else {
7756 radius.get_bottom_left()
7757 })
7758 .min(ctx.half_w)
7759 .min(ctx.half_h)
7760 .max(0.0);
7761 let r_r: f32 = (if py < 0.0 {
7762 radius.get_top_right()
7763 } else {
7764 radius.get_bottom_right()
7765 })
7766 .min(ctx.half_w)
7767 .min(ctx.half_h)
7768 .max(0.0);
7769 let qy_l: f32 = py_abs - ctx.half_h + r_l;
7770 let qy_l_pos: f32 = qy_l.max(0.0);
7771 let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
7772 let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
7773 let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
7774 let qy_r: f32 = py_abs - ctx.half_h + r_r;
7775 let qy_r_pos: f32 = qy_r.max(0.0);
7776 let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
7777 let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
7778 let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
7779 for (rx0, rx1) in spans.into_iter() {
7780 if rx0 >= rx1 {
7781 continue;
7782 }
7783 if ctx.has_mid_x {
7784 let l_end: u32 = rx1.min(ctx.lx1);
7785 for pos_x in rx0..l_end {
7786 let px: f32 = (pos_x as f32) + 0.5 - ctx.cx;
7787 let dist: f32 = if px < 0.0 {
7788 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7789 } else {
7790 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7791 };
7792 if dist < ctx.cutoff {
7793 let alpha_f: f32 =
7794 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7795 if alpha_f > 0.0005 {
7796 blend_shadow_row_pixel(
7797 row,
7798 pos_x,
7799 y_term,
7800 ctx.color_rgb,
7801 ctx.lin_rgb,
7802 alpha_f,
7803 );
7804 shaded += 1;
7805 }
7806 }
7807 }
7808 let r_start: u32 = rx0.max(ctx.rx0);
7809 for coord_x in r_start..rx1 {
7810 let px: f32 = (coord_x as f32) + 0.5 - ctx.cx;
7811 let dist: f32 = if px < 0.0 {
7812 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7813 } else {
7814 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7815 };
7816 if dist < ctx.cutoff {
7817 let alpha_f: f32 =
7818 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7819 if alpha_f > 0.0005 {
7820 blend_shadow_row_pixel(
7821 row,
7822 coord_x,
7823 y_term,
7824 ctx.color_rgb,
7825 ctx.lin_rgb,
7826 alpha_f,
7827 );
7828 shaded += 1;
7829 }
7830 }
7831 }
7832 } else {
7833 for sample_x in rx0..rx1 {
7834 let px: f32 = (sample_x as f32) + 0.5 - ctx.cx;
7835 let dist: f32 = if px < 0.0 {
7836 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7837 } else {
7838 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7839 };
7840 if dist >= ctx.cutoff {
7841 continue;
7842 }
7843 let alpha_f: f32 =
7844 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7845 if alpha_f > 0.0005 {
7846 blend_shadow_row_pixel(
7847 row,
7848 sample_x,
7849 y_term,
7850 ctx.color_rgb,
7851 ctx.lin_rgb,
7852 alpha_f,
7853 );
7854 shaded += 1;
7855 }
7856 }
7857 }
7858 }
7859 shaded
7860 }
7861
7862 fn raster_shadow_vertical_strips(
7875 band: &mut PixelBand<'_>,
7876 ctx: &ShadowRenderContext,
7877 y_span: (u32, u32),
7878 cutouts: (Rect, Rect),
7879 ) -> usize {
7880 let (sy0, sy1): (u32, u32) = y_span;
7881 if sy0 >= sy1 {
7882 return 0;
7883 }
7884 let (cut_h, _): (Rect, Rect) = cutouts;
7885 let sy0_f: f32 = (sy0 as f32) + 0.5;
7886 let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
7887 let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
7888 && cut_h.get_height() > 0.0
7889 && sy0_f >= cut_h.get_y()
7890 && sy1_last_f < cut_h.bottom()
7891 {
7892 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
7893 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
7894 Some((cx0, cx1))
7895 } else {
7896 None
7897 };
7898 let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7899 active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
7900 } else {
7901 (ctx.x0, ctx.lx1)
7902 };
7903 let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7904 active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
7905 } else {
7906 (ctx.rx0, ctx.x1)
7907 };
7908 let mut shaded: usize = 0;
7909 let ran_tls: bool = BAND_SHADOW_SCRATCH
7910 .try_with(|cell: &RefCell<BandShadowScratch>| {
7911 if let Ok(mut scratch) = cell.try_borrow_mut() {
7912 let BandShadowScratch {
7913 left_hot,
7914 left_params,
7915 right_hot,
7916 right_params,
7917 } = &mut *scratch;
7918 let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
7919 (l_build0, l_build1),
7920 ctx,
7921 left_hot,
7922 left_params,
7923 );
7924 let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
7925 (r_build0, r_build1),
7926 ctx,
7927 right_hot,
7928 right_params,
7929 );
7930 if l_act0 >= l_act1 && r_act0 >= r_act1 {
7931 return;
7932 }
7933 let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
7934 let l_par_s: &[ShadowStripParams] = left_params.as_slice();
7935 let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
7936 let r_par_s: &[ShadowStripParams] = right_params.as_slice();
7937 for pos_y in sy0..sy1 {
7938 let Some(row) = band.row_slice_mut(pos_y) else {
7939 continue;
7940 };
7941 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7942 let (cut0, cut1): (u32, u32) = const_cut.unwrap_or_else(|| {
7943 Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1)
7944 });
7945 if l_act0 < l_act1 {
7946 if cut0 < cut1 {
7947 let a_end: u32 = cut0.min(l_act1);
7948 if l_act0 < a_end {
7949 shaded += apply_shadow_strip_span(
7950 row,
7951 (l_act0, a_end, l_act0),
7952 y_term,
7953 ctx.color_rgb,
7954 l_hot_s,
7955 l_par_s,
7956 );
7957 }
7958 let b_start: u32 = cut1.max(l_act0);
7959 if b_start < l_act1 {
7960 shaded += apply_shadow_strip_span(
7961 row,
7962 (b_start, l_act1, l_act0),
7963 y_term,
7964 ctx.color_rgb,
7965 l_hot_s,
7966 l_par_s,
7967 );
7968 }
7969 } else {
7970 shaded += apply_shadow_strip_span(
7971 row,
7972 (l_act0, l_act1, l_act0),
7973 y_term,
7974 ctx.color_rgb,
7975 l_hot_s,
7976 l_par_s,
7977 );
7978 }
7979 }
7980 if r_act0 < r_act1 {
7981 if cut0 < cut1 {
7982 let a_end: u32 = cut0.min(r_act1);
7983 if r_act0 < a_end {
7984 shaded += apply_shadow_strip_span(
7985 row,
7986 (r_act0, a_end, r_act0),
7987 y_term,
7988 ctx.color_rgb,
7989 r_hot_s,
7990 r_par_s,
7991 );
7992 }
7993 let b_start: u32 = cut1.max(r_act0);
7994 if b_start < r_act1 {
7995 shaded += apply_shadow_strip_span(
7996 row,
7997 (b_start, r_act1, r_act0),
7998 y_term,
7999 ctx.color_rgb,
8000 r_hot_s,
8001 r_par_s,
8002 );
8003 }
8004 } else {
8005 shaded += apply_shadow_strip_span(
8006 row,
8007 (r_act0, r_act1, r_act0),
8008 y_term,
8009 ctx.color_rgb,
8010 r_hot_s,
8011 r_par_s,
8012 );
8013 }
8014 }
8015 }
8016 }
8017 })
8018 .is_ok();
8019 if !ran_tls {
8020 for coord_y in sy0..sy1 {
8021 let Some(row) = band.row_slice_mut(coord_y) else {
8022 continue;
8023 };
8024 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
8025 let (cut0, cut1): (u32, u32) = const_cut
8026 .unwrap_or_else(|| Self::shadow_row_cutout(coord_y, cutouts, ctx.x0, ctx.x1));
8027 let spans: [(u32, u32); 2] = if cut0 < cut1 {
8028 [(ctx.x0, cut0), (cut1, ctx.x1)]
8029 } else {
8030 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
8031 };
8032 for (rx0, rx1) in spans.into_iter() {
8033 let left_end: u32 = rx1.min(ctx.lx1);
8034 for pos_x in rx0..left_end {
8035 let dist: f32 = ((pos_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
8036 if dist < ctx.cutoff {
8037 let alpha_f: f32 =
8038 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
8039 if alpha_f > 0.0005 {
8040 blend_shadow_row_pixel(
8041 row,
8042 pos_x,
8043 y_term,
8044 ctx.color_rgb,
8045 ctx.lin_rgb,
8046 alpha_f,
8047 );
8048 shaded += 1;
8049 }
8050 }
8051 }
8052 let right_start: u32 = rx0.max(ctx.rx0);
8053 for coord_x in right_start..rx1 {
8054 let dist: f32 = ((coord_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
8055 if dist < ctx.cutoff {
8056 let alpha_f: f32 =
8057 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
8058 if alpha_f > 0.0005 {
8059 blend_shadow_row_pixel(
8060 row,
8061 coord_x,
8062 y_term,
8063 ctx.color_rgb,
8064 ctx.lin_rgb,
8065 alpha_f,
8066 );
8067 shaded += 1;
8068 }
8069 }
8070 }
8071 }
8072 }
8073 }
8074 shaded
8075 }
8076
8077 fn raster_shadow(
8092 band: &mut PixelBand<'_>,
8093 rects: (Rect, Rect, Rect),
8094 radius: CornerRadius,
8095 sigma: f32,
8096 color: Color,
8097 cutouts: (Rect, Rect),
8098 ) -> usize {
8099 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
8100 if color.get_alpha() == 0 {
8101 return 0;
8102 }
8103 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
8104 if base_alpha <= 0.0005 {
8105 return 0;
8106 }
8107 let Some(vis) = shadow_rect.intersect(clip) else {
8108 return 0;
8109 };
8110 let fb_w: u32 = band.width();
8111 let band_y0: u32 = band.y_offset();
8112 let band_y1: u32 = band.y_end();
8113 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
8114 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
8115 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
8116 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
8117 if x0 >= x1 || y0 >= y1 {
8118 return 0;
8119 }
8120 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
8121 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
8122 let cx: f32 = caster_rect.get_x() + half_w;
8123 let cy: f32 = caster_rect.get_y() + half_h;
8124 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
8125 let cutoff: f32 = sigma * 3.0;
8126 let r_max: f32 = radius.max_radius();
8127 let inner_inset: f32 = cutoff + r_max;
8128 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
8129 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
8130 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
8131 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
8132 let has_mid_x: bool = sx0 < sx1;
8133 let has_mid_y: bool = sy0 < sy1;
8134 let r_tl: f32 = radius.get_top_left();
8135 let uniform_radius: bool = r_tl == radius.get_top_right()
8136 && r_tl == radius.get_bottom_right()
8137 && r_tl == radius.get_bottom_left();
8138 let two_cx_f: f32 = 2.0 * cx;
8139 let two_cx_i: i32 = two_cx_f.round() as i32;
8140 let x_symmetric: bool =
8141 uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
8142 let two_cy_f: f32 = 2.0 * cy;
8143 let two_cy_i: i32 = two_cy_f.round() as i32;
8144 let y_symmetric: bool =
8145 x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
8146 let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
8147 let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
8148 let (lx1, rx0): (u32, u32) = if has_mid_x {
8149 (sx0, sx1)
8150 } else if x_symmetric {
8151 let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
8152 (split_x, split_x)
8153 } else {
8154 (x1, x1)
8155 };
8156 let color_rgb: [u8; 3] = [color.get_red(), color.get_green(), color.get_blue()];
8157 let lin_rgb: [f32; 3] = [
8158 SRGB_TO_LIN_LUT[color_rgb[0] as usize],
8159 SRGB_TO_LIN_LUT[color_rgb[1] as usize],
8160 SRGB_TO_LIN_LUT[color_rgb[2] as usize],
8161 ];
8162 let ctx: ShadowRenderContext = ShadowRenderContext {
8163 color,
8164 color_rgb,
8165 lin_rgb,
8166 cx,
8167 cy,
8168 half_w,
8169 half_h,
8170 base_alpha,
8171 inv_sigma,
8172 cutoff,
8173 uniform_r,
8174 cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
8175 x0,
8176 x1,
8177 lx1,
8178 rx0,
8179 mirror_x_sum: two_cx_i - 1,
8180 has_mid_x,
8181 };
8182 let mut shaded: usize = 0;
8183 if x_symmetric {
8184 let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
8185 (sy0, sy1)
8186 } else if y_symmetric {
8187 let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
8188 (split_y, split_y)
8189 } else {
8190 (y1, y1)
8191 };
8192 let mirror_y_sum: i32 = two_cy_i - 1;
8193 let mut mirrored_b0: u32 = y1;
8194 let mut mirrored_b1: u32 = bot_start;
8195 for y_t in y0..top_end {
8196 let y_b_i: i32 = if y_symmetric {
8197 mirror_y_sum - (y_t as i32)
8198 } else {
8199 -1
8200 };
8201 if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
8202 let y_b: u32 = y_b_i as u32;
8203 mirrored_b0 = mirrored_b0.min(y_b);
8204 mirrored_b1 = mirrored_b1.max(y_b + 1);
8205 shaded +=
8206 Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
8207 } else {
8208 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
8209 }
8210 }
8211 if has_mid_x && has_mid_y {
8212 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8213 }
8214 if mirrored_b0 < mirrored_b1 {
8215 for y_b in bot_start..mirrored_b0 {
8216 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8217 }
8218 for y_b in mirrored_b1..y1 {
8219 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8220 }
8221 } else {
8222 for y_b in bot_start..y1 {
8223 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8224 }
8225 }
8226 } else if has_mid_x && has_mid_y {
8227 for pos_y in y0..sy0 {
8228 shaded +=
8229 Self::raster_shadow_corner_row_general(band, &ctx, radius, pos_y, cutouts);
8230 }
8231 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8232 for coord_y in sy1..y1 {
8233 shaded +=
8234 Self::raster_shadow_corner_row_general(band, &ctx, radius, coord_y, cutouts);
8235 }
8236 } else {
8237 for sample_y in y0..y1 {
8238 shaded +=
8239 Self::raster_shadow_corner_row_general(band, &ctx, radius, sample_y, cutouts);
8240 }
8241 }
8242 shaded
8243 }
8244
8245 fn raster_text_run_band(
8259 band: &mut PixelBand<'_>,
8260 positioned_glyphs: &[PositionedGlyph],
8261 color: Color,
8262 clip: Rect,
8263 glyph_atlas: &GlyphAtlas,
8264 ) -> usize {
8265 let fb_w: i32 = band.width() as i32;
8266 let band_y0: i32 = band.y_offset() as i32;
8267 let band_y1: i32 = band.y_end() as i32;
8268 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
8269 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
8270 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
8271 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
8272 if color.get_alpha() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
8273 return 0;
8274 }
8275 let mut shaded: usize = 0;
8276 for pg in positioned_glyphs.iter() {
8277 let gy0: i32 = pg.get_y();
8278 let gh: i32 = pg.get_height() as i32;
8279 if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
8280 continue;
8281 }
8282 let gx0: i32 = pg.get_x();
8283 let gw: i32 = pg.get_width() as i32;
8284 if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
8285 continue;
8286 }
8287 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.get_glyph_idx());
8288 let py_start: i32 = (clip_y0 - gy0).max(0);
8289 let py_end: i32 = (clip_y1 - gy0).min(gh);
8290 let px_start: i32 = (clip_x0 - gx0).max(0);
8291 let px_end: i32 = (clip_x1 - gx0).min(gw);
8292 if py_start < py_end && px_start < px_end {
8293 let dy0: u32 = (gy0 + py_start) as u32;
8294 let dy1: u32 = (gy0 + py_end) as u32;
8295 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
8296 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
8297 let gw_usize: usize = gw as usize;
8298 let bx0: usize = ((gx0 + px_start) as usize) * 4;
8299 let bx1: usize = ((gx0 + px_end) as usize) * 4;
8300 let start_u: usize = px_start as usize;
8301 let end_u: usize = px_end as usize;
8302 let mut cov_off: usize = (py_start as usize) * gw_usize;
8303 for row in rows_buf.chunks_exact_mut(row_stride) {
8304 let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
8305 shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
8306 cov_off += gw_usize;
8307 }
8308 }
8309 }
8310 }
8311 shaded
8312 }
8313
8314 #[inline(always)]
8323 fn blit_opaque_horiz_packed_u32(
8324 vrow: &[u32],
8325 dst_x0: usize,
8326 x_packed: &[u32],
8327 dst_row: &mut [u8],
8328 ) {
8329 let len: usize = x_packed.len();
8330 let span_bytes_start: usize = dst_x0 * 4;
8331 let span_bytes_end: usize = (dst_x0 + len) * 4;
8332 if span_bytes_end > dst_row.len() || vrow.len() < 2 {
8333 return;
8334 }
8335 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8336 .as_chunks_mut::<4>()
8337 .0;
8338 let vptr: *const u32 = vrow.as_ptr();
8339 let dptr: *mut [u8; 4] = dst_chunks.as_mut_ptr();
8340 let lptr: *const u32 = x_packed.as_ptr();
8341 let mut item_index: usize = 0;
8342 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8343 {
8344 let v256: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(256);
8345 let v128_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8346 let alpha_mask: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0xFF00_0000);
8347 while item_index + 2 <= len {
8348 unsafe {
8350 let e0: u32 = *lptr.add(item_index);
8351 let e1: u32 = *lptr.add(item_index + 1);
8352 let sx_a: usize = (e0 >> 9) as usize;
8353 let wx_a: u16 = (e0 & 0x1FF) as u16;
8354 let sx_b: usize = (e1 >> 9) as usize;
8355 let wx_b: u16 = (e1 & 0x1FF) as u16;
8356 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8357 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8358 let p0_u32: core::arch::wasm32::v128 =
8359 core::arch::wasm32::u32x4(pair_a as u32, pair_b as u32, 0, 0);
8360 let p1_u32: core::arch::wasm32::v128 = core::arch::wasm32::u32x4(
8361 (pair_a >> 32) as u32,
8362 (pair_b >> 32) as u32,
8363 0,
8364 0,
8365 );
8366 let p0_16: core::arch::wasm32::v128 =
8367 core::arch::wasm32::u16x8_extend_low_u8x16(p0_u32);
8368 let p1_16: core::arch::wasm32::v128 =
8369 core::arch::wasm32::u16x8_extend_low_u8x16(p1_u32);
8370 let wx_v: core::arch::wasm32::v128 =
8371 core::arch::wasm32::u16x8(wx_a, wx_a, wx_a, wx_a, wx_b, wx_b, wx_b, wx_b);
8372 let iwx_v: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_sub(v256, wx_v);
8373 let sum: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_add(
8374 core::arch::wasm32::i16x8_add(
8375 core::arch::wasm32::i16x8_mul(p0_16, iwx_v),
8376 core::arch::wasm32::i16x8_mul(p1_16, wx_v),
8377 ),
8378 v128_round,
8379 );
8380 let shr: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(sum, 8);
8381 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8382 core::arch::wasm32::u8x16_narrow_i16x8(shr, shr),
8383 alpha_mask,
8384 );
8385 core::arch::wasm32::v128_store64_lane::<0>(
8386 packed,
8387 dptr.add(item_index).cast::<u64>(),
8388 );
8389 }
8390 item_index += 2;
8391 }
8392 }
8393 #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8394 while item_index + 2 <= len {
8395 unsafe {
8397 let e0: u32 = *lptr.add(item_index);
8398 let e1: u32 = *lptr.add(item_index + 1);
8399 let sx_a: usize = (e0 >> 9) as usize;
8400 let wx_a: u32 = e0 & 0x1FF;
8401 let iwx_a: u32 = 256 - wx_a;
8402 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8403 let p0_a: u32 = pair_a as u32;
8404 let p1_a: u32 = (pair_a >> 32) as u32;
8405 let rb_a: u32 =
8406 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8407 >> 8)
8408 & 0x00FF_00FF;
8409 let g_a: u32 =
8410 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8411 << 8;
8412 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8413 let sx_b: usize = (e1 >> 9) as usize;
8414 let wx_b: u32 = e1 & 0x1FF;
8415 let iwx_b: u32 = 256 - wx_b;
8416 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8417 let p0_b: u32 = pair_b as u32;
8418 let p1_b: u32 = (pair_b >> 32) as u32;
8419 let rb_b: u32 =
8420 (((p0_b & 0x00FF_00FF) * iwx_b + (p1_b & 0x00FF_00FF) * wx_b + 0x0080_0080)
8421 >> 8)
8422 & 0x00FF_00FF;
8423 let g_b: u32 =
8424 ((((p0_b >> 8) & 0x00FF) * iwx_b + ((p1_b >> 8) & 0x00FF) * wx_b + 128) >> 8)
8425 << 8;
8426 *dptr.add(item_index + 1) = (rb_b | g_b | 0xFF00_0000).to_le_bytes();
8427 }
8428 item_index += 2;
8429 }
8430 if item_index < len {
8431 unsafe {
8433 let e0: u32 = *lptr.add(item_index);
8434 let sx_a: usize = (e0 >> 9) as usize;
8435 let wx_a: u32 = e0 & 0x1FF;
8436 let iwx_a: u32 = 256 - wx_a;
8437 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8438 let p0_a: u32 = pair_a as u32;
8439 let p1_a: u32 = (pair_a >> 32) as u32;
8440 let rb_a: u32 =
8441 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8442 >> 8)
8443 & 0x00FF_00FF;
8444 let g_a: u32 =
8445 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8446 << 8;
8447 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8448 }
8449 }
8450 }
8451
8452 #[inline(always)]
8460 fn copy_opaque_row_to_vrow(src0: &[[u8; 4]], sx_range: (usize, usize), vrow: &mut [u32]) {
8461 let (sx_min, sx_max): (usize, usize) = sx_range;
8462 for (&px, out) in src0[sx_min..=sx_max]
8463 .iter()
8464 .zip(vrow[sx_min..=sx_max].iter_mut())
8465 {
8466 *out = u32::from_le_bytes(px);
8467 }
8468 vrow[sx_max + 1] = vrow[sx_max];
8469 }
8470
8471 #[inline(always)]
8481 fn blend_opaque_rows_vert_swar(
8482 src0: &[[u8; 4]],
8483 src1: &[[u8; 4]],
8484 sx_range: (usize, usize),
8485 weights: (u32, u32),
8486 vrow: &mut [u32],
8487 ) {
8488 let (sx_min, sx_max): (usize, usize) = sx_range;
8489 let (wy, iwy): (u32, u32) = weights;
8490 let s0_slice: &[[u8; 4]] = &src0[sx_min..=sx_max];
8491 let s1_slice: &[[u8; 4]] = &src1[sx_min..=sx_max];
8492 let dst_slice: &mut [u32] = &mut vrow[sx_min..=sx_max];
8493 let mut idx: usize = 0;
8494 let count: usize = dst_slice.len();
8495 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8496 if count >= 4 {
8497 unsafe {
8499 let s0_ptr: *const u8 = s0_slice.as_ptr().cast();
8500 let s1_ptr: *const u8 = s1_slice.as_ptr().cast();
8501 let d_ptr: *mut u8 = dst_slice.as_mut_ptr().cast();
8502 let v_wy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(wy as u16);
8503 let v_iwy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(iwy as u16);
8504 let v_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8505 let v_alpha: core::arch::wasm32::v128 =
8506 core::arch::wasm32::u32x4_splat(0xFF00_0000);
8507 while idx + 4 <= count {
8508 let b_off: usize = idx * 4;
8509 let a16: core::arch::wasm32::v128 =
8510 core::arch::wasm32::v128_load(s0_ptr.add(b_off).cast());
8511 let b16: core::arch::wasm32::v128 =
8512 core::arch::wasm32::v128_load(s1_ptr.add(b_off).cast());
8513 let a_lo: core::arch::wasm32::v128 =
8514 core::arch::wasm32::u16x8_extend_low_u8x16(a16);
8515 let b_lo: core::arch::wasm32::v128 =
8516 core::arch::wasm32::u16x8_extend_low_u8x16(b16);
8517 let a_hi: core::arch::wasm32::v128 =
8518 core::arch::wasm32::u16x8_extend_high_u8x16(a16);
8519 let b_hi: core::arch::wasm32::v128 =
8520 core::arch::wasm32::u16x8_extend_high_u8x16(b16);
8521 let lo: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8522 core::arch::wasm32::i16x8_add(
8523 core::arch::wasm32::i16x8_add(
8524 core::arch::wasm32::i16x8_mul(a_lo, v_iwy),
8525 core::arch::wasm32::i16x8_mul(b_lo, v_wy),
8526 ),
8527 v_round,
8528 ),
8529 8,
8530 );
8531 let hi: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8532 core::arch::wasm32::i16x8_add(
8533 core::arch::wasm32::i16x8_add(
8534 core::arch::wasm32::i16x8_mul(a_hi, v_iwy),
8535 core::arch::wasm32::i16x8_mul(b_hi, v_wy),
8536 ),
8537 v_round,
8538 ),
8539 8,
8540 );
8541 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8542 core::arch::wasm32::u8x16_narrow_i16x8(lo, hi),
8543 v_alpha,
8544 );
8545 core::arch::wasm32::v128_store(d_ptr.add(b_off).cast(), packed);
8546 idx += 4;
8547 }
8548 }
8549 }
8550 while idx < count {
8551 let p0: u32 = u32::from_le_bytes(s0_slice[idx]);
8552 let p1: u32 = u32::from_le_bytes(s1_slice[idx]);
8553 let rb: u32 = (((p0 & 0x00FF_00FF) * iwy + (p1 & 0x00FF_00FF) * wy + 0x0080_0080) >> 8)
8554 & 0x00FF_00FF;
8555 let green_val: u32 =
8556 ((((p0 >> 8) & 0x00FF) * iwy + ((p1 >> 8) & 0x00FF) * wy + 128) >> 8) << 8;
8557 dst_slice[idx] = (rb | green_val) | 0xFF00_0000;
8558 idx += 1;
8559 }
8560 vrow[sx_max + 1] = vrow[sx_max];
8561 }
8562
8563 #[inline(always)]
8577 fn blit_bilinear_span_precomputed(
8578 y_params: (usize, usize, u32, u32),
8579 dst_x0: usize,
8580 x_lut: &[(usize, usize, u32)],
8581 src_bytes: &[u8],
8582 dst_row: &mut [u8],
8583 ) -> usize {
8584 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
8585 let span_bytes_start: usize = dst_x0 * 4;
8586 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
8587 if span_bytes_end > dst_row.len() {
8588 return 0;
8589 }
8590 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8591 .as_chunks_mut::<4>()
8592 .0;
8593 let src_len: usize = src_bytes.len();
8594 let mut shaded: usize = 0;
8595 if wy == 0 {
8596 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8597 let i0: usize = (row0 + sx0) * 4;
8598 let i1: usize = (row0 + sx1) * 4;
8599 if i1 + 4 > src_len {
8600 continue;
8601 }
8602 let iwx: u32 = 256 - wx;
8603 let a0: u32 = src_bytes[i0 + 3] as u32;
8604 let a1: u32 = src_bytes[i1 + 3] as u32;
8605 if (a0 & a1) == 255 {
8606 dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
8607 >> 8) as u8;
8608 dp[1] =
8609 (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
8610 >> 8) as u8;
8611 dp[2] =
8612 (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
8613 >> 8) as u8;
8614 dp[3] = 255;
8615 shaded += 1;
8616 continue;
8617 }
8618 let aw0: u32 = a0 * iwx;
8619 let aw1: u32 = a1 * wx;
8620 let a_val: u32 = (aw0 + aw1 + 128) >> 8;
8621 if a_val == 0 {
8622 continue;
8623 }
8624 let pr: u32 =
8625 ((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + 128) >> 8;
8626 let pg: u32 =
8627 ((src_bytes[i0 + 1] as u32) * aw0 + (src_bytes[i1 + 1] as u32) * aw1 + 128)
8628 >> 8;
8629 let pb: u32 =
8630 ((src_bytes[i0 + 2] as u32) * aw0 + (src_bytes[i1 + 2] as u32) * aw1 + 128)
8631 >> 8;
8632 let inv_a: u32 = 255 - a_val;
8633 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8634 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8635 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8636 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8637 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8638 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8639 dp[3] = 255;
8640 shaded += 1;
8641 }
8642 return shaded;
8643 }
8644 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8645 let i00: usize = (row0 + sx0) * 4;
8646 let i10: usize = (row0 + sx1) * 4;
8647 let i01: usize = (row1 + sx0) * 4;
8648 let i11: usize = (row1 + sx1) * 4;
8649 if i11 + 4 > src_len {
8650 continue;
8651 }
8652 let iwx: u32 = 256 - wx;
8653 let w00: u32 = iwx * iwy;
8654 let w10: u32 = wx * iwy;
8655 let w01: u32 = iwx * wy;
8656 let w11: u32 = wx * wy;
8657 let a00: u32 = src_bytes[i00 + 3] as u32;
8658 let a10: u32 = src_bytes[i10 + 3] as u32;
8659 let a01: u32 = src_bytes[i01 + 3] as u32;
8660 let a11: u32 = src_bytes[i11 + 3] as u32;
8661 if (a00 & a10 & a01 & a11) == 255 {
8662 dp[0] = (((src_bytes[i00] as u32) * w00
8663 + (src_bytes[i10] as u32) * w10
8664 + (src_bytes[i01] as u32) * w01
8665 + (src_bytes[i11] as u32) * w11
8666 + 32768)
8667 >> 16) as u8;
8668 dp[1] = (((src_bytes[i00 + 1] as u32) * w00
8669 + (src_bytes[i10 + 1] as u32) * w10
8670 + (src_bytes[i01 + 1] as u32) * w01
8671 + (src_bytes[i11 + 1] as u32) * w11
8672 + 32768)
8673 >> 16) as u8;
8674 dp[2] = (((src_bytes[i00 + 2] as u32) * w00
8675 + (src_bytes[i10 + 2] as u32) * w10
8676 + (src_bytes[i01 + 2] as u32) * w01
8677 + (src_bytes[i11 + 2] as u32) * w11
8678 + 32768)
8679 >> 16) as u8;
8680 dp[3] = 255;
8681 shaded += 1;
8682 continue;
8683 }
8684 let aw00: u64 = (a00 as u64) * (w00 as u64);
8685 let aw10: u64 = (a10 as u64) * (w10 as u64);
8686 let aw01: u64 = (a01 as u64) * (w01 as u64);
8687 let aw11: u64 = (a11 as u64) * (w11 as u64);
8688 let a_val: u32 = ((aw00 + aw10 + aw01 + aw11 + 32768) >> 16) as u32;
8689 if a_val == 0 {
8690 continue;
8691 }
8692 let pr: u32 = (((src_bytes[i00] as u64) * aw00
8693 + (src_bytes[i10] as u64) * aw10
8694 + (src_bytes[i01] as u64) * aw01
8695 + (src_bytes[i11] as u64) * aw11
8696 + 32768)
8697 >> 16) as u32;
8698 let pg: u32 = (((src_bytes[i00 + 1] as u64) * aw00
8699 + (src_bytes[i10 + 1] as u64) * aw10
8700 + (src_bytes[i01 + 1] as u64) * aw01
8701 + (src_bytes[i11 + 1] as u64) * aw11
8702 + 32768)
8703 >> 16) as u32;
8704 let pb: u32 = (((src_bytes[i00 + 2] as u64) * aw00
8705 + (src_bytes[i10 + 2] as u64) * aw10
8706 + (src_bytes[i01 + 2] as u64) * aw01
8707 + (src_bytes[i11 + 2] as u64) * aw11
8708 + 32768)
8709 >> 16) as u32;
8710 let inv_a: u32 = 255 - a_val;
8711 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8712 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8713 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8714 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8715 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8716 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8717 dp[3] = 255;
8718 shaded += 1;
8719 }
8720 shaded
8721 }
8722
8723 fn raster_image_bilinear_with_lut(
8739 band: &mut PixelBand<'_>,
8740 rect: Rect,
8741 src_info: (u32, u32, &[u8]),
8742 bounds: (u32, u32, u32, u32),
8743 radius: CornerRadius,
8744 aa: AntialiasingMode,
8745 x_lut: &mut Vec<(usize, usize, u32)>,
8746 ) -> usize {
8747 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
8748 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
8749 let rect_x: f32 = rect.get_x();
8750 let rect_y: f32 = rect.get_y();
8751 let half_w: f32 = rect.get_width() * 0.5;
8752 let half_h: f32 = rect.get_height() * 0.5;
8753 let cx: f32 = rect_x + half_w;
8754 let cy: f32 = rect_y + half_h;
8755 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
8756 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
8757 let src_w_f: f32 = src_w as f32;
8758 let src_h_f: f32 = src_h as f32;
8759 let src_w_usize: usize = src_w as usize;
8760 let max_sx: usize = src_w_usize.saturating_sub(1);
8761 let max_sy: usize = (src_h as usize).saturating_sub(1);
8762 let has_radius: bool = radius.max_radius() > 0.0;
8763 x_lut.clear();
8764 for pos_x in x0..x1 {
8765 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
8766 let fx: f32 = (tex_u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
8767 let sx0: usize = (fx.floor() as usize).min(max_sx);
8768 let sx1: usize = (sx0 + 1).min(max_sx);
8769 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8770 x_lut.push((sx0, sx1, wx));
8771 }
8772 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
8773 if !has_radius {
8774 let x0_u: usize = x0 as usize;
8775 let sx_min: usize = x_lut_ref
8776 .first()
8777 .map_or(0, |event_ref: &(usize, usize, u32)| event_ref.0);
8778 let sx_max: usize = x_lut_ref
8779 .last()
8780 .map_or(0, |error_val: &(usize, usize, u32)| error_val.1)
8781 .min(max_sx);
8782 let src_row_bytes_len: usize = src_w_usize * 4;
8783 let can_fast_opaque: bool = !x_lut_ref.is_empty()
8784 && sx_min <= sx_max
8785 && sx_max < src_w_usize
8786 && (src_h as usize) * src_row_bytes_len <= src_bytes.len();
8787 if can_fast_opaque {
8788 let mut cached_op_sy: usize = usize::MAX;
8789 let mut cached_op_val: bool = false;
8790 let mut cached_op_sy2: usize = usize::MAX;
8791 let mut cached_op_val2: bool = false;
8792 let ran_vrow: bool = BAND_IMAGE_VROW_U32
8793 .try_with(|cell: &RefCell<Vec<u32>>| {
8794 let _ran_packed: bool = BAND_IMAGE_X_PACKED
8795 .try_with(|pcell: &RefCell<Vec<u32>>| {
8796 if let (Ok(mut vrow_guard), Ok(mut packed_guard)) =
8797 (cell.try_borrow_mut(), pcell.try_borrow_mut())
8798 {
8799 if vrow_guard.len() < src_w_usize + 1 {
8800 vrow_guard.resize(src_w_usize + 1, 0);
8801 }
8802 packed_guard.clear();
8803 for &(sx0, _, wx) in x_lut_ref.iter() {
8804 packed_guard.push(((sx0 as u32) << 9) | (wx & 0x1FF));
8805 }
8806 let x_packed_ref: &[u32] = packed_guard.as_slice();
8807 let vrow: &mut [u32] = vrow_guard.as_mut_slice();
8808 let mut prev_vkey: (usize, usize, u32) =
8809 (usize::MAX, usize::MAX, u32::MAX);
8810 let check_start: usize = sx_min * 4;
8811 let check_end: usize = (sx_max + 1) * 4;
8812 for pos_y in y0..y1 {
8813 let Some(dst_row) = band.row_slice_mut(pos_y) else {
8814 continue;
8815 };
8816 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y)
8817 * inv_dst_h)
8818 .clamp(0.0, 1.0);
8819 let fy: f32 =
8820 (item_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8821 let sy0: usize = (fy.floor() as usize).min(max_sy);
8822 let sy1: usize = (sy0 + 1).min(max_sy);
8823 let wy: u32 =
8824 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0)
8825 as u32;
8826 let r0_off: usize = sy0 * src_row_bytes_len;
8827 let op0: bool = if sy0 == cached_op_sy {
8828 cached_op_val
8829 } else if sy0 == cached_op_sy2 {
8830 cached_op_val2
8831 } else {
8832 let val: bool = is_rgba_slice_opaque(
8833 &src_bytes
8834 [(r0_off + check_start)..(r0_off + check_end)],
8835 );
8836 cached_op_sy2 = cached_op_sy;
8837 cached_op_val2 = cached_op_val;
8838 cached_op_sy = sy0;
8839 cached_op_val = val;
8840 val
8841 };
8842 if wy == 0 || sy0 == sy1 {
8843 if op0 {
8844 let vkey: (usize, usize, u32) = (sy0, sy0, 0);
8845 if prev_vkey != vkey {
8846 let row0_px: &[[u8; 4]] = src_bytes
8847 [r0_off..(r0_off + src_row_bytes_len)]
8848 .as_chunks::<4>()
8849 .0;
8850 Self::copy_opaque_row_to_vrow(
8851 row0_px,
8852 (sx_min, sx_max),
8853 vrow,
8854 );
8855 prev_vkey = vkey;
8856 }
8857 Self::blit_opaque_horiz_packed_u32(
8858 vrow,
8859 x0_u,
8860 x_packed_ref,
8861 dst_row,
8862 );
8863 continue;
8864 }
8865 } else if op0 {
8866 let r1_off: usize = sy1 * src_row_bytes_len;
8867 let op1: bool = if sy1 == cached_op_sy {
8868 cached_op_val
8869 } else if sy1 == cached_op_sy2 {
8870 cached_op_val2
8871 } else {
8872 let val: bool = is_rgba_slice_opaque(
8873 &src_bytes[(r1_off + check_start)
8874 ..(r1_off + check_end)],
8875 );
8876 cached_op_sy2 = cached_op_sy;
8877 cached_op_val2 = cached_op_val;
8878 cached_op_sy = sy1;
8879 cached_op_val = val;
8880 val
8881 };
8882 if op1 {
8883 let vkey: (usize, usize, u32) = (sy0, sy1, wy);
8884 if prev_vkey != vkey {
8885 let row0_px: &[[u8; 4]] = src_bytes
8886 [r0_off..(r0_off + src_row_bytes_len)]
8887 .as_chunks::<4>()
8888 .0;
8889 let row1_px: &[[u8; 4]] = src_bytes
8890 [r1_off..(r1_off + src_row_bytes_len)]
8891 .as_chunks::<4>()
8892 .0;
8893 Self::blend_opaque_rows_vert_swar(
8894 row0_px,
8895 row1_px,
8896 (sx_min, sx_max),
8897 (wy, 256 - wy),
8898 vrow,
8899 );
8900 prev_vkey = vkey;
8901 }
8902 Self::blit_opaque_horiz_packed_u32(
8903 vrow,
8904 x0_u,
8905 x_packed_ref,
8906 dst_row,
8907 );
8908 continue;
8909 }
8910 }
8911 let y_params: (usize, usize, u32, u32) =
8912 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8913 let _: usize = Self::blit_bilinear_span_precomputed(
8914 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8915 );
8916 }
8917 }
8918 })
8919 .is_ok();
8920 })
8921 .is_ok();
8922 if ran_vrow {
8923 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8924 }
8925 }
8926 for coord_y in y0..y1 {
8927 let Some(dst_row) = band.row_slice_mut(coord_y) else {
8928 continue;
8929 };
8930 let tex_v: f32 = (((coord_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8931 let fy: f32 = (tex_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8932 let sy0: usize = (fy.floor() as usize).min(max_sy);
8933 let sy1: usize = (sy0 + 1).min(max_sy);
8934 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8935 let y_params: (usize, usize, u32, u32) =
8936 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8937 let _: usize = Self::blit_bilinear_span_precomputed(
8938 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8939 );
8940 }
8941 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8942 }
8943 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
8944 let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8945 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
8946 let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
8947 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
8948 let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8949 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
8950 let mut shaded: usize = 0;
8951 for sample_y in y0..iy0 {
8952 let Some(dst_row) = band.row_slice_mut(sample_y) else {
8953 continue;
8954 };
8955 let bary_v: f32 = (((sample_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8956 let fy: f32 = (bary_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8957 let sy0: usize = (fy.floor() as usize).min(max_sy);
8958 let sy1: usize = (sy0 + 1).min(max_sy);
8959 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8960 let y_params: (usize, usize, u32, u32) =
8961 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8962 let py: f32 = (sample_y as f32) + 0.5 - cy;
8963 let dist_y: f32 = py.abs() - half_h;
8964 let mid_cov: f32 = sdf_coverage(dist_y, aa);
8965 if cx0 < cx1 && mid_cov > 0.0 {
8966 let lut_s: usize = (cx0 - x0) as usize;
8967 let lut_e: usize = (cx1 - x0) as usize;
8968 if mid_cov >= 0.9995 {
8969 let _: usize = Self::blit_bilinear_span_precomputed(
8970 y_params,
8971 cx0 as usize,
8972 &x_lut_ref[lut_s..lut_e],
8973 src_bytes,
8974 dst_row,
8975 );
8976 } else {
8977 for coord_x in cx0..cx1 {
8978 let rgba: [u8; 4] = sample_bilinear_fixed(
8979 src_bytes,
8980 y_params,
8981 x_lut_ref[(coord_x - x0) as usize],
8982 );
8983 let off: usize = (coord_x as usize) * 4;
8984 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
8985 }
8986 }
8987 shaded += (cx1 - cx0) as usize;
8988 }
8989 for sample_x in x0..cx0 {
8990 let px: f32 = (sample_x as f32) + 0.5 - cx;
8991 let cr: f32 = quadrant_corner_radius(radius, px, py);
8992 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8993 if cov > 0.0 {
8994 let rgba: [u8; 4] = sample_bilinear_fixed(
8995 src_bytes,
8996 y_params,
8997 x_lut_ref[(sample_x - x0) as usize],
8998 );
8999 let off: usize = (sample_x as usize) * 4;
9000 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9001 shaded += 1;
9002 }
9003 }
9004 for value_x in cx1..x1 {
9005 let px: f32 = (value_x as f32) + 0.5 - cx;
9006 let cr: f32 = quadrant_corner_radius(radius, px, py);
9007 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9008 if cov > 0.0 {
9009 let rgba: [u8; 4] = sample_bilinear_fixed(
9010 src_bytes,
9011 y_params,
9012 x_lut_ref[(value_x - x0) as usize],
9013 );
9014 let off: usize = (value_x as usize) * 4;
9015 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9016 shaded += 1;
9017 }
9018 }
9019 }
9020 for value_y in iy0..iy1 {
9021 let Some(dst_row) = band.row_slice_mut(value_y) else {
9022 continue;
9023 };
9024 let sample_val: f32 = (((value_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9025 let fy: f32 = (sample_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9026 let sy0: usize = (fy.floor() as usize).min(max_sy);
9027 let sy1: usize = (sy0 + 1).min(max_sy);
9028 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9029 let y_params: (usize, usize, u32, u32) =
9030 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9031 if ix0 < ix1 {
9032 let lut_s: usize = (ix0 - x0) as usize;
9033 let lut_e: usize = (ix1 - x0) as usize;
9034 let _: usize = Self::blit_bilinear_span_precomputed(
9035 y_params,
9036 ix0 as usize,
9037 &x_lut_ref[lut_s..lut_e],
9038 src_bytes,
9039 dst_row,
9040 );
9041 shaded += (ix1 - ix0) as usize;
9042 }
9043 for pos_x_primary in x0..ix0 {
9044 let dist: f32 = ((pos_x_primary as f32) + 0.5 - cx).abs() - half_w;
9045 let cov: f32 = sdf_coverage(dist, aa);
9046 if cov > 0.0 {
9047 let rgba: [u8; 4] = sample_bilinear_fixed(
9048 src_bytes,
9049 y_params,
9050 x_lut_ref[(pos_x_primary - x0) as usize],
9051 );
9052 let off: usize = (pos_x_primary as usize) * 4;
9053 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9054 shaded += 1;
9055 }
9056 }
9057 for pos_x_secondary in ix1..x1 {
9058 let dist: f32 = ((pos_x_secondary as f32) + 0.5 - cx).abs() - half_w;
9059 let cov: f32 = sdf_coverage(dist, aa);
9060 if cov > 0.0 {
9061 let rgba: [u8; 4] = sample_bilinear_fixed(
9062 src_bytes,
9063 y_params,
9064 x_lut_ref[(pos_x_secondary - x0) as usize],
9065 );
9066 let off: usize = (pos_x_secondary as usize) * 4;
9067 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9068 shaded += 1;
9069 }
9070 }
9071 }
9072 for pos_y_primary in iy1..y1 {
9073 let Some(dst_row) = band.row_slice_mut(pos_y_primary) else {
9074 continue;
9075 };
9076 let item_val_primary: f32 =
9077 (((pos_y_primary as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9078 let fy: f32 = (item_val_primary * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9079 let sy0: usize = (fy.floor() as usize).min(max_sy);
9080 let sy1: usize = (sy0 + 1).min(max_sy);
9081 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9082 let y_params: (usize, usize, u32, u32) =
9083 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9084 let py: f32 = (pos_y_primary as f32) + 0.5 - cy;
9085 let dist_y: f32 = py.abs() - half_h;
9086 let mid_cov: f32 = sdf_coverage(dist_y, aa);
9087 if cx0 < cx1 && mid_cov > 0.0 {
9088 let lut_s: usize = (cx0 - x0) as usize;
9089 let lut_e: usize = (cx1 - x0) as usize;
9090 if mid_cov >= 0.9995 {
9091 let _: usize = Self::blit_bilinear_span_precomputed(
9092 y_params,
9093 cx0 as usize,
9094 &x_lut_ref[lut_s..lut_e],
9095 src_bytes,
9096 dst_row,
9097 );
9098 } else {
9099 for pos_x_next in cx0..cx1 {
9100 let rgba: [u8; 4] = sample_bilinear_fixed(
9101 src_bytes,
9102 y_params,
9103 x_lut_ref[(pos_x_next - x0) as usize],
9104 );
9105 let off: usize = (pos_x_next as usize) * 4;
9106 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
9107 }
9108 }
9109 shaded += (cx1 - cx0) as usize;
9110 }
9111 for pos_x_alt in x0..cx0 {
9112 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
9113 let cr: f32 = quadrant_corner_radius(radius, px, py);
9114 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9115 if cov > 0.0 {
9116 let rgba: [u8; 4] = sample_bilinear_fixed(
9117 src_bytes,
9118 y_params,
9119 x_lut_ref[(pos_x_alt - x0) as usize],
9120 );
9121 let off: usize = (pos_x_alt as usize) * 4;
9122 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9123 shaded += 1;
9124 }
9125 }
9126 for pos_x_inner in cx1..x1 {
9127 let px: f32 = (pos_x_inner as f32) + 0.5 - cx;
9128 let cr: f32 = quadrant_corner_radius(radius, px, py);
9129 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9130 if cov > 0.0 {
9131 let rgba: [u8; 4] = sample_bilinear_fixed(
9132 src_bytes,
9133 y_params,
9134 x_lut_ref[(pos_x_inner - x0) as usize],
9135 );
9136 let off: usize = (pos_x_inner as usize) * 4;
9137 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9138 shaded += 1;
9139 }
9140 }
9141 }
9142 shaded
9143 }
9144
9145 fn raster_rgba_bytes(
9160 band: &mut PixelBand<'_>,
9161 rect: Rect,
9162 source: (u32, u32, &[u8]),
9163 radius: CornerRadius,
9164 clip: Rect,
9165 aa: AntialiasingMode,
9166 ) -> usize {
9167 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = source;
9168 if src_w == 0 || src_h == 0 {
9169 return 0;
9170 }
9171 let Some(vis) = rect.intersect(clip) else {
9172 return 0;
9173 };
9174 let fb_w: u32 = band.width();
9175 let band_y0: u32 = band.y_offset();
9176 let band_y1: u32 = band.y_end();
9177 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9178 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9179 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9180 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9181 if x0 >= x1 || y0 >= y1 {
9182 return 0;
9183 }
9184 let half_w: f32 = rect.get_width() * 0.5;
9185 let half_h: f32 = rect.get_height() * 0.5;
9186 let cx: f32 = rect.get_x() + half_w;
9187 let cy: f32 = rect.get_y() + half_h;
9188 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
9189 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
9190 let use_bilinear: bool = aa != AntialiasingMode::None
9191 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
9192 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
9193 let has_radius: bool = radius.max_radius() > 0.0;
9194 let max_sx: usize = (src_w as usize).saturating_sub(1);
9195 let max_sy: usize = (src_h as usize).saturating_sub(1);
9196 let src_w_usize: usize = src_w as usize;
9197 let is_exact_1to1: bool = !use_bilinear
9198 && (rect.get_width() - (src_w as f32)).abs() <= 0.01
9199 && (rect.get_height() - (src_h as f32)).abs() <= 0.01
9200 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
9201 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
9202 let rx0_i: i32 = rect.get_x().round() as i32;
9203 let ry0_i: i32 = rect.get_y().round() as i32;
9204 if is_exact_1to1
9205 && !has_radius
9206 && (x0 as i32) >= rx0_i
9207 && (x1 as i32) <= rx0_i + (src_w as i32)
9208 && (y0 as i32) >= ry0_i
9209 && (y1 as i32) <= ry0_i + (src_h as i32)
9210 {
9211 let span_w: usize = (x1 - x0) as usize;
9212 let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
9213 let dst_byte0: usize = (x0 as usize) * 4;
9214 let dst_byte1: usize = (x1 as usize) * 4;
9215 for pos_y in y0..y1 {
9216 let Some(dst_row) = band.row_slice_mut(pos_y) else {
9217 continue;
9218 };
9219 let sy: usize = ((pos_y as i32) - ry0_i) as usize;
9220 let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
9221 let src_byte1: usize = src_byte0 + span_w * 4;
9222 if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
9223 blit_1to1_rgba_span(
9224 &src_bytes[src_byte0..src_byte1],
9225 &mut dst_row[dst_byte0..dst_byte1],
9226 );
9227 }
9228 }
9229 return span_w * ((y1 - y0) as usize);
9230 }
9231 if use_bilinear {
9232 let mut shaded: usize = 0;
9233 let ran_tls: bool = BAND_IMAGE_X_LUT
9234 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9235 if let Ok(mut guard) = cell.try_borrow_mut() {
9236 shaded = Self::raster_image_bilinear_with_lut(
9237 band,
9238 rect,
9239 (src_w, src_h, src_bytes),
9240 (x0, y0, x1, y1),
9241 radius,
9242 aa,
9243 &mut guard,
9244 );
9245 }
9246 })
9247 .is_ok();
9248 if !ran_tls {
9249 let mut fallback_lut: Vec<(usize, usize, u32)> =
9250 Vec::with_capacity((x1 - x0) as usize);
9251 shaded = Self::raster_image_bilinear_with_lut(
9252 band,
9253 rect,
9254 (src_w, src_h, src_bytes),
9255 (x0, y0, x1, y1),
9256 radius,
9257 aa,
9258 &mut fallback_lut,
9259 );
9260 }
9261 return shaded;
9262 }
9263 if !has_radius && (src_h as usize) * src_w_usize * 4 <= src_bytes.len() {
9264 let x0_u: usize = x0 as usize;
9265 let span_w: usize = (x1 - x0) as usize;
9266 let dst_b0: usize = x0_u * 4;
9267 let dst_b1: usize = (x1 as usize) * 4;
9268 let src_w_f: f32 = src_w as f32;
9269 let src_h_f: f32 = src_h as f32;
9270 let mut sx_arr_ok: bool = false;
9271 let _ran_tls_nn: bool = BAND_IMAGE_X_LUT
9272 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9273 if let Ok(mut lut) = cell.try_borrow_mut() {
9274 lut.clear();
9275 for pos_x in x0..x1 {
9276 let tex_u: f32 =
9277 (((pos_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9278 let sx: usize = ((tex_u * src_w_f).floor() as usize).min(max_sx);
9279 lut.push((sx, 0, 0));
9280 }
9281 let lut_ref: &[(usize, usize, u32)] = lut.as_slice();
9282 let row_bytes_len: usize = src_w_usize * 4;
9283 let mut cached_sy: usize = usize::MAX;
9284 let mut cached_opaque: bool = false;
9285 for coord_y in y0..y1 {
9286 let Some(dst_row) = band.row_slice_mut(coord_y) else {
9287 continue;
9288 };
9289 if dst_b1 > dst_row.len() {
9290 continue;
9291 }
9292 let item_val: f32 = (((coord_y as f32) + 0.5 - rect.get_y())
9293 * inv_dst_h)
9294 .clamp(0.0, 1.0);
9295 let sy: usize = ((item_val * src_h_f).floor() as usize).min(max_sy);
9296 let r_off: usize = sy * row_bytes_len;
9297 let row_slice: &[u8] = &src_bytes[r_off..(r_off + row_bytes_len)];
9298 let is_op: bool = if sy == cached_sy {
9299 cached_opaque
9300 } else {
9301 cached_sy = sy;
9302 cached_opaque = is_rgba_slice_opaque(row_slice);
9303 cached_opaque
9304 };
9305 let src_px: &[[u8; 4]] = row_slice.as_chunks::<4>().0;
9306 let dst_px: &mut [[u8; 4]] =
9307 dst_row[dst_b0..dst_b1].as_chunks_mut::<4>().0;
9308 if is_op {
9309 let sptr: *const [u8; 4] = src_px.as_ptr();
9310 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9311 *dp = unsafe { *sptr.add(sx) };
9313 }
9314 } else {
9315 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9316 blend_rgba_pixel_with_cov(dp, src_px[sx], 1.0);
9317 }
9318 }
9319 }
9320 sx_arr_ok = true;
9321 }
9322 })
9323 .is_ok();
9324 if sx_arr_ok {
9325 return span_w * ((y1 - y0) as usize);
9326 }
9327 }
9328 let mut shaded: usize = 0;
9329 let r_max: f32 = if has_radius {
9330 radius.max_radius().min(half_w).min(half_h).max(0.0)
9331 } else {
9332 0.0
9333 };
9334 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9335 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
9336 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
9337 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
9338 let can_1to1_interior: bool = is_exact_1to1
9339 && (ix0 as i32) >= rx0_i
9340 && (ix1 as i32) <= rx0_i + (src_w as i32)
9341 && (iy0 as i32) >= ry0_i
9342 && (iy1 as i32) <= ry0_i + (src_h as i32);
9343 for sample_y in y0..y1 {
9344 let Some(dst_row) = band.row_slice_mut(sample_y) else {
9345 continue;
9346 };
9347 let tex_v: f32 = (((sample_y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
9348 let py: f32 = (sample_y as f32) + 0.5 - cy;
9349 let sy: usize = ((tex_v * (src_h as f32)).floor() as usize).min(max_sy);
9350 let row: usize = sy * src_w_usize;
9351 if has_radius && can_1to1_interior && sample_y >= iy0 && sample_y < iy1 && ix0 < ix1 {
9352 let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
9353 let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
9354 let dst_off: usize = (ix0 as usize) * 4;
9355 if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
9356 {
9357 blit_1to1_rgba_span(
9358 &src_bytes[src_off..src_off + span_bytes],
9359 &mut dst_row[dst_off..dst_off + span_bytes],
9360 );
9361 }
9362 shaded += (ix1 - ix0) as usize;
9363 for coord_x in x0..ix0 {
9364 let dist: f32 = ((coord_x as f32) + 0.5 - cx).abs() - half_w;
9365 let cov: f32 = sdf_coverage(dist, aa);
9366 if cov > 0.0 {
9367 let bary_u: f32 =
9368 (((coord_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9369 let sx: usize = ((bary_u * (src_w as f32)).floor() as usize).min(max_sx);
9370 let idx: usize = (row + sx) * 4;
9371 if idx + 4 <= src_bytes.len() {
9372 let off: usize = (coord_x as usize) * 4;
9373 blend_rgba_pixel_with_cov(
9374 &mut dst_row[off..off + 4],
9375 [
9376 src_bytes[idx],
9377 src_bytes[idx + 1],
9378 src_bytes[idx + 2],
9379 src_bytes[idx + 3],
9380 ],
9381 cov,
9382 );
9383 shaded += 1;
9384 }
9385 }
9386 }
9387 for sample_x in ix1..x1 {
9388 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
9389 let cov: f32 = sdf_coverage(dist, aa);
9390 if cov > 0.0 {
9391 let unit_u: f32 =
9392 (((sample_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9393 let sx: usize = ((unit_u * (src_w as f32)).floor() as usize).min(max_sx);
9394 let idx: usize = (row + sx) * 4;
9395 if idx + 4 <= src_bytes.len() {
9396 let off: usize = (sample_x as usize) * 4;
9397 blend_rgba_pixel_with_cov(
9398 &mut dst_row[off..off + 4],
9399 [
9400 src_bytes[idx],
9401 src_bytes[idx + 1],
9402 src_bytes[idx + 2],
9403 src_bytes[idx + 3],
9404 ],
9405 cov,
9406 );
9407 shaded += 1;
9408 }
9409 }
9410 }
9411 continue;
9412 }
9413 for value_x in x0..x1 {
9414 let cov: f32 = if has_radius {
9415 let px: f32 = (value_x as f32) + 0.5 - cx;
9416 let cr: f32 = quadrant_corner_radius(radius, px, py);
9417 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
9418 } else {
9419 1.0
9420 };
9421 if cov <= 0.0 {
9422 continue;
9423 }
9424 let upper_val: f32 =
9425 (((value_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9426 let sx: usize = ((upper_val * (src_w as f32)).floor() as usize).min(max_sx);
9427 let idx: usize = (row + sx) * 4;
9428 if idx + 4 <= src_bytes.len() {
9429 let off: usize = (value_x as usize) * 4;
9430 blend_rgba_pixel_with_cov(
9431 &mut dst_row[off..off + 4],
9432 [
9433 src_bytes[idx],
9434 src_bytes[idx + 1],
9435 src_bytes[idx + 2],
9436 src_bytes[idx + 3],
9437 ],
9438 cov,
9439 );
9440 shaded += 1;
9441 }
9442 }
9443 }
9444 shaded
9445 }
9446
9447 fn raster_line(
9463 band: &mut PixelBand<'_>,
9464 from: Point,
9465 to: Point,
9466 color: Color,
9467 width: f32,
9468 clip: Rect,
9469 aa: AntialiasingMode,
9470 ) -> usize {
9471 if color.get_alpha() == 0 {
9472 return 0;
9473 }
9474 let half_w: f32 = width * 0.5;
9475 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
9476 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
9477 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
9478 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
9479 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9480 else {
9481 return 0;
9482 };
9483 let fb_w: u32 = band.width();
9484 let band_y0: u32 = band.y_offset();
9485 let band_y1: u32 = band.y_end();
9486 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9487 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9488 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9489 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9490 if x0 >= x1 || y0 >= y1 {
9491 return 0;
9492 }
9493 let fx0: f32 = from.get_x();
9494 let fy0: f32 = from.get_y();
9495 let dx: f32 = to.get_x() - fx0;
9496 let dy: f32 = to.get_y() - fy0;
9497 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
9498 let inv_len_sq: f32 = 1.0 / len_sq;
9499 let outer_r: f32 = half_w + 0.9;
9500 let outer_r_sq: f32 = outer_r * outer_r;
9501 let inner_r: f32 = (half_w - 0.9).max(0.0);
9502 let inner_r_sq: f32 = inner_r * inner_r;
9503 let has_inner: bool = half_w > 0.9;
9504 let use_oriented_x: bool = dy.abs() > 1e-4;
9505 let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
9506 let x_pad: f32 = if use_oriented_x {
9507 outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
9508 } else {
9509 0.0
9510 };
9511 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9512 let lin_rgb: [f32; 3] = [
9513 SRGB_TO_LIN_LUT[color.get_red() as usize],
9514 SRGB_TO_LIN_LUT[color.get_green() as usize],
9515 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9516 ];
9517 let mut shaded: usize = 0;
9518 for pos_y in y0..y1 {
9519 let py: f32 = (pos_y as f32) + 0.5;
9520 let py_off: f32 = py - fy0;
9521 let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
9522 let x_center: f32 = fx0 + py_off * slope_x_per_y;
9523 let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
9524 let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
9525 (rx0, rx1)
9526 } else {
9527 (x0, x1)
9528 };
9529 if row_x0 >= row_x1 {
9530 continue;
9531 }
9532 let Some(row) = band.row_slice_mut(pos_y) else {
9533 continue;
9534 };
9535 let py_dy: f32 = py_off * dy;
9536 for pos_x in row_x0..row_x1 {
9537 let px: f32 = (pos_x as f32) + 0.5;
9538 let blend_factor: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
9539 let dpx: f32 = px - (fx0 + blend_factor * dx);
9540 let dpy: f32 = py - (fy0 + blend_factor * dy);
9541 let dist_sq: f32 = dpx * dpx + dpy * dpy;
9542 if dist_sq >= outer_r_sq {
9543 continue;
9544 }
9545 let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
9546 1.0
9547 } else {
9548 sdf_coverage(dist_sq.sqrt() - half_w, aa)
9549 };
9550 if cov > 0.0 {
9551 blend_row_pixel_f32_precomputed(row, pos_x, color, lin_rgb, base_alpha * cov);
9552 shaded += 1;
9553 }
9554 }
9555 }
9556 shaded
9557 }
9558
9559 fn raster_circle(
9574 band: &mut PixelBand<'_>,
9575 center: Point,
9576 radius: f32,
9577 color: Color,
9578 clip: Rect,
9579 aa: AntialiasingMode,
9580 ) -> usize {
9581 if radius <= 0.0 || color.get_alpha() == 0 {
9582 return 0;
9583 }
9584 let bounds: Rect = Rect::new(
9585 center.get_x() - radius - 1.0,
9586 center.get_y() - radius - 1.0,
9587 (radius + 1.0) * 2.0,
9588 (radius + 1.0) * 2.0,
9589 );
9590 let Some(vis) = bounds.intersect(clip) else {
9591 return 0;
9592 };
9593 let fb_w: u32 = band.width();
9594 let band_y0: u32 = band.y_offset();
9595 let band_y1: u32 = band.y_end();
9596 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9597 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9598 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9599 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9600 if x0 >= x1 || y0 >= y1 {
9601 return 0;
9602 }
9603 let outer_r: f32 = if aa == AntialiasingMode::None {
9604 radius + 0.5
9605 } else {
9606 radius + 0.65
9607 };
9608 let inner_r: f32 = if aa == AntialiasingMode::None {
9609 (radius - 0.5).max(0.0)
9610 } else {
9611 (radius - 0.65).max(0.0)
9612 };
9613 let outer_r2: f32 = outer_r * outer_r;
9614 let inner_r2: f32 = inner_r * inner_r;
9615 let r2: f32 = radius * radius;
9616 let cx: f32 = center.get_x();
9617 let cy: f32 = center.get_y();
9618 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9619 let lin_rgb: [f32; 3] = [
9620 SRGB_TO_LIN_LUT[color.get_red() as usize],
9621 SRGB_TO_LIN_LUT[color.get_green() as usize],
9622 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9623 ];
9624 let interior_luts: Option<[[u8; 256]; 4]> = if color.get_alpha() < 255 && radius >= 12.0 {
9625 Some(build_linear_blend_luts(color))
9626 } else {
9627 None
9628 };
9629 let mut shaded: usize = 0;
9630 for pos_y in y0..y1 {
9631 let dy: f32 = (pos_y as f32) + 0.5 - cy;
9632 let dy2: f32 = dy * dy;
9633 if dy2 >= outer_r2 {
9634 continue;
9635 }
9636 let out_dx: f32 = (outer_r2 - dy2).sqrt();
9637 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
9638 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
9639 if row_x0 >= row_x1 {
9640 continue;
9641 }
9642 if dy2 < inner_r2 && inner_r > 0.65 {
9643 let in_dx: f32 = (inner_r2 - dy2).sqrt();
9644 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
9645 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
9646 if in_x0 < in_x1 {
9647 if let Some(ref luts) = interior_luts {
9648 band.fill_span_linear_luts(in_x0, in_x1, pos_y, luts);
9649 } else {
9650 band.fill_span_linear(in_x0, in_x1, pos_y, color);
9651 }
9652 shaded += (in_x1 - in_x0) as usize;
9653 }
9654 if (row_x0 < in_x0 || in_x1 < row_x1)
9655 && let Some(row) = band.row_slice_mut(pos_y)
9656 {
9657 for pos_x in row_x0..in_x0 {
9658 let dx: f32 = (pos_x as f32) + 0.5 - cx;
9659 let cov: f32 = if aa == AntialiasingMode::None {
9660 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9661 } else {
9662 circle_supersampled_coverage(dx, dy, radius)
9663 };
9664 if cov > 0.0 {
9665 blend_row_pixel_f32_precomputed(
9666 row,
9667 pos_x,
9668 color,
9669 lin_rgb,
9670 base_alpha * cov,
9671 );
9672 shaded += 1;
9673 }
9674 }
9675 for coord_x in in_x1..row_x1 {
9676 let dx: f32 = (coord_x as f32) + 0.5 - cx;
9677 let cov: f32 = if aa == AntialiasingMode::None {
9678 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9679 } else {
9680 circle_supersampled_coverage(dx, dy, radius)
9681 };
9682 if cov > 0.0 {
9683 blend_row_pixel_f32_precomputed(
9684 row,
9685 coord_x,
9686 color,
9687 lin_rgb,
9688 base_alpha * cov,
9689 );
9690 shaded += 1;
9691 }
9692 }
9693 }
9694 } else if let Some(row) = band.row_slice_mut(pos_y) {
9695 for sample_x in row_x0..row_x1 {
9696 let dx: f32 = (sample_x as f32) + 0.5 - cx;
9697 let cov: f32 = if aa == AntialiasingMode::None {
9698 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9699 } else {
9700 circle_supersampled_coverage(dx, dy, radius)
9701 };
9702 if cov > 0.0 {
9703 blend_row_pixel_f32_precomputed(
9704 row,
9705 sample_x,
9706 color,
9707 lin_rgb,
9708 base_alpha * cov,
9709 );
9710 shaded += 1;
9711 }
9712 }
9713 }
9714 }
9715 shaded
9716 }
9717
9718 #[inline(always)]
9731 #[must_use]
9732 fn solve_triangle_scanline_interval(
9733 d_base: [f32; 3],
9734 a_step: [f32; 3],
9735 thresh: f32,
9736 max_s: f32,
9737 ) -> (f32, f32) {
9738 let mut s_min: f32 = 0.0;
9739 let mut s_max: f32 = max_s;
9740 for idx in 0..3usize {
9741 let alpha_val: f32 = a_step[idx];
9742 let delta_val: f32 = d_base[idx];
9743 if alpha_val > 1e-6 {
9744 let bound: f32 = (thresh - delta_val) / alpha_val;
9745 if bound > s_min {
9746 s_min = bound;
9747 }
9748 } else if alpha_val < -1e-6 {
9749 let bound: f32 = (thresh - delta_val) / alpha_val;
9750 if bound < s_max {
9751 s_max = bound;
9752 }
9753 } else if delta_val < thresh {
9754 return (1.0, 0.0);
9755 }
9756 }
9757 (s_min, s_max)
9758 }
9759
9760 fn raster_triangle(
9776 band: &mut PixelBand<'_>,
9777 p0: Point,
9778 p1: Point,
9779 p2: Point,
9780 color: Color,
9781 clip: Rect,
9782 aa: AntialiasingMode,
9783 ) -> usize {
9784 if color.get_alpha() == 0 {
9785 return 0;
9786 }
9787 let dx0: f32 = p1.get_x() - p0.get_x();
9788 let dy0: f32 = p1.get_y() - p0.get_y();
9789 let dx1: f32 = p2.get_x() - p1.get_x();
9790 let dy1: f32 = p2.get_y() - p1.get_y();
9791 let dx2: f32 = p0.get_x() - p2.get_x();
9792 let dy2: f32 = p0.get_y() - p2.get_y();
9793 let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
9794 if area.abs() < 1e-5 {
9795 return 0;
9796 }
9797 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
9798 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
9799 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
9800 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
9801 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9802 else {
9803 return 0;
9804 };
9805 let fb_w: u32 = band.width();
9806 let band_y0: u32 = band.y_offset();
9807 let band_y1: u32 = band.y_end();
9808 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9809 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9810 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9811 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9812 if clip_x0 >= clip_x1 || y0 >= y1 {
9813 return 0;
9814 }
9815 if aa == AntialiasingMode::None {
9816 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
9817 let mut shaded: usize = 0;
9818 for pos_y in y0..y1 {
9819 let py: f32 = (pos_y as f32) + 0.5;
9820 let mut min_ix: f32 = f32::INFINITY;
9821 let mut max_ix: f32 = f32::NEG_INFINITY;
9822 for (alpha_val, blue_val) in edges.iter() {
9823 let ay: f32 = alpha_val.get_y();
9824 let by: f32 = blue_val.get_y();
9825 if (ay <= py && by > py) || (by <= py && ay > py) {
9826 let blend_factor: f32 = (py - ay) / (by - ay);
9827 let ix: f32 = alpha_val.get_x()
9828 + blend_factor * (blue_val.get_x() - alpha_val.get_x());
9829 min_ix = min_ix.min(ix);
9830 max_ix = max_ix.max(ix);
9831 }
9832 }
9833 if min_ix <= max_ix {
9834 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
9835 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
9836 if sx0 < sx1 {
9837 band.fill_span_linear(sx0, sx1, pos_y, color);
9838 shaded += (sx1 - sx0) as usize;
9839 }
9840 }
9841 }
9842 return shaded;
9843 }
9844 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
9845 let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
9846 let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
9847 let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
9848 let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
9849 let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
9850 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9851 let lin_rgb: [f32; 3] = [
9852 SRGB_TO_LIN_LUT[color.get_red() as usize],
9853 SRGB_TO_LIN_LUT[color.get_green() as usize],
9854 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9855 ];
9856 let interior_luts: Option<[[u8; 256]; 4]> =
9857 if color.get_alpha() < 255 && (area.abs() * 0.5) >= 256.0 {
9858 Some(build_linear_blend_luts(color))
9859 } else {
9860 None
9861 };
9862 let px_base: f32 = (clip_x0 as f32) + 0.5;
9863 let max_s: f32 = (clip_x1 - clip_x0) as f32;
9864 let py_start: f32 = (y0 as f32) + 0.5;
9865 let mut d_row: [f32; 3] = [
9866 (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
9867 (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
9868 (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
9869 ];
9870 let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
9871 let verts: (Point, Point, Point) = (p0, p1, p2);
9872 let mut shaded: usize = 0;
9873 for coord_y in y0..y1 {
9874 let py: f32 = (coord_y as f32) + 0.5;
9875 let (out_min, out_max): (f32, f32) =
9876 Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
9877 if out_min <= out_max {
9878 let k_out0: u32 = out_min.floor().max(0.0) as u32;
9879 let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
9880 let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
9881 let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
9882 if row_x0 < row_x1 {
9883 let (in_min, in_max): (f32, f32) =
9884 Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
9885 let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
9886 let k_in0: u32 = in_min.ceil().max(0.0) as u32;
9887 let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
9888 let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
9889 let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
9890 (ix0, ix1)
9891 } else {
9892 (row_x1, row_x1)
9893 };
9894 if in_x0 < in_x1 {
9895 if let Some(ref luts) = interior_luts {
9896 band.fill_span_linear_luts(in_x0, in_x1, coord_y, luts);
9897 } else {
9898 band.fill_span_linear(in_x0, in_x1, coord_y, color);
9899 }
9900 shaded += (in_x1 - in_x0) as usize;
9901 }
9902 if (row_x0 < in_x0 || in_x1 < row_x1)
9903 && let Some(row) = band.row_slice_mut(coord_y)
9904 {
9905 let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
9906 if in_x0 >= in_x1 {
9907 rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
9908 }
9909 for (sx0, sx1) in rim_spans.into_iter() {
9910 if sx0 >= sx1 {
9911 continue;
9912 }
9913 let s0: f32 = (sx0 - clip_x0) as f32;
9914 let mut d0: f32 = d_row[0] + a_step[0] * s0;
9915 let mut d1: f32 = d_row[1] + a_step[1] * s0;
9916 let mut d2: f32 = d_row[2] + a_step[2] * s0;
9917 for pos_x in sx0..sx1 {
9918 if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
9919 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
9920 blend_row_pixel_linear_precomputed(
9921 row, pos_x, color, lin_rgb,
9922 );
9923 shaded += 1;
9924 } else {
9925 let px: f32 = (pos_x as f32) + 0.5;
9926 let cov: f32 = triangle_supersampled_coverage_precomputed(
9927 (px, py),
9928 verts,
9929 edge_deltas,
9930 sign,
9931 );
9932 if cov >= 0.999 {
9933 blend_row_pixel_linear_precomputed(
9934 row, pos_x, color, lin_rgb,
9935 );
9936 shaded += 1;
9937 } else if cov > 0.0 {
9938 blend_row_pixel_f32_precomputed(
9939 row,
9940 pos_x,
9941 color,
9942 lin_rgb,
9943 base_alpha * cov,
9944 );
9945 shaded += 1;
9946 }
9947 }
9948 }
9949 d0 += a_step[0];
9950 d1 += a_step[1];
9951 d2 += a_step[2];
9952 }
9953 }
9954 }
9955 }
9956 }
9957 d_row[0] += b_step[0];
9958 d_row[1] += b_step[1];
9959 d_row[2] += b_step[2];
9960 }
9961 shaded
9962 }
9963
9964 #[inline(always)]
9979 fn blit_sprite_span_tinted(
9980 y_params: (usize, usize, u32, u32),
9981 dst_x0: usize,
9982 x_lut: &[(usize, usize, u32)],
9983 src_bytes: &[u8],
9984 dst_row: &mut [u8],
9985 tint: Color,
9986 ) -> usize {
9987 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
9988 let span_bytes_start: usize = dst_x0 * 4;
9989 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
9990 if span_bytes_end > dst_row.len() {
9991 return 0;
9992 }
9993 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
9994 .as_chunks_mut::<4>()
9995 .0;
9996 let src_len: usize = src_bytes.len();
9997 let transform_val: u32 = tint.get_red() as u32;
9998 let tg: u32 = tint.get_green() as u32;
9999 let tb: u32 = tint.get_blue() as u32;
10000 let ta: u32 = tint.get_alpha() as u32;
10001 let mut shaded: usize = 0;
10002 if wy == 0 {
10003 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
10004 let i0: usize = (row0 + sx0) * 4;
10005 let i1: usize = (row0 + sx1) * 4;
10006 if i1 + 4 > src_len {
10007 continue;
10008 }
10009 let iwx: u32 = 256 - wx;
10010 let a0: u32 = src_bytes[i0 + 3] as u32;
10011 let a1: u32 = src_bytes[i1 + 3] as u32;
10012 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) = if (a0 & a1) == 255 {
10013 (
10014 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8,
10015 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
10016 >> 8,
10017 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
10018 >> 8,
10019 255,
10020 )
10021 } else {
10022 let aw0: u32 = a0 * iwx;
10023 let aw1: u32 = a1 * wx;
10024 let a_sum: u32 = aw0 + aw1;
10025 let a_out: u32 = (a_sum + 128) >> 8;
10026 if a_out == 0 || a_sum == 0 {
10027 continue;
10028 }
10029 let half_a: u32 = a_sum >> 1;
10030 (
10031 (((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + half_a)
10032 / a_sum)
10033 .min(255),
10034 (((src_bytes[i0 + 1] as u32) * aw0
10035 + (src_bytes[i1 + 1] as u32) * aw1
10036 + half_a)
10037 / a_sum)
10038 .min(255),
10039 (((src_bytes[i0 + 2] as u32) * aw0
10040 + (src_bytes[i1 + 2] as u32) * aw1
10041 + half_a)
10042 / a_sum)
10043 .min(255),
10044 a_out,
10045 )
10046 };
10047 let rr: u32 = sr_raw * transform_val + 128;
10048 let gg: u32 = sg_raw * tg + 128;
10049 let bb: u32 = sb_raw * tb + 128;
10050 let aa_v: u32 = sa_raw * ta + 128;
10051 let red_val: u32 = (rr + (rr >> 8)) >> 8;
10052 let green_val: u32 = (gg + (gg >> 8)) >> 8;
10053 let blue_val: u32 = (bb + (bb >> 8)) >> 8;
10054 let alpha_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
10055 if alpha_val == 255 {
10056 dp[0] = red_val as u8;
10057 dp[1] = green_val as u8;
10058 dp[2] = blue_val as u8;
10059 dp[3] = 255;
10060 } else if alpha_val > 0 {
10061 let inv_a: u32 = 255 - alpha_val;
10062 let vr: u32 = red_val * alpha_val + (dp[0] as u32) * inv_a + 128;
10063 let vg: u32 = green_val * alpha_val + (dp[1] as u32) * inv_a + 128;
10064 let vb: u32 = blue_val * alpha_val + (dp[2] as u32) * inv_a + 128;
10065 let va: u32 = (dp[3] as u32) * inv_a + 128;
10066 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
10067 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10068 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10069 dp[3] = (alpha_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
10070 }
10071 shaded += 1;
10072 }
10073 return shaded;
10074 }
10075 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
10076 let i00: usize = (row0 + sx0) * 4;
10077 let i10: usize = (row0 + sx1) * 4;
10078 let i01: usize = (row1 + sx0) * 4;
10079 let i11: usize = (row1 + sx1) * 4;
10080 if i11 + 4 > src_len {
10081 continue;
10082 }
10083 let iwx: u32 = 256 - wx;
10084 let w00: u32 = iwx * iwy;
10085 let w10: u32 = wx * iwy;
10086 let w01: u32 = iwx * wy;
10087 let w11: u32 = wx * wy;
10088 let a00: u32 = src_bytes[i00 + 3] as u32;
10089 let a10: u32 = src_bytes[i10 + 3] as u32;
10090 let a01: u32 = src_bytes[i01 + 3] as u32;
10091 let a11: u32 = src_bytes[i11 + 3] as u32;
10092 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) =
10093 if (a00 & a10 & a01 & a11) == 255 {
10094 (
10095 ((src_bytes[i00] as u32) * w00
10096 + (src_bytes[i10] as u32) * w10
10097 + (src_bytes[i01] as u32) * w01
10098 + (src_bytes[i11] as u32) * w11
10099 + 32768)
10100 >> 16,
10101 ((src_bytes[i00 + 1] as u32) * w00
10102 + (src_bytes[i10 + 1] as u32) * w10
10103 + (src_bytes[i01 + 1] as u32) * w01
10104 + (src_bytes[i11 + 1] as u32) * w11
10105 + 32768)
10106 >> 16,
10107 ((src_bytes[i00 + 2] as u32) * w00
10108 + (src_bytes[i10 + 2] as u32) * w10
10109 + (src_bytes[i01 + 2] as u32) * w01
10110 + (src_bytes[i11 + 2] as u32) * w11
10111 + 32768)
10112 >> 16,
10113 255,
10114 )
10115 } else {
10116 let aw00: u64 = (a00 as u64) * (w00 as u64);
10117 let aw10: u64 = (a10 as u64) * (w10 as u64);
10118 let aw01: u64 = (a01 as u64) * (w01 as u64);
10119 let aw11: u64 = (a11 as u64) * (w11 as u64);
10120 let a_sum: u64 = aw00 + aw10 + aw01 + aw11;
10121 let a_out: u32 = ((a_sum + 32768) >> 16) as u32;
10122 if a_out == 0 || a_sum == 0 {
10123 continue;
10124 }
10125 let half_a: u64 = a_sum >> 1;
10126 (
10127 ((((src_bytes[i00] as u64) * aw00
10128 + (src_bytes[i10] as u64) * aw10
10129 + (src_bytes[i01] as u64) * aw01
10130 + (src_bytes[i11] as u64) * aw11
10131 + half_a)
10132 / a_sum)
10133 .min(255)) as u32,
10134 ((((src_bytes[i00 + 1] as u64) * aw00
10135 + (src_bytes[i10 + 1] as u64) * aw10
10136 + (src_bytes[i01 + 1] as u64) * aw01
10137 + (src_bytes[i11 + 1] as u64) * aw11
10138 + half_a)
10139 / a_sum)
10140 .min(255)) as u32,
10141 ((((src_bytes[i00 + 2] as u64) * aw00
10142 + (src_bytes[i10 + 2] as u64) * aw10
10143 + (src_bytes[i01 + 2] as u64) * aw01
10144 + (src_bytes[i11 + 2] as u64) * aw11
10145 + half_a)
10146 / a_sum)
10147 .min(255)) as u32,
10148 a_out,
10149 )
10150 };
10151 let rr: u32 = sr_raw * transform_val + 128;
10152 let gg: u32 = sg_raw * tg + 128;
10153 let bb: u32 = sb_raw * tb + 128;
10154 let aa_v: u32 = sa_raw * ta + 128;
10155 let radius_val: u32 = (rr + (rr >> 8)) >> 8;
10156 let geometry_val: u32 = (gg + (gg >> 8)) >> 8;
10157 let byte_val: u32 = (bb + (bb >> 8)) >> 8;
10158 let first_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
10159 if first_val == 255 {
10160 dp[0] = radius_val as u8;
10161 dp[1] = geometry_val as u8;
10162 dp[2] = byte_val as u8;
10163 dp[3] = 255;
10164 } else if first_val > 0 {
10165 let inv_a: u32 = 255 - first_val;
10166 let vr: u32 = radius_val * first_val + (dp[0] as u32) * inv_a + 128;
10167 let vg: u32 = geometry_val * first_val + (dp[1] as u32) * inv_a + 128;
10168 let vb: u32 = byte_val * first_val + (dp[2] as u32) * inv_a + 128;
10169 let va: u32 = (dp[3] as u32) * inv_a + 128;
10170 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
10171 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10172 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10173 dp[3] = (first_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
10174 }
10175 shaded += 1;
10176 }
10177 shaded
10178 }
10179
10180 fn raster_sprite_region_with_lut(
10196 band: &mut PixelBand<'_>,
10197 rects: (Rect, Rect),
10198 src_info: (u32, u32, &[u8]),
10199 bounds: (u32, u32, u32, u32),
10200 tint: Color,
10201 use_bilinear: bool,
10202 x_lut: &mut Vec<(usize, usize, u32)>,
10203 ) -> usize {
10204 let (rect, src_rect): (Rect, Rect) = rects;
10205 let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
10206 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
10207 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
10208 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
10209 let untinted: bool = tint == COLOR_WHITE;
10210 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
10211 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
10212 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
10213 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
10214 let buf_w_usize: usize = buf_w as usize;
10215 let rect_x: f32 = rect.get_x();
10216 let rect_y: f32 = rect.get_y();
10217 let src_x: f32 = src_rect.get_x();
10218 let src_y: f32 = src_rect.get_y();
10219 let src_w: f32 = src_rect.get_width();
10220 let src_h: f32 = src_rect.get_height();
10221 let min_sx_f: f32 = min_sx as f32;
10222 let max_sx_f: f32 = max_sx as f32;
10223 let min_sy_f: f32 = min_sy as f32;
10224 let max_sy_f: f32 = max_sy as f32;
10225 x_lut.clear();
10226 for pos_x in x0..x1 {
10227 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
10228 let fx: f32 = (src_x + tex_u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
10229 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
10230 let sx1: u32 = if use_bilinear {
10231 (sx0 + 1).min(max_sx)
10232 } else {
10233 sx0
10234 };
10235 let wx: u32 = if use_bilinear {
10236 ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10237 } else {
10238 0
10239 };
10240 x_lut.push((sx0 as usize, sx1 as usize, wx));
10241 }
10242 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
10243 let x0_u: usize = x0 as usize;
10244 let mut shaded: usize = 0;
10245 for pos_y in y0..y1 {
10246 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10247 continue;
10248 };
10249 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
10250 let fy: f32 = (src_y + item_val * src_h - 0.5).clamp(min_sy_f, max_sy_f);
10251 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
10252 let sy1: u32 = if use_bilinear {
10253 (sy0 + 1).min(max_sy)
10254 } else {
10255 sy0
10256 };
10257 let wy: u32 = if use_bilinear {
10258 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10259 } else {
10260 0
10261 };
10262 let y_params: (usize, usize, u32, u32) = (
10263 (sy0 as usize) * buf_w_usize,
10264 (sy1 as usize) * buf_w_usize,
10265 wy,
10266 256 - wy,
10267 );
10268 if untinted {
10269 shaded += Self::blit_bilinear_span_precomputed(
10270 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
10271 );
10272 } else {
10273 shaded += Self::blit_sprite_span_tinted(
10274 y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
10275 );
10276 }
10277 }
10278 shaded
10279 }
10280
10281 fn raster_sprite_region(
10297 band: &mut PixelBand<'_>,
10298 rect: Rect,
10299 buffer: &ImageBuffer,
10300 src_rect: Rect,
10301 tint: Color,
10302 clip: Rect,
10303 aa: AntialiasingMode,
10304 ) -> usize {
10305 if buffer.get_width() == 0
10306 || buffer.get_height() == 0
10307 || tint.get_alpha() == 0
10308 || src_rect.get_width() <= 0.0
10309 || src_rect.get_height() <= 0.0
10310 {
10311 return 0;
10312 }
10313 let Some(vis) = rect.intersect(clip) else {
10314 return 0;
10315 };
10316 let fb_w: u32 = band.width();
10317 let band_y0: u32 = band.y_offset();
10318 let band_y1: u32 = band.y_end();
10319 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
10320 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
10321 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
10322 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
10323 if x0 >= x1 || y0 >= y1 {
10324 return 0;
10325 }
10326 let buf_w: u32 = buffer.get_width();
10327 let buf_h: u32 = buffer.get_height();
10328 let src_bytes: &[u8] = buffer.get_pixels();
10329 let use_bilinear: bool = aa != AntialiasingMode::None
10330 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
10331 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
10332 if !use_bilinear
10333 && tint == COLOR_WHITE
10334 && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
10335 && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
10336 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
10337 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
10338 && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
10339 && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
10340 {
10341 let rx0_i: i32 = rect.get_x().round() as i32;
10342 let ry0_i: i32 = rect.get_y().round() as i32;
10343 let sx0_i: i32 = src_rect.get_x().round() as i32;
10344 let sy0_i: i32 = src_rect.get_y().round() as i32;
10345 let span_w: usize = (x1 - x0) as usize;
10346 let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
10347 let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
10348 let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
10349 if src_x0_i >= 0
10350 && src_x0_i + (span_w as i32) <= (buf_w as i32)
10351 && src_y0_i >= 0
10352 && src_y1_i <= (buf_h as i32)
10353 {
10354 let buf_w_u: usize = buf_w as usize;
10355 let dst_b0: usize = (x0 as usize) * 4;
10356 let dst_b1: usize = (x1 as usize) * 4;
10357 let src_x0_u: usize = src_x0_i as usize;
10358 for pos_y in y0..y1 {
10359 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10360 continue;
10361 };
10362 let sy: usize = (sy0_i + ((pos_y as i32) - ry0_i)) as usize;
10363 let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
10364 let src_b1: usize = src_b0 + span_w * 4;
10365 if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
10366 blit_1to1_rgba_span(
10367 &src_bytes[src_b0..src_b1],
10368 &mut dst_row[dst_b0..dst_b1],
10369 );
10370 }
10371 }
10372 return span_w * ((y1 - y0) as usize);
10373 }
10374 }
10375 let mut shaded: usize = 0;
10376 let ran_tls: bool = BAND_IMAGE_X_LUT
10377 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
10378 if let Ok(mut guard) = cell.try_borrow_mut() {
10379 shaded = Self::raster_sprite_region_with_lut(
10380 band,
10381 (rect, src_rect),
10382 (buf_w, buf_h, src_bytes),
10383 (x0, y0, x1, y1),
10384 tint,
10385 use_bilinear,
10386 &mut guard,
10387 );
10388 }
10389 })
10390 .is_ok();
10391 if !ran_tls {
10392 let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
10393 shaded = Self::raster_sprite_region_with_lut(
10394 band,
10395 (rect, src_rect),
10396 (buf_w, buf_h, src_bytes),
10397 (x0, y0, x1, y1),
10398 tint,
10399 use_bilinear,
10400 &mut fallback_lut,
10401 );
10402 }
10403 shaded
10404 }
10405}