1use crate::*;
8
9use tiny_skia_path::{PathStroker, Scalar, SCALAR_MAX};
10
11use crate::geom::ScreenIntRect;
12use crate::mask::SubMaskRef;
13use crate::pipeline::{RasterPipelineBlitter, RasterPipelineBuilder};
14use crate::pixmap::SubPixmapMut;
15use crate::scan;
16
17use crate::geom::IntSizeExt;
18#[cfg(all(not(feature = "std"), feature = "no-std-float"))]
19use tiny_skia_path::NoStdFloat;
20
21#[derive(Copy, Clone, PartialEq, Debug)]
23pub enum FillRule {
24 Winding,
26 EvenOdd,
28}
29
30impl Default for FillRule {
31 fn default() -> Self {
32 FillRule::Winding
33 }
34}
35
36#[derive(Clone, PartialEq, Debug)]
38pub struct Paint<'a> {
39 pub shader: Shader<'a>,
43
44 pub blend_mode: BlendMode,
48
49 pub anti_alias: bool,
53
54 pub force_hq_pipeline: bool,
71}
72
73impl Default for Paint<'_> {
74 fn default() -> Self {
75 Paint {
76 shader: Shader::SolidColor(Color::BLACK),
77 blend_mode: BlendMode::default(),
78 anti_alias: true,
79 force_hq_pipeline: false,
80 }
81 }
82}
83
84impl<'a> Paint<'a> {
85 pub fn set_color(&mut self, color: Color) {
87 self.shader = Shader::SolidColor(color);
88 }
89
90 pub fn set_color_rgba8(&mut self, r: u8, g: u8, b: u8, a: u8) {
94 self.set_color(Color::from_rgba8(r, g, b, a))
95 }
96
97 pub fn is_solid_color(&self) -> bool {
99 matches!(self.shader, Shader::SolidColor(_))
100 }
101}
102
103impl Pixmap {
104 pub fn fill_rect(
108 &mut self,
109 rect: Rect,
110 paint: &Paint,
111 transform: Transform,
112 mask: Option<&Mask>,
113 ) {
114 self.as_mut().fill_rect(rect, paint, transform, mask);
115 }
116
117 pub fn fill_path(
121 &mut self,
122 path: &Path,
123 paint: &Paint,
124 fill_rule: FillRule,
125 transform: Transform,
126 mask: Option<&Mask>,
127 ) {
128 self.as_mut()
129 .fill_path(path, paint, fill_rule, transform, mask);
130 }
131
132 pub fn stroke_path(
136 &mut self,
137 path: &Path,
138 paint: &Paint,
139 stroke: &Stroke,
140 transform: Transform,
141 mask: Option<&Mask>,
142 ) {
143 self.as_mut()
144 .stroke_path(path, paint, stroke, transform, mask);
145 }
146
147 pub fn draw_pixmap(
151 &mut self,
152 x: i32,
153 y: i32,
154 pixmap: PixmapRef,
155 paint: &PixmapPaint,
156 transform: Transform,
157 mask: Option<&Mask>,
158 ) {
159 self.as_mut()
160 .draw_pixmap(x, y, pixmap, paint, transform, mask);
161 }
162
163 pub fn apply_mask(&mut self, mask: &Mask) {
167 self.as_mut().apply_mask(mask);
168 }
169}
170
171impl PixmapMut<'_> {
172 pub fn fill_rect(
183 &mut self,
184 rect: Rect,
185 paint: &Paint,
186 transform: Transform,
187 mask: Option<&Mask>,
188 ) {
189 if transform.is_identity() && !DrawTiler::required(self.width(), self.height()) {
191 let clip = self.size().to_screen_int_rect(0, 0);
194
195 let mask = mask.map(|mask| mask.as_submask());
196 let mut subpix = self.as_subpixmap();
197 let mut blitter = match RasterPipelineBlitter::new(paint, mask, &mut subpix) {
198 Some(v) => v,
199 None => return, };
201
202 if paint.anti_alias {
203 scan::fill_rect_aa(&rect, &clip, &mut blitter);
204 } else {
205 scan::fill_rect(&rect, &clip, &mut blitter);
206 }
207 } else {
208 let path = PathBuilder::from_rect(rect);
209 self.fill_path(&path, paint, FillRule::Winding, transform, mask);
210 }
211 }
212
213 pub fn fill_path(
215 &mut self,
216 path: &Path,
217 paint: &Paint,
218 fill_rule: FillRule,
219 transform: Transform,
220 mask: Option<&Mask>,
221 ) {
222 if transform.is_identity() {
223 let path_bounds = path.bounds();
227 if path_bounds.width().is_nearly_zero() || path_bounds.height().is_nearly_zero() {
228 log::warn!("empty paths and horizontal/vertical lines cannot be filled");
229 return;
230 }
231
232 if is_too_big_for_math(path) {
233 log::warn!("path coordinates are too big");
234 return;
235 }
236
237 if let Some(tiler) = DrawTiler::new(self.width(), self.height()) {
240 let mut path = path.clone(); let mut paint = paint.clone();
242
243 for tile in tiler {
244 let ts = Transform::from_translate(-(tile.x() as f32), -(tile.y() as f32));
245 path = match path.transform(ts) {
246 Some(v) => v,
247 None => {
248 log::warn!("path transformation failed");
249 return;
250 }
251 };
252 paint.shader.transform(ts);
253
254 let clip_rect = tile.size().to_screen_int_rect(0, 0);
255 let mut subpix = match self.subpixmap(tile.to_int_rect()) {
256 Some(v) => v,
257 None => continue, };
259
260 let submask = mask.and_then(|mask| mask.submask(tile.to_int_rect()));
261 let mut blitter = match RasterPipelineBlitter::new(&paint, submask, &mut subpix)
262 {
263 Some(v) => v,
264 None => continue, };
266
267 if paint.anti_alias {
271 scan::path_aa::fill_path(&path, fill_rule, &clip_rect, &mut blitter);
272 } else {
273 scan::path::fill_path(&path, fill_rule, &clip_rect, &mut blitter);
274 }
275
276 let ts = Transform::from_translate(tile.x() as f32, tile.y() as f32);
277 path = match path.transform(ts) {
278 Some(v) => v,
279 None => return, };
281 paint.shader.transform(ts);
282 }
283 } else {
284 let clip_rect = self.size().to_screen_int_rect(0, 0);
285 let submask = mask.map(|mask| mask.as_submask());
286 let mut subpix = self.as_subpixmap();
287 let mut blitter = match RasterPipelineBlitter::new(paint, submask, &mut subpix) {
288 Some(v) => v,
289 None => return, };
291
292 if paint.anti_alias {
293 scan::path_aa::fill_path(path, fill_rule, &clip_rect, &mut blitter);
294 } else {
295 scan::path::fill_path(path, fill_rule, &clip_rect, &mut blitter);
296 }
297 }
298 } else {
299 let path = match path.clone().transform(transform) {
300 Some(v) => v,
301 None => {
302 log::warn!("path transformation failed");
303 return;
304 }
305 };
306
307 let mut paint = paint.clone();
308 paint.shader.transform(transform);
309
310 self.fill_path(&path, &paint, fill_rule, Transform::identity(), mask)
311 }
312 }
313
314 pub fn stroke_path(
328 &mut self,
329 path: &Path,
330 paint: &Paint,
331 stroke: &Stroke,
332 transform: Transform,
333 mask: Option<&Mask>,
334 ) {
335 if stroke.width < 0.0 {
336 log::warn!("negative stroke width isn't allowed");
337 return;
338 }
339
340 let res_scale = PathStroker::compute_resolution_scale(&transform);
341
342 let dash_path;
343 let path = if let Some(ref dash) = stroke.dash {
344 dash_path = match path.dash(dash, res_scale) {
345 Some(v) => v,
346 None => {
347 log::warn!("path dashing failed");
348 return;
349 }
350 };
351 &dash_path
352 } else {
353 path
354 };
355
356 if let Some(coverage) = treat_as_hairline(paint, stroke, transform) {
357 let mut paint = paint.clone();
358 if coverage == 1.0 {
359 } else if paint.blend_mode.should_pre_scale_coverage() {
361 let scale = (coverage * 256.0) as i32;
365 let new_alpha = (255 * scale) >> 8;
366 paint.shader.apply_opacity(new_alpha as f32 / 255.0);
367 }
368
369 if let Some(tiler) = DrawTiler::new(self.width(), self.height()) {
370 let mut path = path.clone(); let mut paint = paint.clone();
372
373 if !transform.is_identity() {
374 paint.shader.transform(transform);
375 path = match path.transform(transform) {
376 Some(v) => v,
377 None => {
378 log::warn!("path transformation failed");
379 return;
380 }
381 };
382 }
383
384 for tile in tiler {
385 let ts = Transform::from_translate(-(tile.x() as f32), -(tile.y() as f32));
386 path = match path.transform(ts) {
387 Some(v) => v,
388 None => {
389 log::warn!("path transformation failed");
390 return;
391 }
392 };
393 paint.shader.transform(ts);
394
395 let mut subpix = match self.subpixmap(tile.to_int_rect()) {
396 Some(v) => v,
397 None => continue, };
399 let submask = mask.and_then(|mask| mask.submask(tile.to_int_rect()));
400
401 Self::stroke_hairline(&path, &paint, stroke.line_cap, submask, &mut subpix);
405
406 let ts = Transform::from_translate(tile.x() as f32, tile.y() as f32);
407 path = match path.transform(ts) {
408 Some(v) => v,
409 None => return,
410 };
411 paint.shader.transform(ts);
412 }
413 } else {
414 let subpix = &mut self.as_subpixmap();
415 let submask = mask.map(|mask| mask.as_submask());
416 if !transform.is_identity() {
417 paint.shader.transform(transform);
418
419 let path = match path.clone().transform(transform) {
421 Some(v) => v,
422 None => {
423 log::warn!("path transformation failed");
424 return;
425 }
426 };
427
428 Self::stroke_hairline(&path, &paint, stroke.line_cap, submask, subpix);
429 } else {
430 Self::stroke_hairline(path, &paint, stroke.line_cap, submask, subpix);
431 }
432 }
433 } else {
434 let path = match path.stroke(stroke, res_scale) {
435 Some(v) => v,
436 None => {
437 log::warn!("path stroking failed");
438 return;
439 }
440 };
441
442 self.fill_path(&path, paint, FillRule::Winding, transform, mask);
443 }
444 }
445
446 fn stroke_hairline(
448 path: &Path,
449 paint: &Paint,
450 line_cap: LineCap,
451 mask: Option<SubMaskRef>,
452 pixmap: &mut SubPixmapMut,
453 ) {
454 let clip = pixmap.size.to_screen_int_rect(0, 0);
455 let mut blitter = match RasterPipelineBlitter::new(paint, mask, pixmap) {
456 Some(v) => v,
457 None => return, };
459 if paint.anti_alias {
460 scan::hairline_aa::stroke_path(path, line_cap, &clip, &mut blitter);
461 } else {
462 scan::hairline::stroke_path(path, line_cap, &clip, &mut blitter);
463 }
464 }
465
466 pub fn draw_pixmap(
470 &mut self,
471 x: i32,
472 y: i32,
473 pixmap: PixmapRef,
474 paint: &PixmapPaint,
475 transform: Transform,
476 mask: Option<&Mask>,
477 ) {
478 let rect = pixmap.size().to_int_rect(x, y).to_rect();
479
480 let patt_transform = Transform::from_translate(x as f32, y as f32);
486
487 let paint = Paint {
488 shader: Pattern::new(
489 pixmap,
490 SpreadMode::Pad, paint.quality,
492 paint.opacity,
493 patt_transform,
494 ),
495 blend_mode: paint.blend_mode,
496 anti_alias: false, force_hq_pipeline: false, };
499
500 self.fill_rect(rect, &paint, transform, mask);
501 }
502
503 pub fn apply_mask(&mut self, mask: &Mask) {
515 if self.size() != mask.size() {
516 log::warn!("Pixmap and Mask are expected to have the same size");
517 return;
518 }
519
520 let pixmap_src = PixmapRef::from_bytes(&[0, 0, 0, 0], 1, 1).unwrap();
522
523 let mut p = RasterPipelineBuilder::new();
524 p.push(pipeline::Stage::LoadMaskU8);
525 p.push(pipeline::Stage::LoadDestination);
526 p.push(pipeline::Stage::DestinationIn);
527 p.push(pipeline::Stage::Store);
528 let mut p = p.compile();
529 let rect = self.size().to_screen_int_rect(0, 0);
530 p.run(
531 &rect,
532 pipeline::AAMaskCtx::default(),
533 mask.as_submask().mask_ctx(),
534 pixmap_src,
535 &mut self.as_subpixmap(),
536 );
537 }
538}
539
540fn treat_as_hairline(paint: &Paint, stroke: &Stroke, mut ts: Transform) -> Option<f32> {
541 fn fast_len(p: Point) -> f32 {
542 let mut x = p.x.abs();
543 let mut y = p.y.abs();
544 if x < y {
545 core::mem::swap(&mut x, &mut y);
546 }
547
548 x + y.half()
549 }
550
551 debug_assert!(stroke.width >= 0.0);
552
553 if stroke.width == 0.0 {
554 return Some(1.0);
555 }
556
557 if !paint.anti_alias {
558 return None;
559 }
560
561 ts.tx = 0.0;
563 ts.ty = 0.0;
564
565 let mut points = [
567 Point::from_xy(stroke.width, 0.0),
568 Point::from_xy(0.0, stroke.width),
569 ];
570 ts.map_points(&mut points);
571
572 let len0 = fast_len(points[0]);
573 let len1 = fast_len(points[1]);
574
575 if len0 <= 1.0 && len1 <= 1.0 {
576 return Some(len0.ave(len1));
577 }
578
579 None
580}
581
582pub(crate) fn is_too_big_for_math(path: &Path) -> bool {
589 const SCALE_DOWN_TO_ALLOW_FOR_SMALL_MULTIPLIES: f32 = 0.25;
592 const MAX: f32 = SCALAR_MAX * SCALE_DOWN_TO_ALLOW_FOR_SMALL_MULTIPLIES;
593
594 let b = path.bounds();
595
596 !(b.left() >= -MAX && b.top() >= -MAX && b.right() <= MAX && b.bottom() <= MAX)
598}
599
600pub(crate) struct DrawTiler {
609 image_width: u32,
610 image_height: u32,
611 x_offset: u32,
612 y_offset: u32,
613 finished: bool,
614}
615
616impl DrawTiler {
617 const MAX_DIMENSIONS: u32 = 8192 - 1;
619
620 fn required(image_width: u32, image_height: u32) -> bool {
621 image_width > Self::MAX_DIMENSIONS || image_height > Self::MAX_DIMENSIONS
622 }
623
624 pub(crate) fn new(image_width: u32, image_height: u32) -> Option<Self> {
625 if Self::required(image_width, image_height) {
626 Some(DrawTiler {
627 image_width,
628 image_height,
629 x_offset: 0,
630 y_offset: 0,
631 finished: false,
632 })
633 } else {
634 None
635 }
636 }
637}
638
639impl Iterator for DrawTiler {
640 type Item = ScreenIntRect;
641
642 fn next(&mut self) -> Option<Self::Item> {
643 if self.finished {
644 return None;
645 }
646
647 if self.x_offset < self.image_width && self.y_offset < self.image_height {
650 let h = if self.y_offset < self.image_height {
651 (self.image_height - self.y_offset).min(Self::MAX_DIMENSIONS)
652 } else {
653 self.image_height
654 };
655
656 let r = ScreenIntRect::from_xywh(
657 self.x_offset,
658 self.y_offset,
659 (self.image_width - self.x_offset).min(Self::MAX_DIMENSIONS),
660 h,
661 );
662
663 self.x_offset += Self::MAX_DIMENSIONS;
664 if self.x_offset >= self.image_width {
665 self.x_offset = 0;
666 self.y_offset += Self::MAX_DIMENSIONS;
667 }
668
669 return r;
670 }
671
672 None
673 }
674}
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679 const MAX_DIM: u32 = DrawTiler::MAX_DIMENSIONS;
680
681 #[test]
682 fn skip() {
683 assert!(DrawTiler::new(100, 500).is_none());
684 }
685
686 #[test]
687 fn horizontal() {
688 let mut iter = DrawTiler::new(10000, 500).unwrap();
689 assert_eq!(iter.next(), ScreenIntRect::from_xywh(0, 0, MAX_DIM, 500));
690 assert_eq!(
691 iter.next(),
692 ScreenIntRect::from_xywh(MAX_DIM, 0, 10000 - MAX_DIM, 500)
693 );
694 assert_eq!(iter.next(), None);
695 }
696
697 #[test]
698 fn vertical() {
699 let mut iter = DrawTiler::new(500, 10000).unwrap();
700 assert_eq!(iter.next(), ScreenIntRect::from_xywh(0, 0, 500, MAX_DIM));
701 assert_eq!(
702 iter.next(),
703 ScreenIntRect::from_xywh(0, MAX_DIM, 500, 10000 - MAX_DIM)
704 );
705 assert_eq!(iter.next(), None);
706 }
707
708 #[test]
709 fn rect() {
710 let mut iter = DrawTiler::new(10000, 10000).unwrap();
711 assert_eq!(
713 iter.next(),
714 ScreenIntRect::from_xywh(0, 0, MAX_DIM, MAX_DIM)
715 );
716 assert_eq!(
717 iter.next(),
718 ScreenIntRect::from_xywh(MAX_DIM, 0, 10000 - MAX_DIM, MAX_DIM)
719 );
720 assert_eq!(
722 iter.next(),
723 ScreenIntRect::from_xywh(0, MAX_DIM, MAX_DIM, 10000 - MAX_DIM)
724 );
725 assert_eq!(
726 iter.next(),
727 ScreenIntRect::from_xywh(MAX_DIM, MAX_DIM, 10000 - MAX_DIM, 10000 - MAX_DIM)
728 );
729 assert_eq!(iter.next(), None);
730 }
731}