1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// Copyright 2006 The Android Open Source Project
// Copyright 2020 Evgeniy Reizner
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This module is closer to SkDraw than SkCanvas.

use crate::{PixmapRef, PixmapMut, Transform, Path, Paint, Stroke, Point, Rect};
use crate::{PathBuilder, Pattern, FilterQuality, BlendMode, FillRule, SpreadMode};

use crate::clip::ClipMask;
use crate::scalar::Scalar;
use crate::stroker::PathStroker;


/// Controls how a pixmap should be blended.
///
/// Like `Paint`, but for `Pixmap`.
#[derive(Copy, Clone, Debug)]
pub struct PixmapPaint {
    /// Pixmap opacity.
    ///
    /// Must be in 0..=1 range.
    ///
    /// Default: 1.0
    pub opacity: f32,

    /// Pixmap blending mode.
    ///
    /// Default: SourceOver
    pub blend_mode: BlendMode,

    /// Specifies how much filtering to be done when transforming images.
    ///
    /// Default: Nearest
    pub quality: FilterQuality,
}

impl Default for PixmapPaint {
    #[inline]
    fn default() -> Self {
        PixmapPaint {
            opacity: 1.0,
            blend_mode: BlendMode::default(),
            quality: FilterQuality::Nearest,
        }
    }
}


/// Provides a high-level rendering API.
///
/// Unlike the most of other types, `Canvas` provides an unchecked API.
/// Which means that a drawing command will simply be ignored in case of an error
/// and a caller has no way of checking it.
#[allow(missing_debug_implementations)]
pub struct Canvas<'a> {
    /// A pixmap used by the canvas.
    pixmap: PixmapMut<'a>,

    /// Canvas's transform.
    transform: Transform,

    /// Canvas's clip region.
    clip: ClipMask,

    /// A path stroker used to cache temporary stroking data.
    stroker: PathStroker,
    stroked_path: Option<Path>,
}

impl<'a> From<PixmapMut<'a>> for Canvas<'a> {
    #[inline]
    fn from(pixmap: PixmapMut<'a>) -> Self {
        Canvas {
            pixmap,
            transform: Transform::identity(),
            clip: ClipMask::new(),
            stroker: PathStroker::new(),
            stroked_path: None,
        }
    }
}

impl<'a> Canvas<'a> {
    /// Returns an underlying pixmap.
    #[inline]
    pub fn pixmap(&mut self) -> &mut PixmapMut<'a> {
        &mut self.pixmap
    }

    /// Translates the canvas.
    #[inline]
    pub fn translate(&mut self, tx: f32, ty: f32) {
        if let Some(ts) = self.transform.pre_translate(tx, ty) {
            self.transform = ts;
        }
    }

    /// Scales the canvas.
    #[inline]
    pub fn scale(&mut self, sx: f32, sy: f32) {
        if let Some(ts) = self.transform.pre_scale(sx, sy) {
            self.transform = ts;
        }
    }

    /// Applies an affine transformation to the canvas.
    #[inline]
    pub fn transform(&mut self, sx: f32, ky: f32, kx: f32, sy: f32, tx: f32, ty: f32) {
        if let Some(ref ts) = Transform::from_row(sx, ky, kx, sy, tx, ty) {
            self.apply_transform(ts);
        }
    }

    // TODO: overload?

    /// Applies an affine transformation to the canvas.
    #[inline]
    pub fn apply_transform(&mut self, ts: &Transform) {
        if let Some(ts) = self.transform.pre_concat(ts) {
            self.transform = ts;
        }
    }

    /// Gets the current canvas transform.
    #[inline]
    pub fn get_transform(&mut self) -> Transform {
        self.transform
    }

    /// Sets the canvas transform.
    #[inline]
    pub fn set_transform(&mut self, ts: Transform) {
        self.transform = ts;
    }

    /// Resets the canvas transform to identity.
    #[inline]
    pub fn reset_transform(&mut self) {
        self.transform = Transform::identity();
    }

    /// Sets a clip rectangle.
    ///
    /// Consecutive calls will replace the previous value.
    ///
    /// Clipping is affected by the current transform.
    pub fn set_clip_rect(&mut self, rect: Rect, anti_alias: bool) {
        self.set_clip_path(&PathBuilder::from_rect(rect), FillRule::Winding, anti_alias);
    }

    /// Sets a clip path.
    ///
    /// Consecutive calls will replace the previous value.
    ///
    /// Clipping is affected by the current transform.
    pub fn set_clip_path(&mut self, path: &Path, fill_type: FillRule, anti_alias: bool) {
        if !self.transform.is_identity() {
            if let Some(ref path) = path.clone().transform(&self.transform) {
                self.clip.set_path(path, self.pixmap.rect(), fill_type, anti_alias);
            }
        } else {
            self.clip.set_path(path, self.pixmap.rect(), fill_type, anti_alias);
        }
    }

    /// Sets the current clip mask.
    ///
    /// This is a low-level alternative to `set_clip_rect` and `set_clip_path`.
    pub fn set_clip_mask(&mut self, clip: ClipMask) {
        self.clip = clip;
    }

    /// Returns a reference to the current clip mask.
    pub fn get_clip_mask(&self) -> &ClipMask {
        &self.clip
    }

    /// Takes the current clip mask.
    pub fn take_clip_mask(&mut self) -> ClipMask {
        std::mem::replace(&mut self.clip, ClipMask::new())
    }

    /// Resets the current clip.
    pub fn reset_clip(&mut self) {
        self.clip.clear();
    }

    /// Fills a path.
    pub fn fill_path(&mut self, path: &Path, paint: &Paint, fill_type: FillRule) {
        self.fill_path_impl(path, paint, fill_type);
    }

    #[inline(always)]
    fn fill_path_impl(&mut self, path: &Path, paint: &Paint, fill_type: FillRule) -> Option<()> {
        if !self.transform.is_identity() {
            let path = path.clone().transform(&self.transform)?;

            let mut paint = paint.clone();
            paint.shader.transform(&self.transform);

            self.pixmap.fill_path(&path, &paint, fill_type, self.clip.as_ref())
        } else {
            self.pixmap.fill_path(path, paint, fill_type, self.clip.as_ref())
        }
    }

    /// Strokes a path.
    ///
    /// Stroking is implemented using two separate algorithms:
    ///
    /// 1. If a stroke width is wider than 1px (after applying the transformation),
    ///    a path will be converted into a stroked path and then filled using `Canvas::fill_path`.
    ///    Which means that we have to allocate a separate `Path`, that can be 2-3x larger
    ///    then the original path.
    ///    `Canvas` will reuse this allocation during subsequent strokes.
    /// 2. If a stroke width is thinner than 1px (after applying the transformation),
    ///    we will use hairline stroking, which doesn't involve a separate path allocation.
    ///
    /// Also, if a `stroke` has a dash array, then path will be converted into
    /// a dashed path first and then stroked. Which means a yet another allocation.
    pub fn stroke_path(&mut self, path: &Path, paint: &Paint, stroke: &Stroke) {
        self.stroke_path_impl(path, paint, stroke);
    }

    #[inline(always)]
    fn stroke_path_impl(&mut self, path: &Path, paint: &Paint, stroke: &Stroke) -> Option<()> {
        if stroke.width < 0.0 {
            return None;
        }

        let res_scale = PathStroker::compute_resolution_scale(&self.transform);

        let dash_path;
        let path = if let Some(ref dash) = stroke.dash {
            dash_path = crate::dash::dash(path, dash, res_scale)?;
            &dash_path
        } else {
            path
        };

        if let Some(coverage) = treat_as_hairline(&paint, stroke, &self.transform) {
            let mut paint = paint.clone();
            if coverage == 1.0 {
                // No changes to the `paint`.
            } else if paint.blend_mode.should_pre_scale_coverage() {
                // This is the old technique, which we preserve for now so
                // we don't change previous results (testing)
                // the new way seems fine, its just (a tiny bit) different.
                let scale = (coverage * 256.0) as i32;
                let new_alpha = (255 * scale) >> 8;
                paint.shader.apply_opacity(new_alpha as f32 / 255.0);
            }

            if !self.transform.is_identity() {
                paint.shader.transform(&self.transform);

                let path = path.clone().transform(&self.transform)?;
                self.pixmap.stroke_hairline(&path, &paint, stroke.line_cap, self.clip.as_ref())
            } else {
                self.pixmap.stroke_hairline(&path, &paint, stroke.line_cap, self.clip.as_ref())
            }
        } else {
            let mut stroked_path = if let Some(stroked_path) = self.stroked_path.take() {
                self.stroker.stroke_to(&path, stroke, res_scale, stroked_path)
            } else {
                self.stroker.stroke(&path, stroke, res_scale)
            }?;
            stroked_path = stroked_path.transform(&self.transform)?;
            self.stroked_path = Some(stroked_path);

            let path = self.stroked_path.as_ref()?;
            if !self.transform.is_identity() {
                let mut paint = paint.clone();
                paint.shader.transform(&self.transform);

                self.pixmap.fill_path(&path, &paint, FillRule::Winding, self.clip.as_ref())
            } else {
                self.pixmap.fill_path(path, paint, FillRule::Winding, self.clip.as_ref())
            }
        }
    }

    /// Draws a `Pixmap` on top of the current `Pixmap`.
    ///
    /// We basically filling a rectangle with a `pixmap` pattern.
    pub fn draw_pixmap(&mut self, x: i32, y: i32, pixmap: PixmapRef, paint: &PixmapPaint) {
        self.draw_pixmap_impl(x, y, pixmap, paint);
    }

    #[inline(always)]
    fn draw_pixmap_impl(
        &mut self,
        x: i32,
        y: i32,
        pixmap: PixmapRef,
        paint: &PixmapPaint,
    ) -> Option<()> {
        let rect = pixmap.size().to_int_rect(x, y).to_rect();

        // TODO: SkSpriteBlitter
        // TODO: partially clipped
        // TODO: clipped out

        // Translate pattern as well as bounds.
        let transform = Transform::from_translate(x as f32, y as f32)?;

        let paint = Paint {
            shader: Pattern::new(
                pixmap,
                SpreadMode::Pad, // Pad, otherwise we will get weird borders overlap.
                paint.quality,
                paint.opacity,
                transform,
            ),
            blend_mode: paint.blend_mode,
            anti_alias: false, // Skia doesn't use it too.
            force_hq_pipeline: false, // Pattern will use hq anyway.
        };

        self.fill_rect_impl(rect, &paint)
    }

    /// Fills a rectangle.
    ///
    /// This function is usually slower than filling a rectangular path,
    /// but it produces better results. Mainly it doesn't suffer from weird
    /// clipping of horizontal/vertical edges.
    ///
    /// Used mainly to render a pixmap onto a pixmap.
    ///
    /// Fallbacks to `Canvas::fill_path` when `Canvas` has a transform.
    pub fn fill_rect(&mut self, rect: Rect, paint: &Paint) {
        self.fill_rect_impl(rect, paint);
    }

    #[inline(always)]
    fn fill_rect_impl(&mut self, rect: Rect, paint: &Paint) -> Option<()> {
        // TODO: allow translate too
        if self.transform.is_identity() {
            self.pixmap.fill_rect(rect, paint, self.clip.as_ref())
        } else {
            let path = PathBuilder::from_rect(rect);
            self.fill_path_impl(&path, paint, FillRule::Winding)
        }
    }
}

fn treat_as_hairline(paint: &Paint, stroke: &Stroke, ts: &Transform) -> Option<f32> {
    #[inline]
    fn fast_len(p: Point) -> f32 {
        let mut x = p.x.abs();
        let mut y = p.y.abs();
        if x < y {
            std::mem::swap(&mut x, &mut y);
        }

        x + y.half()
    }

    debug_assert!(stroke.width >= 0.0);

    if stroke.width == 0.0 {
        return Some(1.0);
    }

    if !paint.anti_alias {
        return None;
    }

    // We don't care about translate.
    let ts = {
        let (sx, ky, kx, sy, _, _) = ts.get_row();
        Transform::from_row(sx, ky, kx, sy, 0.0, 0.0)?
    };

    // We need to try to fake a thick-stroke with a modulated hairline.
    let mut points = [Point::from_xy(stroke.width, 0.0), Point::from_xy(0.0, stroke.width)];
    ts.map_points(&mut points);

    let len0 = fast_len(points[0]);
    let len1 = fast_len(points[1]);

    if len0 <= 1.0 && len1 <= 1.0 {
        return Some(len0.ave(len1));
    }

    None
}