1use crate::compositor::{DisplayList, DrawCommand};
4use std::fs::File;
5use std::io::Write;
6use std::path::Path;
7use strata_layout::Rect;
8use strata_style::effects::ClipPath;
9use strata_style::types::{BlendMode, BoxShadow, Color, ColorStop};
10
11#[inline(always)]
18pub fn sd_rounded_rect(px: f32, py: f32, half_w: f32, half_h: f32, r: f32) -> f32 {
19 let r = r.min(half_w).min(half_h).max(0.0);
20 let qx = px.abs() - half_w + r;
21 let qy = py.abs() - half_h + r;
22
23 let len = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
24 let inside = qx.max(qy).min(0.0);
25 len + inside - r
26}
27
28#[inline(always)]
30pub fn sdf_coverage(distance: f32) -> f32 {
31 (0.5 - distance).clamp(0.0, 1.0)
32}
33
34pub const SRGB_GAMMA: f32 = 2.2;
36
37#[inline]
39pub fn srgb_to_linear(v: u8) -> f32 {
40 let s = v as f32 / 255.0;
41 s.powf(SRGB_GAMMA)
42}
43
44#[inline]
46pub fn linear_to_srgb(l: f32) -> u8 {
47 let l_clamped = l.clamp(0.0, 1.0);
48 let s = l_clamped.powf(1.0 / SRGB_GAMMA);
49 (s * 255.0).round().clamp(0.0, 255.0) as u8
50}
51
52pub type Rasterizer = FrameBuffer;
54
55#[derive(Debug, Clone, PartialEq)]
57pub struct FrameBuffer {
58 pub width: usize,
59 pub height: usize,
60 pub pixels: Vec<u8>, pub clip_mask_stack: Vec<Vec<u8>>,
62}
63
64impl FrameBuffer {
65 pub fn new(width: usize, height: usize) -> Self {
67 Self {
68 width,
69 height,
70 pixels: vec![0; width * height * 4],
71 clip_mask_stack: Vec::new(),
72 }
73 }
74
75 pub fn clear(&mut self, color: Color) {
77 let (r, g, b, a) = color.to_rgba8();
78 for chunk in self.pixels.chunks_exact_mut(4) {
79 chunk[0] = r;
80 chunk[1] = g;
81 chunk[2] = b;
82 chunk[3] = a;
83 }
84 }
85
86 pub fn clear_rect(&mut self, rect: Rect, color: Color) {
88 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(rect, None);
89 let (r, g, b, a) = color.to_rgba8();
90 for y in min_y..max_y {
91 let row_start = (y * self.width + min_x) * 4;
92 let row_end = (y * self.width + max_x) * 4;
93 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
94 chunk[0] = r;
95 chunk[1] = g;
96 chunk[2] = b;
97 chunk[3] = a;
98 }
99 }
100 }
101
102 #[inline]
104 pub fn get_pixel(&self, x: usize, y: usize) -> Color {
105 if x >= self.width || y >= self.height {
106 return Color::TRANSPARENT;
107 }
108 let idx = (y * self.width + x) * 4;
109 Color::rgba(
110 self.pixels[idx],
111 self.pixels[idx + 1],
112 self.pixels[idx + 2],
113 self.pixels[idx + 3],
114 )
115 }
116
117 #[inline]
119 pub fn as_raw_bytes(&self) -> &[u8] {
120 &self.pixels
121 }
122
123 #[inline]
125 pub fn set_pixel(&mut self, x: usize, y: usize, mut src: Color) {
126 if x >= self.width || y >= self.height {
127 return;
128 }
129 if let Some(mask) = self.clip_mask_stack.last() {
130 let mask_val = mask[y * self.width + x];
131 if mask_val == 0 {
132 return;
133 }
134 if mask_val < 255 {
135 let cov = mask_val as f32 / 255.0;
136 src = Color::from_f32(src.r(), src.g(), src.b(), src.a() * cov);
137 }
138 }
139 let src_a = src.a();
140 if src_a <= 0.001 {
141 return;
142 }
143
144 let idx = (y * self.width + x) * 4;
145 let dst_r = self.pixels[idx] as f32 / 255.0;
146 let dst_g = self.pixels[idx + 1] as f32 / 255.0;
147 let dst_b = self.pixels[idx + 2] as f32 / 255.0;
148 let dst_a = self.pixels[idx + 3] as f32 / 255.0;
149
150 let out_a = src_a + dst_a * (1.0 - src_a);
151 if out_a > 1e-5 {
152 let out_r = (src.r() * src_a + dst_r * dst_a * (1.0 - src_a)) / out_a;
153 let out_g = (src.g() * src_a + dst_g * dst_a * (1.0 - src_a)) / out_a;
154 let out_b = (src.b() * src_a + dst_b * dst_a * (1.0 - src_a)) / out_a;
155
156 self.pixels[idx] = (out_r * 255.0).round() as u8;
157 self.pixels[idx + 1] = (out_g * 255.0).round() as u8;
158 self.pixels[idx + 2] = (out_b * 255.0).round() as u8;
159 self.pixels[idx + 3] = (out_a * 255.0).round() as u8;
160 }
161 }
162
163 pub fn blend_glyph_coverage(&mut self, x: usize, y: usize, color: Color, mut coverage: f32) {
168 if x >= self.width || y >= self.height || coverage <= 0.001 {
169 return;
170 }
171
172 if let Some(mask) = self.clip_mask_stack.last() {
173 let mask_val = mask[y * self.width + x];
174 if mask_val == 0 {
175 return;
176 }
177 if mask_val < 255 {
178 coverage *= mask_val as f32 / 255.0;
179 }
180 }
181
182 let src_a = (color.a() * coverage).clamp(0.0, 1.0);
183 if src_a <= 0.001 {
184 return;
185 }
186
187 let idx = (y * self.width + x) * 4;
188 let dst_r_byte = self.pixels[idx];
189 let dst_g_byte = self.pixels[idx + 1];
190 let dst_b_byte = self.pixels[idx + 2];
191 let dst_a = self.pixels[idx + 3] as f32 / 255.0;
192
193 let dst_r_lin = srgb_to_linear(dst_r_byte);
195 let dst_g_lin = srgb_to_linear(dst_g_byte);
196 let dst_b_lin = srgb_to_linear(dst_b_byte);
197
198 let (sr, sg, sb, _) = color.to_rgba8();
200 let src_r_lin = srgb_to_linear(sr);
201 let src_g_lin = srgb_to_linear(sg);
202 let src_b_lin = srgb_to_linear(sb);
203
204 let out_a = src_a + dst_a * (1.0 - src_a);
206 if out_a > 1e-5 {
207 let out_r_lin = (src_r_lin * src_a + dst_r_lin * dst_a * (1.0 - src_a)) / out_a;
208 let out_g_lin = (src_g_lin * src_a + dst_g_lin * dst_a * (1.0 - src_a)) / out_a;
209 let out_b_lin = (src_b_lin * src_a + dst_b_lin * dst_a * (1.0 - src_a)) / out_a;
210
211 self.pixels[idx] = linear_to_srgb(out_r_lin);
212 self.pixels[idx + 1] = linear_to_srgb(out_g_lin);
213 self.pixels[idx + 2] = linear_to_srgb(out_b_lin);
214 self.pixels[idx + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
215 }
216 }
217
218 pub fn draw_rect(&mut self, bounds: Rect, color: Color, clip: Option<Rect>) {
220 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
221
222 for y in min_y..max_y {
223 for x in min_x..max_x {
224 self.set_pixel(x, y, color);
225 }
226 }
227 }
228
229 pub fn draw_rounded_rect(
231 &mut self,
232 bounds: Rect,
233 color: Color,
234 radius: f32,
235 border_width: f32,
236 border_color: Option<Color>,
237 clip: Option<Rect>,
238 ) {
239 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
240 let center_x = bounds.x + bounds.width * 0.5;
241 let center_y = bounds.y + bounds.height * 0.5;
242 let half_w = bounds.width * 0.5;
243 let half_h = bounds.height * 0.5;
244
245 for y in min_y..max_y {
246 let py = y as f32 + 0.5 - center_y;
247 for x in min_x..max_x {
248 let px = x as f32 + 0.5 - center_x;
249
250 let d = sd_rounded_rect(px, py, half_w, half_h, radius);
251 let alpha = sdf_coverage(d);
252
253 if alpha > 0.0 {
254 if let Some(b_color) = border_color.filter(|_| border_width > 0.0) {
255 let inner_d = d + border_width;
256 let inner_alpha = sdf_coverage(inner_d);
257
258 let effective_color = Color::rgba(
260 (b_color.r() * 255.0) as u8,
261 (b_color.g() * 255.0) as u8,
262 (b_color.b() * 255.0) as u8,
263 (b_color.a() * alpha * (1.0 - inner_alpha) * 255.0) as u8,
264 );
265 self.set_pixel(x, y, effective_color);
266
267 let fill_color = Color::rgba(
268 (color.r() * 255.0) as u8,
269 (color.g() * 255.0) as u8,
270 (color.b() * 255.0) as u8,
271 (color.a() * inner_alpha * 255.0) as u8,
272 );
273 self.set_pixel(x, y, fill_color);
274 } else {
275 let blended = Color::rgba(
276 (color.r() * 255.0) as u8,
277 (color.g() * 255.0) as u8,
278 (color.b() * 255.0) as u8,
279 (color.a() * alpha * 255.0) as u8,
280 );
281 self.set_pixel(x, y, blended);
282 }
283 }
284 }
285 }
286 }
287
288 pub fn draw_shadow(&mut self, bounds: Rect, shadow: &BoxShadow, clip: Option<Rect>) {
290 if shadow.color.a() <= 0.001 {
291 return;
292 }
293
294 let shadow_bounds = Rect::new(
295 bounds.x + shadow.offset_x - shadow.spread_radius - shadow.blur_radius,
296 bounds.y + shadow.offset_y - shadow.spread_radius - shadow.blur_radius,
297 bounds.width + (shadow.spread_radius + shadow.blur_radius) * 2.0,
298 bounds.height + (shadow.spread_radius + shadow.blur_radius) * 2.0,
299 );
300
301 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(shadow_bounds, clip);
302 let center_x = bounds.x + shadow.offset_x + bounds.width * 0.5;
303 let center_y = bounds.y + shadow.offset_y + bounds.height * 0.5;
304 let half_w = bounds.width * 0.5 + shadow.spread_radius;
305 let half_h = bounds.height * 0.5 + shadow.spread_radius;
306
307 let blur = shadow.blur_radius.max(1.0);
308
309 for y in min_y..max_y {
310 let py = y as f32 + 0.5 - center_y;
311 for x in min_x..max_x {
312 let px = x as f32 + 0.5 - center_x;
313
314 let d = sd_rounded_rect(px, py, half_w, half_h, 0.0);
315 let alpha = (-d / blur).exp().clamp(0.0, 1.0) * shadow.color.a();
317
318 if alpha > 0.005 {
319 let c = Color::rgba(
320 (shadow.color.r() * 255.0) as u8,
321 (shadow.color.g() * 255.0) as u8,
322 (shadow.color.b() * 255.0) as u8,
323 (alpha * 255.0) as u8,
324 );
325 self.set_pixel(x, y, c);
326 }
327 }
328 }
329 }
330
331 pub fn draw_text(
333 &mut self,
334 origin: (f32, f32),
335 text: &str,
336 font_size: f32,
337 color: Color,
338 clip: Option<Rect>,
339 ) {
340 if color.a() <= 0.001 {
341 return;
342 }
343
344 let scale = (font_size / 16.0).max(0.65);
345 let char_w = 8.0 * scale;
346 let char_h = 16.0 * scale;
347
348 let mut cursor_x = origin.0;
349 let mut cursor_y = origin.1;
350
351 for ch in text.chars() {
352 if ch == '\n' {
353 cursor_y += char_h * 1.25;
354 cursor_x = origin.0;
355 continue;
356 }
357
358 let glyph = crate::font::get_glyph_or_fallback(ch);
359 if (scale - 1.0).abs() < 1e-4
360 && cursor_x.fract().abs() < 1e-4
361 && cursor_y.fract().abs() < 1e-4
362 {
363 let base_x = cursor_x.round() as usize;
364 let base_y = cursor_y.round() as usize;
365 for (row_idx, &row) in glyph.iter().enumerate() {
366 if row == 0 {
367 continue;
368 }
369 let y = base_y + row_idx;
370 if y >= self.height {
371 continue;
372 }
373 for col_idx in 0..8 {
374 if (row & (1 << (7 - col_idx))) != 0 {
375 let x = base_x + col_idx;
376 if x >= self.width {
377 continue;
378 }
379 if let Some(c) = clip {
380 if !c.contains_point(x as f32 + 0.5, y as f32 + 0.5) {
381 continue;
382 }
383 }
384 self.blend_glyph_coverage(x, y, color, 1.0);
385 }
386 }
387 }
388 } else {
389 let min_x = (cursor_x.floor() as isize).max(0).min(self.width as isize) as usize;
390 let max_x = ((cursor_x + char_w).ceil() as isize)
391 .max(0)
392 .min(self.width as isize) as usize;
393 let min_y = (cursor_y.floor() as isize).max(0).min(self.height as isize) as usize;
394 let max_y = ((cursor_y + char_h).ceil() as isize)
395 .max(0)
396 .min(self.height as isize) as usize;
397
398 for y in min_y..max_y {
399 let py = y as f32 + 0.5;
400 let gy = (py - cursor_y) / scale;
401 if gy < 0.0 || gy >= 16.0 {
402 continue;
403 }
404 let row_f = gy.clamp(0.0, 15.99);
405 let r0 = row_f.floor() as usize;
406 let r1 = (r0 + 1).min(15);
407 let fr = row_f - r0 as f32;
408
409 for x in min_x..max_x {
410 let px = x as f32 + 0.5;
411 let gx = (px - cursor_x) / scale;
412 if gx < 0.0 || gx >= 8.0 {
413 continue;
414 }
415 if let Some(c) = clip {
416 if !c.contains_point(px, py) {
417 continue;
418 }
419 }
420
421 let col_f = gx.clamp(0.0, 7.99);
422 let c0 = col_f.floor() as usize;
423 let c1 = (c0 + 1).min(7);
424 let fc = col_f - c0 as f32;
425
426 let b00 = if (glyph[r0] & (1 << (7 - c0))) != 0 {
427 1.0f32
428 } else {
429 0.0f32
430 };
431 let b10 = if (glyph[r0] & (1 << (7 - c1))) != 0 {
432 1.0f32
433 } else {
434 0.0f32
435 };
436 let b01 = if (glyph[r1] & (1 << (7 - c0))) != 0 {
437 1.0f32
438 } else {
439 0.0f32
440 };
441 let b11 = if (glyph[r1] & (1 << (7 - c1))) != 0 {
442 1.0f32
443 } else {
444 0.0f32
445 };
446
447 let top = b00 * (1.0 - fc) + b10 * fc;
448 let bot = b01 * (1.0 - fc) + b11 * fc;
449 let cov = top * (1.0 - fr) + bot * fr;
450
451 if cov > 0.01 {
452 self.blend_glyph_coverage(x, y, color, cov);
453 }
454 }
455 }
456 }
457 cursor_x += char_w;
458 }
459 }
460
461 pub fn apply_filter(&mut self, bounds: Rect, filter: &strata_style::effects::BackdropFilter) {
463 if filter.is_empty() {
464 return;
465 }
466 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, None);
467 if min_x >= max_x || min_y >= max_y {
468 return;
469 }
470
471 for op in &filter.operations {
472 match *op {
473 strata_style::effects::FilterOp::Brightness(factor) => {
474 for y in min_y..max_y {
475 let row_start = (y * self.width + min_x) * 4;
476 let row_end = (y * self.width + max_x) * 4;
477 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
478 chunk[0] = ((chunk[0] as f32 * factor).round() as u32).min(255) as u8;
479 chunk[1] = ((chunk[1] as f32 * factor).round() as u32).min(255) as u8;
480 chunk[2] = ((chunk[2] as f32 * factor).round() as u32).min(255) as u8;
481 }
482 }
483 }
484 strata_style::effects::FilterOp::Contrast(factor) => {
485 for y in min_y..max_y {
486 let row_start = (y * self.width + min_x) * 4;
487 let row_end = (y * self.width + max_x) * 4;
488 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
489 for ch in &mut chunk[..3] {
490 let norm = *ch as f32 / 255.0;
491 let adjusted = ((norm - 0.5) * factor + 0.5).clamp(0.0, 1.0);
492 *ch = (adjusted * 255.0).round() as u8;
493 }
494 }
495 }
496 }
497 strata_style::effects::FilterOp::Grayscale(amt) => {
498 let amt = amt.clamp(0.0, 1.0);
499 let inv = 1.0 - amt;
500 for y in min_y..max_y {
501 let row_start = (y * self.width + min_x) * 4;
502 let row_end = (y * self.width + max_x) * 4;
503 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
504 let r = chunk[0] as f32;
505 let g = chunk[1] as f32;
506 let b = chunk[2] as f32;
507 let gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
508 chunk[0] = (r * inv + gray * amt).round() as u8;
509 chunk[1] = (g * inv + gray * amt).round() as u8;
510 chunk[2] = (b * inv + gray * amt).round() as u8;
511 }
512 }
513 }
514 strata_style::effects::FilterOp::Invert(amt) => {
515 let amt = amt.clamp(0.0, 1.0);
516 let inv = 1.0 - amt;
517 for y in min_y..max_y {
518 let row_start = (y * self.width + min_x) * 4;
519 let row_end = (y * self.width + max_x) * 4;
520 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
521 chunk[0] = (chunk[0] as f32 * inv + (255 - chunk[0]) as f32 * amt)
522 .round() as u8;
523 chunk[1] = (chunk[1] as f32 * inv + (255 - chunk[1]) as f32 * amt)
524 .round() as u8;
525 chunk[2] = (chunk[2] as f32 * inv + (255 - chunk[2]) as f32 * amt)
526 .round() as u8;
527 }
528 }
529 }
530 strata_style::effects::FilterOp::Sepia(amt) => {
531 let amt = amt.clamp(0.0, 1.0);
532 let inv = 1.0 - amt;
533 for y in min_y..max_y {
534 let row_start = (y * self.width + min_x) * 4;
535 let row_end = (y * self.width + max_x) * 4;
536 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
537 let r = chunk[0] as f32;
538 let g = chunk[1] as f32;
539 let b = chunk[2] as f32;
540 let sr = (0.393 * r + 0.769 * g + 0.189 * b).min(255.0);
541 let sg = (0.349 * r + 0.686 * g + 0.168 * b).min(255.0);
542 let sb = (0.272 * r + 0.534 * g + 0.131 * b).min(255.0);
543 chunk[0] = (r * inv + sr * amt).round() as u8;
544 chunk[1] = (g * inv + sg * amt).round() as u8;
545 chunk[2] = (b * inv + sb * amt).round() as u8;
546 }
547 }
548 }
549 strata_style::effects::FilterOp::Opacity(amt) => {
550 let amt = amt.clamp(0.0, 1.0);
551 for y in min_y..max_y {
552 let row_start = (y * self.width + min_x) * 4;
553 let row_end = (y * self.width + max_x) * 4;
554 for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
555 chunk[3] = (chunk[3] as f32 * amt).round() as u8;
556 }
557 }
558 }
559 _ => {}
560 }
561 }
562 }
563
564 pub fn draw_circle(&mut self, cx: f32, cy: f32, radius: f32, color: Color, clip: Option<Rect>) {
566 if radius <= 0.0 || color.a() <= 0.001 {
567 return;
568 }
569 let bounds = Rect::new(cx - radius, cy - radius, radius * 2.0, radius * 2.0);
570 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
571
572 for y in min_y..max_y {
573 let py = y as f32 + 0.5 - cy;
574 for x in min_x..max_x {
575 let px = x as f32 + 0.5 - cx;
576 let d = (px * px + py * py).sqrt() - radius;
577 let cov = sdf_coverage(d);
578 if cov > 0.001 {
579 let mut blended = color;
580 let out_a = blended.a() * cov;
581 blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
582 self.set_pixel(x, y, blended);
583 }
584 }
585 }
586 }
587
588 pub fn draw_linear_gradient(
590 &mut self,
591 bounds: Rect,
592 angle_deg: f32,
593 stops: &[ColorStop],
594 radius: f32,
595 clip: Option<Rect>,
596 ) {
597 if stops.is_empty() || bounds.width <= 0.0 || bounds.height <= 0.0 {
598 return;
599 }
600 let norm_stops = normalize_color_stops(stops);
601 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
602 let center_x = bounds.x + bounds.width * 0.5;
603 let center_y = bounds.y + bounds.height * 0.5;
604 let half_w = bounds.width * 0.5;
605 let half_h = bounds.height * 0.5;
606
607 let rad = angle_deg.to_radians();
608 let dx = rad.sin();
609 let dy = -rad.cos();
610 let length = (bounds.width * dx.abs() + bounds.height * dy.abs()).max(1e-4);
611
612 for y in min_y..max_y {
613 let py = y as f32 + 0.5 - center_y;
614 for x in min_x..max_x {
615 let px = x as f32 + 0.5 - center_x;
616
617 let d = sd_rounded_rect(px, py, half_w, half_h, radius);
618 let cov = sdf_coverage(d);
619 if cov <= 0.001 {
620 continue;
621 }
622
623 let proj = px * dx + py * dy;
624 let t = (proj + length * 0.5) / length;
625 let col = sample_gradient(&norm_stops, t);
626
627 if cov >= 0.999 {
628 self.set_pixel(x, y, col);
629 } else {
630 let mut blended = col;
631 let out_a = blended.a() * cov;
632 blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
633 self.set_pixel(x, y, blended);
634 }
635 }
636 }
637 }
638
639 pub fn draw_radial_gradient(
641 &mut self,
642 bounds: Rect,
643 center: (f32, f32),
644 stops: &[ColorStop],
645 radius: f32,
646 clip: Option<Rect>,
647 ) {
648 if stops.is_empty() || bounds.width <= 0.0 || bounds.height <= 0.0 {
649 return;
650 }
651 let norm_stops = normalize_color_stops(stops);
652 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
653 let center_x = bounds.x + bounds.width * 0.5;
654 let center_y = bounds.y + bounds.height * 0.5;
655 let half_w = bounds.width * 0.5;
656 let half_h = bounds.height * 0.5;
657
658 let focal_x = if center.0 <= 1.0 {
659 bounds.x + bounds.width * center.0
660 } else {
661 center.0
662 };
663 let focal_y = if center.1 <= 1.0 {
664 bounds.y + bounds.height * center.1
665 } else {
666 center.1
667 };
668 let rx = half_w.max(1e-4);
669 let ry = half_h.max(1e-4);
670
671 for y in min_y..max_y {
672 let py = y as f32 + 0.5 - center_y;
673 let actual_y = y as f32 + 0.5;
674 for x in min_x..max_x {
675 let px = x as f32 + 0.5 - center_x;
676 let actual_x = x as f32 + 0.5;
677
678 let d = sd_rounded_rect(px, py, half_w, half_h, radius);
679 let cov = sdf_coverage(d);
680 if cov <= 0.001 {
681 continue;
682 }
683
684 let ndx = (actual_x - focal_x) / rx;
685 let ndy = (actual_y - focal_y) / ry;
686 let t = (ndx * ndx + ndy * ndy).sqrt();
687 let col = sample_gradient(&norm_stops, t);
688
689 if cov >= 0.999 {
690 self.set_pixel(x, y, col);
691 } else {
692 let mut blended = col;
693 let out_a = blended.a() * cov;
694 blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
695 self.set_pixel(x, y, blended);
696 }
697 }
698 }
699 }
700
701 pub fn draw_image(
703 &mut self,
704 bounds: Rect,
705 image: &strata_layout::ImageResource,
706 clip: Option<Rect>,
707 ) {
708 if bounds.width <= 0.0 || bounds.height <= 0.0 || image.width == 0 || image.height == 0 {
709 return;
710 }
711
712 let raw_pixels =
713 decode_or_get_rgba(&image.data, image.width as usize, image.height as usize);
714 let src_w = image.width as usize;
715 let src_h = image.height as usize;
716 if raw_pixels.len() < src_w * src_h * 4 {
717 return;
718 }
719
720 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
721
722 for y in min_y..max_y {
723 let v = ((y as f32 + 0.5 - bounds.y) / bounds.height * src_h as f32 - 0.5)
724 .clamp(0.0, (src_h - 1) as f32);
725 let y_low = v.floor() as usize;
726 let y_high = (y_low + 1).min(src_h - 1);
727 let fy = v - v.floor();
728
729 for x in min_x..max_x {
730 let u = ((x as f32 + 0.5 - bounds.x) / bounds.width * src_w as f32 - 0.5)
731 .clamp(0.0, (src_w - 1) as f32);
732 let x_low = u.floor() as usize;
733 let x_high = (x_low + 1).min(src_w - 1);
734 let fx = u - u.floor();
735
736 let idx_tl = (y_low * src_w + x_low) * 4;
737 let idx_tr = (y_low * src_w + x_high) * 4;
738 let idx_bl = (y_high * src_w + x_low) * 4;
739 let idx_br = (y_high * src_w + x_high) * 4;
740
741 let r_t = (raw_pixels[idx_tl] as f32 * (1.0 - fx) + raw_pixels[idx_tr] as f32 * fx)
742 / 255.0;
743 let g_t = (raw_pixels[idx_tl + 1] as f32 * (1.0 - fx)
744 + raw_pixels[idx_tr + 1] as f32 * fx)
745 / 255.0;
746 let b_t = (raw_pixels[idx_tl + 2] as f32 * (1.0 - fx)
747 + raw_pixels[idx_tr + 2] as f32 * fx)
748 / 255.0;
749 let a_t = (raw_pixels[idx_tl + 3] as f32 * (1.0 - fx)
750 + raw_pixels[idx_tr + 3] as f32 * fx)
751 / 255.0;
752
753 let r_b = (raw_pixels[idx_bl] as f32 * (1.0 - fx) + raw_pixels[idx_br] as f32 * fx)
754 / 255.0;
755 let g_b = (raw_pixels[idx_bl + 1] as f32 * (1.0 - fx)
756 + raw_pixels[idx_br + 1] as f32 * fx)
757 / 255.0;
758 let b_b = (raw_pixels[idx_bl + 2] as f32 * (1.0 - fx)
759 + raw_pixels[idx_br + 2] as f32 * fx)
760 / 255.0;
761 let a_b = (raw_pixels[idx_bl + 3] as f32 * (1.0 - fx)
762 + raw_pixels[idx_br + 3] as f32 * fx)
763 / 255.0;
764
765 let r = r_t * (1.0 - fy) + r_b * fy;
766 let g = g_t * (1.0 - fy) + g_b * fy;
767 let b = b_t * (1.0 - fy) + b_b * fy;
768 let a = a_t * (1.0 - fy) + a_b * fy;
769
770 self.set_pixel(x, y, Color::from_f32(r, g, b, a));
771 }
772 }
773 }
774
775 pub fn draw_svg_path(
777 &mut self,
778 bounds: Rect,
779 path_data: &str,
780 stroke_color: Option<Color>,
781 fill_color: Option<Color>,
782 stroke_width: f32,
783 stroke_linecap: strata_layout::StrokeLineCap,
784 stroke_linejoin: strata_layout::StrokeLineJoin,
785 stroke_dasharray: &[f32],
786 fill_rule: strata_layout::FillRule,
787 view_box: (f32, f32),
788 clip: Option<Rect>,
789 ) {
790 let path = strata_gpu_path::PathBuilder::from_svg(path_data);
791 let scale_x = if view_box.0 > 0.0 {
792 bounds.width / view_box.0
793 } else {
794 1.0
795 };
796 let scale_y = if view_box.1 > 0.0 {
797 bounds.height / view_box.1
798 } else {
799 1.0
800 };
801
802 let quads = path.to_quadratics(0.25);
803 if quads.is_empty() {
804 return;
805 }
806
807 let transformed_quads: Vec<strata_gpu_path::QuadraticBezier> = quads
808 .into_iter()
809 .map(|q| {
810 strata_gpu_path::QuadraticBezier::new(
811 strata_gpu_path::Point2D::new(
812 bounds.x + q.p0.x * scale_x,
813 bounds.y + q.p0.y * scale_y,
814 ),
815 strata_gpu_path::Point2D::new(
816 bounds.x + q.p1.x * scale_x,
817 bounds.y + q.p1.y * scale_y,
818 ),
819 strata_gpu_path::Point2D::new(
820 bounds.x + q.p2.x * scale_x,
821 bounds.y + q.p2.y * scale_y,
822 ),
823 )
824 })
825 .collect();
826
827 let gpu_fill_rule = match fill_rule {
828 strata_layout::FillRule::NonZero => strata_gpu_path::FillRule::NonZero,
829 strata_layout::FillRule::EvenOdd => strata_gpu_path::FillRule::EvenOdd,
830 };
831
832 if let Some(fc) = fill_color {
833 if fc.a() > 0.001 {
834 self.rasterize_curves_fill(&transformed_quads, bounds, fc, gpu_fill_rule, clip);
835 }
836 }
837
838 if let Some(sc) = stroke_color {
839 if sc.a() > 0.001 && stroke_width > 0.0 {
840 let cap = match stroke_linecap {
841 strata_layout::StrokeLineCap::Round => strata_gpu_path::LineCap::Round,
842 strata_layout::StrokeLineCap::Square => strata_gpu_path::LineCap::Square,
843 _ => strata_gpu_path::LineCap::Butt,
844 };
845 let join = match stroke_linejoin {
846 strata_layout::StrokeLineJoin::Round => strata_gpu_path::LineJoin::Round,
847 strata_layout::StrokeLineJoin::Bevel => strata_gpu_path::LineJoin::Bevel,
848 _ => strata_gpu_path::LineJoin::Miter,
849 };
850 let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
851 let stroke_opts = strata_gpu_path::StrokeOptions {
852 width: stroke_width * avg_scale,
853 miter_limit: 4.0,
854 cap,
855 join,
856 };
857 let inflated = Rect::new(
858 bounds.x - stroke_width * avg_scale,
859 bounds.y - stroke_width * avg_scale,
860 bounds.width + stroke_width * avg_scale * 2.0,
861 bounds.height + stroke_width * avg_scale * 2.0,
862 );
863 let has_dashes = stroke_dasharray.iter().any(|&d| d > 0.0);
864 if has_dashes {
865 let scaled_dashes: Vec<f32> =
866 stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
867 for dash_subpath in
868 strata_gpu_path::dash_quadratics(&transformed_quads, &scaled_dashes)
869 {
870 let stroked_quads = strata_gpu_path::expand_stroke_quadratics(
871 &dash_subpath,
872 &stroke_opts,
873 );
874 self.rasterize_curves_fill(
875 &stroked_quads,
876 inflated,
877 sc,
878 strata_gpu_path::FillRule::NonZero,
879 clip,
880 );
881 }
882 } else {
883 let stroked_quads = strata_gpu_path::expand_stroke_quadratics(
884 &transformed_quads,
885 &stroke_opts,
886 );
887 self.rasterize_curves_fill(
888 &stroked_quads,
889 inflated,
890 sc,
891 strata_gpu_path::FillRule::NonZero,
892 clip,
893 );
894 }
895 }
896 }
897 }
898
899 pub fn draw_gpu_path(
901 &mut self,
902 bounds: Rect,
903 path: &strata_gpu_path::Path,
904 stroke: Option<strata_gpu_path::StrokeOptions>,
905 fill_color: Option<Color>,
906 stroke_color: Option<Color>,
907 transform: Option<strata_primitives::geom::Matrix4x4>,
908 clip: Option<Rect>,
909 ) {
910 let quads = path.to_quadratics(0.25);
911 if quads.is_empty() {
912 return;
913 }
914
915 let transformed_quads: Vec<strata_gpu_path::QuadraticBezier> = quads
916 .into_iter()
917 .map(|q| {
918 let p0 = if let Some(ref m) = transform {
919 let (tx, ty) = m.transform_point(q.p0.x, q.p0.y);
920 strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
921 } else {
922 strata_gpu_path::Point2D::new(bounds.x + q.p0.x, bounds.y + q.p0.y)
923 };
924 let p1 = if let Some(ref m) = transform {
925 let (tx, ty) = m.transform_point(q.p1.x, q.p1.y);
926 strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
927 } else {
928 strata_gpu_path::Point2D::new(bounds.x + q.p1.x, bounds.y + q.p1.y)
929 };
930 let p2 = if let Some(ref m) = transform {
931 let (tx, ty) = m.transform_point(q.p2.x, q.p2.y);
932 strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
933 } else {
934 strata_gpu_path::Point2D::new(bounds.x + q.p2.x, bounds.y + q.p2.y)
935 };
936 strata_gpu_path::QuadraticBezier::new(p0, p1, p2)
937 })
938 .collect();
939
940 let path_fill_rule = path.fill_rule.unwrap_or(strata_gpu_path::FillRule::NonZero);
941 if let Some(fc) = fill_color {
942 if fc.a() > 0.001 {
943 self.rasterize_curves_fill(&transformed_quads, bounds, fc, path_fill_rule, clip);
944 }
945 }
946
947 if let Some(sc) = stroke_color {
948 if sc.a() > 0.001 {
949 let opts = stroke.unwrap_or_else(|| strata_gpu_path::StrokeOptions::new(1.0));
950 let stroked_quads =
951 strata_gpu_path::expand_stroke_quadratics(&transformed_quads, &opts);
952 let inflated = Rect::new(
953 bounds.x - opts.width,
954 bounds.y - opts.width,
955 bounds.width + opts.width * 2.0,
956 bounds.height + opts.width * 2.0,
957 );
958 self.rasterize_curves_fill(
959 &stroked_quads,
960 inflated,
961 sc,
962 strata_gpu_path::FillRule::NonZero,
963 clip,
964 );
965 }
966 }
967 }
968
969 fn rasterize_curves_fill(
970 &mut self,
971 curves: &[strata_gpu_path::QuadraticBezier],
972 bounds: Rect,
973 color: Color,
974 fill_rule: strata_gpu_path::FillRule,
975 clip: Option<Rect>,
976 ) {
977 if curves.is_empty() || color.a() <= 0.001 {
978 return;
979 }
980
981 let mut min_x_f = bounds.x;
982 let mut min_y_f = bounds.y;
983 let mut max_x_f = bounds.max_x();
984 let mut max_y_f = bounds.max_y();
985
986 for q in curves {
987 let bb = q.bounding_box();
988 min_x_f = min_x_f.min(bb.min_x);
989 min_y_f = min_y_f.min(bb.min_y);
990 max_x_f = max_x_f.max(bb.max_x);
991 max_y_f = max_y_f.max(bb.max_y);
992 }
993
994 let effective_bounds = Rect::new(min_x_f, min_y_f, max_x_f - min_x_f, max_y_f - min_y_f);
995 let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(effective_bounds, clip);
996
997 for y in min_y..max_y {
998 let py = y as f32;
999 for x in min_x..max_x {
1000 let px = x as f32;
1001 let mut hits = 0;
1002 let sub_offsets = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)];
1003 for (ox, oy) in sub_offsets {
1004 let pt = strata_gpu_path::Point2D::new(px + ox, py + oy);
1005 if strata_gpu_path::is_point_inside_closed_path_rule(pt, curves, fill_rule) {
1006 hits += 1;
1007 }
1008 }
1009 if hits > 0 {
1010 let cov = hits as f32 / 4.0;
1011 let mut blended = color;
1012 let out_a = blended.a() * cov;
1013 blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
1014 self.set_pixel(x, y, blended);
1015 }
1016 }
1017 }
1018 }
1019
1020 pub fn push_clip_path(&mut self, bounds: Rect, clip_path: &ClipPath) {
1022 let mut mask = vec![0u8; self.width * self.height];
1023
1024 match clip_path {
1025 ClipPath::None => {
1026 mask.fill(255);
1027 }
1028 ClipPath::Circle {
1029 radius,
1030 center_x,
1031 center_y,
1032 } => {
1033 let cx = bounds.x + center_x;
1034 let cy = bounds.y + center_y;
1035 let r = *radius;
1036 for y in 0..self.height {
1037 let py = y as f32 + 0.5 - cy;
1038 for x in 0..self.width {
1039 let px = x as f32 + 0.5 - cx;
1040 let d = (px * px + py * py).sqrt() - r;
1041 let cov = sdf_coverage(d);
1042 mask[y * self.width + x] = (cov * 255.0).round() as u8;
1043 }
1044 }
1045 }
1046 ClipPath::Ellipse {
1047 radius_x,
1048 radius_y,
1049 center_x,
1050 center_y,
1051 } => {
1052 let cx = bounds.x + center_x;
1053 let cy = bounds.y + center_y;
1054 let rx = (*radius_x).max(1e-4);
1055 let ry = (*radius_y).max(1e-4);
1056 for y in 0..self.height {
1057 let py = (y as f32 + 0.5 - cy) / ry;
1058 for x in 0..self.width {
1059 let px = (x as f32 + 0.5 - cx) / rx;
1060 let d = (px * px + py * py).sqrt() - 1.0;
1061 let cov = (0.5 - d * rx.min(ry)).clamp(0.0, 1.0);
1062 mask[y * self.width + x] = (cov * 255.0).round() as u8;
1063 }
1064 }
1065 }
1066 ClipPath::Inset {
1067 top,
1068 right,
1069 bottom,
1070 left,
1071 border_radius,
1072 } => {
1073 let ix = bounds.x + left;
1074 let iy = bounds.y + top;
1075 let iw = (bounds.width - left - right).max(0.0);
1076 let ih = (bounds.height - top - bottom).max(0.0);
1077 let half_w = iw * 0.5;
1078 let half_h = ih * 0.5;
1079 let cx = ix + half_w;
1080 let cy = iy + half_h;
1081 for y in 0..self.height {
1082 let py = y as f32 + 0.5 - cy;
1083 for x in 0..self.width {
1084 let px = x as f32 + 0.5 - cx;
1085 let d = sd_rounded_rect(px, py, half_w, half_h, *border_radius);
1086 let cov = sdf_coverage(d);
1087 mask[y * self.width + x] = (cov * 255.0).round() as u8;
1088 }
1089 }
1090 }
1091 ClipPath::Polygon(pts) => {
1092 if pts.len() >= 3 {
1093 let poly_pts: Vec<(f32, f32)> = pts
1094 .iter()
1095 .map(|p| (bounds.x + p.x, bounds.y + p.y))
1096 .collect();
1097 for y in 0..self.height {
1098 let py = y as f32 + 0.5;
1099 for x in 0..self.width {
1100 let px = x as f32 + 0.5;
1101 let mut inside = false;
1102 let n = poly_pts.len();
1103 let mut j = n - 1;
1104 for i in 0..n {
1105 let (xi, yi) = poly_pts[i];
1106 let (xj, yj) = poly_pts[j];
1107 if ((yi > py) != (yj > py))
1108 && (px < (xj - xi) * (py - yi) / (yj - yi) + xi)
1109 {
1110 inside = !inside;
1111 }
1112 j = i;
1113 }
1114 if inside {
1115 mask[y * self.width + x] = 255;
1116 }
1117 }
1118 }
1119 }
1120 }
1121 ClipPath::Path(svg_data) => {
1122 let path = strata_gpu_path::PathBuilder::from_svg(svg_data);
1123 let curves = path.to_quadratics(0.2);
1124 let offset_curves: Vec<strata_gpu_path::QuadraticBezier> = curves
1125 .into_iter()
1126 .map(|q| {
1127 strata_gpu_path::QuadraticBezier::new(
1128 strata_gpu_path::Point2D::new(q.p0.x + bounds.x, q.p0.y + bounds.y),
1129 strata_gpu_path::Point2D::new(q.p1.x + bounds.x, q.p1.y + bounds.y),
1130 strata_gpu_path::Point2D::new(q.p2.x + bounds.x, q.p2.y + bounds.y),
1131 )
1132 })
1133 .collect();
1134
1135 for y in 0..self.height {
1136 let py = y as f32 + 0.5;
1137 for x in 0..self.width {
1138 let pt = strata_gpu_path::Point2D::new(x as f32 + 0.5, py);
1139 if strata_gpu_path::is_point_inside_closed_path(pt, &offset_curves) {
1140 mask[y * self.width + x] = 255;
1141 }
1142 }
1143 }
1144 }
1145 }
1146
1147 if let Some(parent) = self.clip_mask_stack.last() {
1148 for i in 0..mask.len() {
1149 mask[i] = ((mask[i] as u16 * parent[i] as u16) / 255) as u8;
1150 }
1151 }
1152
1153 self.clip_mask_stack.push(mask);
1154 }
1155
1156 pub fn pop_clip_path(&mut self) {
1158 self.clip_mask_stack.pop();
1159 }
1160
1161 pub fn render_display_list(&mut self, list: &DisplayList) {
1163 self.execute_display_list(list);
1164 }
1165
1166 pub fn execute_display_list(&mut self, list: &DisplayList) {
1168 let full_bounds = Rect::new(0.0, 0.0, self.width as f32, self.height as f32);
1169 self.execute_display_list_damaged(list, full_bounds);
1170 }
1171
1172 pub fn rasterize_damaged(
1174 &mut self,
1175 list: &DisplayList,
1176 damage: &crate::compositor::DamageTracker,
1177 ) {
1178 let clusters = damage.cluster_damage_rects();
1179 if clusters.is_empty() {
1180 return;
1181 }
1182
1183 for damage_rect in clusters {
1184 self.execute_display_list_damaged(list, damage_rect);
1185 }
1186 }
1187
1188 pub fn execute_display_list_damaged(&mut self, list: &DisplayList, damage: Rect) {
1191 if damage.width <= 0.0 || damage.height <= 0.0 {
1192 return;
1193 }
1194
1195 let mut clip_stack: Vec<Rect> = Vec::new();
1196 let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
1197 let mut filter_stack: Vec<(Rect, strata_style::effects::BackdropFilter)> = Vec::new();
1198 let mut layer_stack: Vec<LayerState> = Vec::new();
1199
1200 for cmd in list.commands() {
1201 match cmd {
1203 DrawCommand::PushClip { bounds, .. } => {
1204 let combined = match clip_stack.last() {
1205 Some(prev) => prev
1206 .intersect(*bounds)
1207 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
1208 None => *bounds,
1209 };
1210 clip_stack.push(combined);
1211 continue;
1212 }
1213 DrawCommand::PopClip => {
1214 clip_stack.pop();
1215 continue;
1216 }
1217 DrawCommand::PushTransform { matrix } => {
1218 let combined = match transform_stack.last() {
1219 Some(prev) => prev.multiply(matrix),
1220 None => *matrix,
1221 };
1222 transform_stack.push(combined);
1223 continue;
1224 }
1225 DrawCommand::PopTransform => {
1226 transform_stack.pop();
1227 continue;
1228 }
1229 DrawCommand::PushFilter { bounds, filter } => {
1230 filter_stack.push((*bounds, filter.clone()));
1231 continue;
1232 }
1233 DrawCommand::PopFilter => {
1234 if let Some((bounds, filter)) = filter_stack.pop() {
1235 let active_matrix = transform_stack.last();
1236 let tb = if let Some(mat) = active_matrix {
1237 if !mat.is_identity() {
1238 let (x, y, w, h) = mat.transform_bounds(
1239 bounds.x,
1240 bounds.y,
1241 bounds.width,
1242 bounds.height,
1243 );
1244 Rect::new(x, y, w, h)
1245 } else {
1246 bounds
1247 }
1248 } else {
1249 bounds
1250 };
1251 let target = if let Some(top) = layer_stack.last_mut() {
1252 &mut top.buffer
1253 } else {
1254 &mut *self
1255 };
1256 target.apply_filter(tb, &filter);
1257 }
1258 continue;
1259 }
1260 DrawCommand::PushBackdropFilter { .. } => {
1261 continue;
1262 }
1263 DrawCommand::PopBackdropFilter => {
1264 continue;
1265 }
1266 DrawCommand::PushOpacity { alpha } => {
1267 layer_stack.push(LayerState {
1268 buffer: FrameBuffer::new(self.width, self.height),
1269 opacity: *alpha,
1270 blend_mode: BlendMode::Normal,
1271 });
1272 continue;
1273 }
1274 DrawCommand::PopOpacity => {
1275 if let Some(popped) = layer_stack.pop() {
1276 let effective_clip = match clip_stack.last() {
1277 Some(prev) => prev.intersect(damage),
1278 None => Some(damage),
1279 };
1280 let target = if let Some(top) = layer_stack.last_mut() {
1281 &mut top.buffer
1282 } else {
1283 &mut *self
1284 };
1285 composite_layer(
1286 target,
1287 &popped.buffer,
1288 popped.opacity,
1289 popped.blend_mode,
1290 effective_clip,
1291 );
1292 }
1293 continue;
1294 }
1295 DrawCommand::PushBlendMode { mode } => {
1296 layer_stack.push(LayerState {
1297 buffer: FrameBuffer::new(self.width, self.height),
1298 opacity: 1.0,
1299 blend_mode: *mode,
1300 });
1301 continue;
1302 }
1303 DrawCommand::PopBlendMode => {
1304 if let Some(popped) = layer_stack.pop() {
1305 let effective_clip = match clip_stack.last() {
1306 Some(prev) => prev.intersect(damage),
1307 None => Some(damage),
1308 };
1309 let target = if let Some(top) = layer_stack.last_mut() {
1310 &mut top.buffer
1311 } else {
1312 &mut *self
1313 };
1314 composite_layer(
1315 target,
1316 &popped.buffer,
1317 popped.opacity,
1318 popped.blend_mode,
1319 effective_clip,
1320 );
1321 }
1322 continue;
1323 }
1324 DrawCommand::PushIsolation { .. } => {
1325 layer_stack.push(LayerState {
1326 buffer: FrameBuffer::new(self.width, self.height),
1327 opacity: 1.0,
1328 blend_mode: BlendMode::Normal,
1329 });
1330 continue;
1331 }
1332 DrawCommand::PopIsolation => {
1333 if let Some(popped) = layer_stack.pop() {
1334 let effective_clip = match clip_stack.last() {
1335 Some(prev) => prev.intersect(damage),
1336 None => Some(damage),
1337 };
1338 let target = if let Some(top) = layer_stack.last_mut() {
1339 &mut top.buffer
1340 } else {
1341 &mut *self
1342 };
1343 composite_layer(
1344 target,
1345 &popped.buffer,
1346 popped.opacity,
1347 popped.blend_mode,
1348 effective_clip,
1349 );
1350 }
1351 continue;
1352 }
1353 DrawCommand::PushClipPath { bounds, clip_path } => {
1354 let active_matrix = transform_stack.last();
1355 let tb = if let Some(mat) = active_matrix {
1356 if !mat.is_identity() {
1357 let (x, y, w, h) = mat.transform_bounds(
1358 bounds.x,
1359 bounds.y,
1360 bounds.width,
1361 bounds.height,
1362 );
1363 Rect::new(x, y, w, h)
1364 } else {
1365 *bounds
1366 }
1367 } else {
1368 *bounds
1369 };
1370 let target = if let Some(top) = layer_stack.last_mut() {
1371 &mut top.buffer
1372 } else {
1373 &mut *self
1374 };
1375 target.push_clip_path(tb, clip_path);
1376 continue;
1377 }
1378 DrawCommand::PopClipPath => {
1379 let target = if let Some(top) = layer_stack.last_mut() {
1380 &mut top.buffer
1381 } else {
1382 &mut *self
1383 };
1384 target.pop_clip_path();
1385 continue;
1386 }
1387 _ => {}
1388 }
1389
1390 let effective_clip = match clip_stack.last() {
1392 Some(prev) => match prev.intersect(damage) {
1393 Some(c) => c,
1394 None => continue,
1395 },
1396 None => damage,
1397 };
1398
1399 let active_matrix = transform_stack.last();
1400 let transform_rect_fn = |r: Rect| -> Rect {
1401 if let Some(mat) = active_matrix {
1402 if !mat.is_identity() {
1403 let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
1404 return Rect::new(x, y, w, h);
1405 }
1406 }
1407 r
1408 };
1409
1410 let transformed_cmd_bounds = cmd.bounds().map(transform_rect_fn);
1412 if let Some(cmd_bounds) = transformed_cmd_bounds {
1413 if cmd_bounds.intersect(effective_clip).is_none() {
1414 continue;
1415 }
1416 }
1417
1418 let target = if let Some(top) = layer_stack.last_mut() {
1420 &mut top.buffer
1421 } else {
1422 &mut *self
1423 };
1424
1425 match cmd {
1426 DrawCommand::DrawRect { bounds, color } => {
1427 target.draw_rect(transform_rect_fn(*bounds), *color, Some(effective_clip));
1428 }
1429 DrawCommand::DrawRoundedRect {
1430 bounds,
1431 color,
1432 border_radius,
1433 border_width,
1434 border_color,
1435 } => {
1436 target.draw_rounded_rect(
1437 transform_rect_fn(*bounds),
1438 *color,
1439 border_radius.top_left,
1440 border_width.top,
1441 *border_color,
1442 Some(effective_clip),
1443 );
1444 }
1445 DrawCommand::DrawShadow { bounds, shadow, .. } => {
1446 target.draw_shadow(transform_rect_fn(*bounds), shadow, Some(effective_clip));
1447 }
1448 DrawCommand::DrawBorder {
1449 bounds,
1450 widths,
1451 color,
1452 border_radius,
1453 ..
1454 } => {
1455 target.draw_rounded_rect(
1456 transform_rect_fn(*bounds),
1457 Color::TRANSPARENT,
1458 border_radius.top_left,
1459 widths.top,
1460 Some(*color),
1461 Some(effective_clip),
1462 );
1463 }
1464 DrawCommand::DrawText {
1465 origin,
1466 bounds_width,
1467 bounds_height,
1468 text_align,
1469 text,
1470 font_size,
1471 line_height,
1472 color,
1473 ..
1474 } => {
1475 let scale = (*font_size / 16.0).max(0.65);
1476 let char_w = 8.0 * scale;
1477 let step_y = crate::compositor::effective_draw_text_line_height(
1478 *font_size,
1479 *line_height,
1480 );
1481 let (lines, start_y_off) = crate::compositor::layout_draw_text_lines(
1482 text,
1483 *bounds_width,
1484 *bounds_height,
1485 *font_size,
1486 *line_height,
1487 *text_align,
1488 |_| char_w,
1489 );
1490 for (line_idx, (line_ox, line_str)) in lines.into_iter().enumerate() {
1491 let lx = origin.0 + line_ox;
1492 let ly = origin.1 + start_y_off + line_idx as f32 * step_y;
1493 let (ox, oy) = if let Some(m) = active_matrix {
1494 m.transform_point(lx, ly)
1495 } else {
1496 (lx, ly)
1497 };
1498 target.draw_text(
1499 (ox, oy),
1500 line_str,
1501 *font_size,
1502 *color,
1503 Some(effective_clip),
1504 );
1505 }
1506 }
1507 DrawCommand::DrawViewport3D { bounds, scene } => {
1508 crate::rasterizer3d::render_scene_3d_with_textures(
1509 target,
1510 transform_rect_fn(*bounds),
1511 scene,
1512 Some(effective_clip),
1513 scene.textures_deref(),
1514 );
1515 }
1516 DrawCommand::DrawCanvas2D { bounds, commands } => {
1517 let tb = transform_rect_fn(*bounds);
1518 crate::canvas2d::rasterize_canvas_commands(
1519 target,
1520 commands,
1521 tb.x,
1522 tb.y,
1523 Some(effective_clip),
1524 );
1525 }
1526 DrawCommand::DrawTextFragments { fragments } => {
1527 for frag in fragments {
1528 if !frag.text.is_empty() {
1529 let fb = transform_rect_fn(frag.bounds);
1530 target.draw_text(
1531 (fb.x, fb.y),
1532 &frag.text,
1533 frag.style.font_size,
1534 frag.style.color,
1535 Some(effective_clip),
1536 );
1537 }
1538 }
1539 }
1540 DrawCommand::DrawInsetShadow { bounds, shadow, .. } => {
1541 target.draw_shadow(transform_rect_fn(*bounds), shadow, Some(effective_clip));
1542 }
1543 DrawCommand::DrawLinearGradient {
1544 bounds,
1545 angle_deg,
1546 stops,
1547 border_radius,
1548 } => {
1549 target.draw_linear_gradient(
1550 transform_rect_fn(*bounds),
1551 *angle_deg,
1552 stops,
1553 border_radius.top_left,
1554 Some(effective_clip),
1555 );
1556 }
1557 DrawCommand::DrawRadialGradient {
1558 bounds,
1559 center,
1560 stops,
1561 border_radius,
1562 } => {
1563 target.draw_radial_gradient(
1564 transform_rect_fn(*bounds),
1565 *center,
1566 stops,
1567 border_radius.top_left,
1568 Some(effective_clip),
1569 );
1570 }
1571 DrawCommand::DrawImage { bounds, image } => {
1572 target.draw_image(transform_rect_fn(*bounds), image, Some(effective_clip));
1573 }
1574 DrawCommand::DrawSvgPath {
1575 bounds,
1576 path_data,
1577 stroke_color,
1578 fill_color,
1579 stroke_width,
1580 stroke_linecap,
1581 stroke_linejoin,
1582 stroke_dasharray,
1583 fill_rule,
1584 view_box,
1585 } => {
1586 target.draw_svg_path(
1587 transform_rect_fn(*bounds),
1588 path_data,
1589 *stroke_color,
1590 *fill_color,
1591 *stroke_width,
1592 *stroke_linecap,
1593 *stroke_linejoin,
1594 stroke_dasharray,
1595 *fill_rule,
1596 *view_box,
1597 Some(effective_clip),
1598 );
1599 }
1600 DrawCommand::DrawGpuPath {
1601 bounds,
1602 path,
1603 stroke,
1604 fill_color,
1605 stroke_color,
1606 transform,
1607 } => {
1608 let mut combined_transform = *transform;
1609 if let Some(m) = active_matrix {
1610 combined_transform = Some(match combined_transform {
1611 Some(t) => m.multiply(&t),
1612 None => *m,
1613 });
1614 }
1615 target.draw_gpu_path(
1616 transform_rect_fn(*bounds),
1617 path,
1618 *stroke,
1619 *fill_color,
1620 *stroke_color,
1621 combined_transform,
1622 Some(effective_clip),
1623 );
1624 }
1625 _ => {}
1626 }
1627 }
1628
1629 while let Some(popped) = layer_stack.pop() {
1631 let target = if let Some(top) = layer_stack.last_mut() {
1632 &mut top.buffer
1633 } else {
1634 &mut *self
1635 };
1636 composite_layer(
1637 target,
1638 &popped.buffer,
1639 popped.opacity,
1640 popped.blend_mode,
1641 None,
1642 );
1643 }
1644 }
1645
1646 fn compute_clamped_bounds(
1647 &self,
1648 bounds: Rect,
1649 clip: Option<Rect>,
1650 ) -> (usize, usize, usize, usize) {
1651 let rect = match clip {
1652 Some(c) => bounds.intersect(c).unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
1653 None => bounds,
1654 };
1655
1656 let min_x = (rect.x.floor() as isize).max(0).min(self.width as isize) as usize;
1657 let max_x = (rect.max_x().ceil() as isize)
1658 .max(0)
1659 .min(self.width as isize) as usize;
1660 let min_y = (rect.y.floor() as isize).max(0).min(self.height as isize) as usize;
1661 let max_y = (rect.max_y().ceil() as isize)
1662 .max(0)
1663 .min(self.height as isize) as usize;
1664
1665 (min_x, max_x, min_y, max_y)
1666 }
1667
1668 pub fn to_png_bytes(&self) -> Result<Vec<u8>, String> {
1670 if self.width == 0 || self.height == 0 {
1671 return Err("FrameBuffer dimensions must be non-zero to encode PNG".to_string());
1672 }
1673
1674 let mut out = Vec::new();
1675 out.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
1677
1678 let mut ihdr_data = Vec::with_capacity(13);
1680 ihdr_data.extend_from_slice(&(self.width as u32).to_be_bytes());
1681 ihdr_data.extend_from_slice(&(self.height as u32).to_be_bytes());
1682 ihdr_data.push(8); ihdr_data.push(6); ihdr_data.push(0); ihdr_data.push(0); ihdr_data.push(0); write_png_chunk(&mut out, b"IHDR", &ihdr_data);
1688
1689 let row_stride = self.width * 4;
1691 let mut raw_scanlines = Vec::with_capacity(self.height * (1 + row_stride));
1692 for y in 0..self.height {
1693 raw_scanlines.push(0); let row_start = y * row_stride;
1695 raw_scanlines.extend_from_slice(&self.pixels[row_start..row_start + row_stride]);
1696 }
1697
1698 let mut deflate_stream = Vec::new();
1700 deflate_stream.push(0x78); deflate_stream.push(0x01); const CHUNK_SIZE: usize = 65535;
1704 let total = raw_scanlines.len();
1705 let mut offset = 0;
1706 while offset < total {
1707 let chunk_len = (total - offset).min(CHUNK_SIZE);
1708 let is_last = (offset + chunk_len) >= total;
1709 let bfinal_btype: u8 = if is_last { 0x01 } else { 0x00 };
1710 deflate_stream.push(bfinal_btype);
1711
1712 let len_u16 = chunk_len as u16;
1713 let nlen_u16 = !len_u16;
1714 deflate_stream.extend_from_slice(&len_u16.to_le_bytes());
1715 deflate_stream.extend_from_slice(&nlen_u16.to_le_bytes());
1716 deflate_stream.extend_from_slice(&raw_scanlines[offset..offset + chunk_len]);
1717 offset += chunk_len;
1718 }
1719
1720 let adler = adler32(&raw_scanlines);
1721 deflate_stream.extend_from_slice(&adler.to_be_bytes());
1722
1723 write_png_chunk(&mut out, b"IDAT", &deflate_stream);
1725
1726 write_png_chunk(&mut out, b"IEND", &[]);
1728
1729 Ok(out)
1730 }
1731
1732 pub fn export_png<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
1734 let bytes = self.to_png_bytes().map_err(std::io::Error::other)?;
1735 let mut file = File::create(path)?;
1736 file.write_all(&bytes)?;
1737 file.flush()?;
1738 Ok(())
1739 }
1740
1741 #[allow(clippy::needless_range_loop)]
1743 pub fn compute_phash(&self) -> u64 {
1744 if self.width == 0 || self.height == 0 {
1745 return 0;
1746 }
1747
1748 let mut grid = [[0.0f32; 9]; 8];
1749 for y in 0..8 {
1750 for x in 0..9 {
1751 let px = (((x as f32 + 0.5) * self.width as f32 / 9.0).floor() as usize)
1752 .min(self.width - 1);
1753 let py = (((y as f32 + 0.5) * self.height as f32 / 8.0).floor() as usize)
1754 .min(self.height - 1);
1755 let idx = (py * self.width + px) * 4;
1756 let r = self.pixels[idx] as f32;
1757 let g = self.pixels[idx + 1] as f32;
1758 let b = self.pixels[idx + 2] as f32;
1759 grid[y][x] = 0.299 * r + 0.587 * g + 0.114 * b;
1760 }
1761 }
1762
1763 let mut hash = 0u64;
1764 for y in 0..8 {
1765 for x in 0..8 {
1766 if grid[y][x] > grid[y][x + 1] {
1767 hash |= 1u64 << (y * 8 + x);
1768 }
1769 }
1770 }
1771 hash
1772 }
1773
1774 pub fn phash_distance(hash_a: u64, hash_b: u64) -> u32 {
1776 (hash_a ^ hash_b).count_ones()
1777 }
1778}
1779
1780const CRC_TABLE: [u32; 256] = {
1781 let mut table = [0u32; 256];
1782 let mut i = 0;
1783 while i < 256 {
1784 let mut crc = i as u32;
1785 let mut j = 0;
1786 while j < 8 {
1787 if crc & 1 != 0 {
1788 crc = (crc >> 1) ^ 0xEDB8_8320;
1789 } else {
1790 crc >>= 1;
1791 }
1792 j += 1;
1793 }
1794 table[i] = crc;
1795 i += 1;
1796 }
1797 table
1798};
1799
1800fn adler32(data: &[u8]) -> u32 {
1801 let mut s1 = 1u32;
1802 let mut s2 = 0u32;
1803 for &b in data {
1804 s1 = (s1 + b as u32) % 65521;
1805 s2 = (s2 + s1) % 65521;
1806 }
1807 (s2 << 16) | s1
1808}
1809
1810fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
1811 out.extend_from_slice(&(data.len() as u32).to_be_bytes());
1812 out.extend_from_slice(chunk_type);
1813 out.extend_from_slice(data);
1814
1815 let mut crc = 0xFFFF_FFFFu32;
1816 for &byte in chunk_type {
1817 let idx = ((crc ^ (byte as u32)) & 0xFF) as usize;
1818 crc = (crc >> 8) ^ CRC_TABLE[idx];
1819 }
1820 for &byte in data {
1821 let idx = ((crc ^ (byte as u32)) & 0xFF) as usize;
1822 crc = (crc >> 8) ^ CRC_TABLE[idx];
1823 }
1824 let final_crc = !crc;
1825 out.extend_from_slice(&final_crc.to_be_bytes());
1826}
1827
1828struct LayerState {
1829 buffer: FrameBuffer,
1830 opacity: f32,
1831 blend_mode: BlendMode,
1832}
1833
1834fn composite_layer(
1835 dst: &mut FrameBuffer,
1836 src: &FrameBuffer,
1837 opacity: f32,
1838 blend_mode: BlendMode,
1839 clip: Option<Rect>,
1840) {
1841 if opacity <= 0.0 {
1842 return;
1843 }
1844 let opacity = opacity.clamp(0.0, 1.0);
1845 let (min_x, max_x, min_y, max_y) = if let Some(c) = clip {
1846 dst.compute_clamped_bounds(c, None)
1847 } else {
1848 (0, dst.width.min(src.width), 0, dst.height.min(src.height))
1849 };
1850
1851 for y in min_y..max_y {
1852 for x in min_x..max_x {
1853 let src_idx = (y * src.width + x) * 4;
1854 let src_raw_a = src.pixels[src_idx + 3] as f32 / 255.0;
1855 if src_raw_a <= 0.001 {
1856 continue;
1857 }
1858
1859 let clip_cov = if let Some(mask) = dst.clip_mask_stack.last() {
1860 mask[y * dst.width + x] as f32 / 255.0
1861 } else {
1862 1.0
1863 };
1864 if clip_cov <= 0.001 {
1865 continue;
1866 }
1867
1868 let cs_r = src.pixels[src_idx] as f32 / 255.0;
1869 let cs_g = src.pixels[src_idx + 1] as f32 / 255.0;
1870 let cs_b = src.pixels[src_idx + 2] as f32 / 255.0;
1871 let alpha_s = (src_raw_a * opacity * clip_cov).clamp(0.0, 1.0);
1872
1873 let dst_idx = (y * dst.width + x) * 4;
1874 let cb_r = dst.pixels[dst_idx] as f32 / 255.0;
1875 let cb_g = dst.pixels[dst_idx + 1] as f32 / 255.0;
1876 let cb_b = dst.pixels[dst_idx + 2] as f32 / 255.0;
1877 let alpha_b = dst.pixels[dst_idx + 3] as f32 / 255.0;
1878
1879 let b_r = blend_channel(cb_r, cs_r, blend_mode);
1880 let b_g = blend_channel(cb_g, cs_g, blend_mode);
1881 let b_b = blend_channel(cb_b, cs_b, blend_mode);
1882
1883 let alpha_o = alpha_s + alpha_b * (1.0 - alpha_s);
1884 if alpha_o > 1e-5 {
1885 let out_r = ((1.0 - alpha_b) * alpha_s * cs_r
1886 + (1.0 - alpha_s) * alpha_b * cb_r
1887 + alpha_b * alpha_s * b_r)
1888 / alpha_o;
1889 let out_g = ((1.0 - alpha_b) * alpha_s * cs_g
1890 + (1.0 - alpha_s) * alpha_b * cb_g
1891 + alpha_b * alpha_s * b_g)
1892 / alpha_o;
1893 let out_b = ((1.0 - alpha_b) * alpha_s * cs_b
1894 + (1.0 - alpha_s) * alpha_b * cb_b
1895 + alpha_b * alpha_s * b_b)
1896 / alpha_o;
1897
1898 dst.pixels[dst_idx] = (out_r.clamp(0.0, 1.0) * 255.0).round() as u8;
1899 dst.pixels[dst_idx + 1] = (out_g.clamp(0.0, 1.0) * 255.0).round() as u8;
1900 dst.pixels[dst_idx + 2] = (out_b.clamp(0.0, 1.0) * 255.0).round() as u8;
1901 dst.pixels[dst_idx + 3] = (alpha_o.clamp(0.0, 1.0) * 255.0).round() as u8;
1902 }
1903 }
1904 }
1905}
1906
1907fn blend_channel(cb: f32, cs: f32, mode: BlendMode) -> f32 {
1908 match mode {
1909 BlendMode::Normal => cs,
1910 BlendMode::Multiply => cb * cs,
1911 BlendMode::Screen => cb + cs - cb * cs,
1912 BlendMode::Darken => cb.min(cs),
1913 BlendMode::Lighten => cb.max(cs),
1914 BlendMode::Difference => (cb - cs).abs(),
1915 BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,
1916 BlendMode::Overlay => {
1917 if cb <= 0.5 {
1918 2.0 * cb * cs
1919 } else {
1920 1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
1921 }
1922 }
1923 BlendMode::HardLight => {
1924 if cs <= 0.5 {
1925 2.0 * cb * cs
1926 } else {
1927 1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
1928 }
1929 }
1930 BlendMode::SoftLight => {
1931 if cs <= 0.5 {
1932 cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
1933 } else {
1934 let d = if cb <= 0.25 {
1935 ((16.0 * cb - 12.0) * cb + 4.0) * cb
1936 } else {
1937 cb.sqrt()
1938 };
1939 cb + (2.0 * cs - 1.0) * (d - cb)
1940 }
1941 }
1942 BlendMode::ColorDodge => {
1943 if cb == 0.0 {
1944 0.0
1945 } else if cs >= 1.0 {
1946 1.0
1947 } else {
1948 (cb / (1.0 - cs)).min(1.0)
1949 }
1950 }
1951 BlendMode::ColorBurn => {
1952 if cb >= 1.0 {
1953 1.0
1954 } else if cs <= 0.0 {
1955 0.0
1956 } else {
1957 1.0 - ((1.0 - cb) / cs).min(1.0)
1958 }
1959 }
1960 _ => cs,
1961 }
1962}
1963
1964fn normalize_color_stops(stops: &[ColorStop]) -> Vec<(f32, Color)> {
1965 if stops.is_empty() {
1966 return Vec::new();
1967 }
1968 if stops.len() == 1 {
1969 return vec![(0.0, stops[0].color), (1.0, stops[0].color)];
1970 }
1971
1972 let mut result: Vec<(f32, Color)> = stops
1973 .iter()
1974 .map(|s| (s.position.unwrap_or(-1.0), s.color))
1975 .collect();
1976
1977 if result[0].0 < 0.0 {
1979 result[0].0 = 0.0;
1980 }
1981 let last_idx = result.len() - 1;
1983 if result[last_idx].0 < 0.0 {
1984 result[last_idx].0 = 1.0;
1985 }
1986
1987 let mut i = 0;
1989 while i < result.len() {
1990 if result[i].0 < 0.0 {
1991 let start_idx = i - 1;
1992 let start_pos = result[start_idx].0;
1993 let mut end_idx = i;
1994 while end_idx < result.len() && result[end_idx].0 < 0.0 {
1995 end_idx += 1;
1996 }
1997 let end_pos = if end_idx < result.len() {
1998 result[end_idx].0
1999 } else {
2000 1.0
2001 };
2002 let count = (end_idx - start_idx) as f32;
2003 let step = (end_pos - start_pos) / count;
2004 for (k, entry) in result[(start_idx + 1)..end_idx].iter_mut().enumerate() {
2005 entry.0 = start_pos + step * (k + 1) as f32;
2006 }
2007 i = end_idx;
2008 } else {
2009 i += 1;
2010 }
2011 }
2012
2013 let mut current_max = 0.0f32;
2015 for entry in &mut result {
2016 if entry.0 < current_max {
2017 entry.0 = current_max;
2018 } else {
2019 current_max = entry.0;
2020 }
2021 }
2022
2023 result
2024}
2025
2026fn sample_gradient(stops: &[(f32, Color)], t: f32) -> Color {
2027 if stops.is_empty() {
2028 return Color::TRANSPARENT;
2029 }
2030 let t = t.clamp(0.0, 1.0);
2031 if t <= stops[0].0 {
2032 return stops[0].1;
2033 }
2034 if t >= stops.last().unwrap().0 {
2035 return stops.last().unwrap().1;
2036 }
2037
2038 for i in 0..stops.len() - 1 {
2039 let (p0, c0) = stops[i];
2040 let (p1, c1) = stops[i + 1];
2041 if t >= p0 && t <= p1 {
2042 let factor = if p1 > p0 { (t - p0) / (p1 - p0) } else { 0.0 };
2043 let r = c0.r() + (c1.r() - c0.r()) * factor;
2044 let g = c0.g() + (c1.g() - c0.g()) * factor;
2045 let b = c0.b() + (c1.b() - c0.b()) * factor;
2046 let a = c0.a() + (c1.a() - c0.a()) * factor;
2047 return Color::from_f32(r, g, b, a);
2048 }
2049 }
2050
2051 stops.last().unwrap().1
2052}
2053
2054fn decode_or_get_rgba(data: &[u8], width: usize, height: usize) -> Vec<u8> {
2055 if data.len() == width * height * 4 {
2056 return data.to_vec();
2057 }
2058 if data.len() >= 8 && data[0..8] == [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] {
2059 if let Ok(decoded) = decode_png_to_rgba(data, width, height) {
2060 return decoded;
2061 }
2062 }
2063 if data.len() == width * height * 3 {
2064 let mut out = Vec::with_capacity(width * height * 4);
2065 for chunk in data.chunks_exact(3) {
2066 out.push(chunk[0]);
2067 out.push(chunk[1]);
2068 out.push(chunk[2]);
2069 out.push(255);
2070 }
2071 return out;
2072 }
2073
2074 vec![0u8; width * height * 4]
2075}
2076
2077fn decode_png_to_rgba(
2078 data: &[u8],
2079 expected_w: usize,
2080 expected_h: usize,
2081) -> Result<Vec<u8>, String> {
2082 if data.len() < 8 || data[0..8] != [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] {
2083 return Err("Invalid PNG signature".to_string());
2084 }
2085
2086 let mut cursor = 8;
2087 let mut width = 0usize;
2088 let mut height = 0usize;
2089 let mut color_type = 6u8;
2090 let mut idat_data = Vec::new();
2091
2092 while cursor + 12 <= data.len() {
2093 let chunk_len = u32::from_be_bytes(data[cursor..cursor + 4].try_into().unwrap()) as usize;
2094 let chunk_type = &data[cursor + 4..cursor + 8];
2095 let chunk_payload = &data[cursor + 8..cursor + 8 + chunk_len];
2096 cursor += 12 + chunk_len;
2097
2098 if chunk_type == b"IHDR" {
2099 if chunk_len < 13 {
2100 return Err("IHDR chunk too short".to_string());
2101 }
2102 width = u32::from_be_bytes(chunk_payload[0..4].try_into().unwrap()) as usize;
2103 height = u32::from_be_bytes(chunk_payload[4..8].try_into().unwrap()) as usize;
2104 color_type = chunk_payload[9];
2105 } else if chunk_type == b"IDAT" {
2106 idat_data.extend_from_slice(chunk_payload);
2107 } else if chunk_type == b"IEND" {
2108 break;
2109 }
2110 }
2111
2112 if width == 0 || height == 0 {
2113 width = expected_w;
2114 height = expected_h;
2115 }
2116
2117 let decompressed = miniz_oxide::inflate::decompress_to_vec_zlib(&idat_data)
2118 .map_err(|e| format!("PNG zlib inflation failed: {e:?}"))?;
2119
2120 let bpp: usize = match color_type {
2121 0 => 1,
2122 2 => 3,
2123 3 => 1,
2124 4 => 2,
2125 6 => 4,
2126 _ => 4,
2127 };
2128
2129 let stride = 1 + width * bpp;
2130 if decompressed.len() < height * stride {
2131 return Err("Decompressed PNG data truncated".to_string());
2132 }
2133
2134 let mut uncompressed_rows: Vec<u8> = vec![0u8; height * width * bpp];
2135 let mut prev_row: Vec<u8> = vec![0u8; width * bpp];
2136
2137 for y in 0..height {
2138 let filter_type = decompressed[y * stride];
2139 let raw_row = &decompressed[y * stride + 1..y * stride + stride];
2140 let row_out_start = y * width * bpp;
2141 let row_out = &mut uncompressed_rows[row_out_start..row_out_start + width * bpp];
2142
2143 match filter_type {
2144 0 => {
2145 row_out.copy_from_slice(raw_row);
2146 }
2147 1 => {
2148 for x in 0..raw_row.len() {
2149 let a = if x >= bpp { row_out[x - bpp] } else { 0 };
2150 row_out[x] = raw_row[x].wrapping_add(a);
2151 }
2152 }
2153 2 => {
2154 for x in 0..raw_row.len() {
2155 let b = prev_row[x];
2156 row_out[x] = raw_row[x].wrapping_add(b);
2157 }
2158 }
2159 3 => {
2160 for x in 0..raw_row.len() {
2161 let a = if x >= bpp { row_out[x - bpp] as u16 } else { 0 };
2162 let b = prev_row[x] as u16;
2163 row_out[x] = raw_row[x].wrapping_add(((a + b) / 2) as u8);
2164 }
2165 }
2166 4 => {
2167 for x in 0..raw_row.len() {
2168 let a = if x >= bpp { row_out[x - bpp] as i32 } else { 0 };
2169 let b = prev_row[x] as i32;
2170 let c = if x >= bpp {
2171 prev_row[x - bpp] as i32
2172 } else {
2173 0
2174 };
2175 let p = a + b - c;
2176 let pa = (p - a).abs();
2177 let pb = (p - b).abs();
2178 let pc = (p - c).abs();
2179 let pr = if pa <= pb && pa <= pc {
2180 a
2181 } else if pb <= pc {
2182 b
2183 } else {
2184 c
2185 };
2186 row_out[x] = raw_row[x].wrapping_add(pr as u8);
2187 }
2188 }
2189 _ => {
2190 row_out.copy_from_slice(raw_row);
2191 }
2192 }
2193
2194 prev_row.copy_from_slice(row_out);
2195 }
2196
2197 let mut rgba_out = Vec::with_capacity(width * height * 4);
2198 for y in 0..height {
2199 let row_start = y * width * bpp;
2200 for x in 0..width {
2201 let px_start = row_start + x * bpp;
2202 match color_type {
2203 6 => {
2204 rgba_out.extend_from_slice(&uncompressed_rows[px_start..px_start + 4]);
2205 }
2206 2 => {
2207 rgba_out.push(uncompressed_rows[px_start]);
2208 rgba_out.push(uncompressed_rows[px_start + 1]);
2209 rgba_out.push(uncompressed_rows[px_start + 2]);
2210 rgba_out.push(255);
2211 }
2212 0 => {
2213 let g = uncompressed_rows[px_start];
2214 rgba_out.push(g);
2215 rgba_out.push(g);
2216 rgba_out.push(g);
2217 rgba_out.push(255);
2218 }
2219 4 => {
2220 let g = uncompressed_rows[px_start];
2221 let a = uncompressed_rows[px_start + 1];
2222 rgba_out.push(g);
2223 rgba_out.push(g);
2224 rgba_out.push(g);
2225 rgba_out.push(a);
2226 }
2227 _ => {
2228 rgba_out.extend_from_slice(&[255, 255, 255, 255]);
2229 }
2230 }
2231 }
2232 }
2233
2234 Ok(rgba_out)
2235}