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
// 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.

use crate::{Shader, Transform, PixmapRef, SpreadMode};

use crate::floating_point::NormalizedF32;
use crate::pipeline;
use crate::shaders::StageRec;


/// Controls how much filtering to be done when transforming images.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum FilterQuality {
    /// Nearest-neighbor. Low quality, but fastest.
    Nearest,
    /// Bilinear.
    Bilinear,
    /// Bicubic. High quality, but slow.
    Bicubic,
}


/// A pattern shader.
///
/// Essentially a `SkImageShader`.
///
/// Unlike Skia, we do not support FilterQuality::Medium, because it involves
/// mipmap generation, which adds too much complexity.
#[derive(Clone, Debug)]
pub struct Pattern<'a> {
    pixmap: PixmapRef<'a>,
    quality: FilterQuality,
    spread_mode: SpreadMode,
    pub(crate) opacity: NormalizedF32,
    pub(crate) transform: Transform,
}

impl<'a> Pattern<'a> {
    /// Creates a new pattern shader.
    ///
    /// `opacity` will be clamped to the 0..=1 range.
    #[allow(clippy::new_ret_no_self)]
    pub fn new(
        pixmap: PixmapRef<'a>,
        spread_mode: SpreadMode,
        quality: FilterQuality,
        opacity: f32,
        transform: Transform,
    ) -> Shader {
        Shader::Pattern(Pattern {
            pixmap,
            spread_mode,
            quality,
            opacity: NormalizedF32::new_bounded(opacity),
            transform,
        })
    }

    pub(crate) fn push_stages(&self, rec: StageRec) -> Option<()> {
        let ts = self.transform.invert()?;

        rec.pipeline.push(pipeline::Stage::SeedShader);

        rec.pipeline.push_transform(ts, rec.ctx_storage);

        let ctx = pipeline::GatherCtx {
            pixels: self.pixmap.pixels().as_ptr(),
            pixels_len: self.pixmap.pixels().len(),
            width: self.pixmap.size().width_safe(),
            height: self.pixmap.size().height_safe(),
        };

        let mut quality = self.quality;

        if ts.is_identity() || ts.is_translate() {
            quality = FilterQuality::Nearest;
        }

        if quality == FilterQuality::Bilinear {
            if ts.is_translate() {
                let (tx, ty) = ts.get_translate();
                if tx == tx.trunc() && ty == ty.trunc() {
                    // When the matrix is just an integer translate, bilerp == nearest neighbor.
                    quality = FilterQuality::Nearest;
                }
            }
        }

        // TODO: minimizing scale via mipmap

        match quality {
            FilterQuality::Nearest => {
                let limit_x = pipeline::TileCtx {
                    scale: self.pixmap.width() as f32,
                    inv_scale: 1.0 / self.pixmap.width() as f32,
                };

                let limit_y = pipeline::TileCtx {
                    scale: self.pixmap.height() as f32,
                    inv_scale: 1.0 / self.pixmap.height() as f32,
                };

                let limit_x = rec.ctx_storage.push_context(limit_x);
                let limit_y = rec.ctx_storage.push_context(limit_y);
                let ctx = rec.ctx_storage.push_context(ctx);

                match self.spread_mode {
                    SpreadMode::Pad => { /* The gather_xxx stage will clamp for us. */ }
                    SpreadMode::Repeat => {
                        rec.pipeline.push_with_context(pipeline::Stage::RepeatX, limit_x);
                        rec.pipeline.push_with_context(pipeline::Stage::RepeatY, limit_y);
                    }
                    SpreadMode::Reflect => {
                        rec.pipeline.push_with_context(pipeline::Stage::ReflectX, limit_x);
                        rec.pipeline.push_with_context(pipeline::Stage::ReflectY, limit_y);
                    }
                }

                rec.pipeline.push_with_context(pipeline::Stage::Gather, ctx);
            }
            FilterQuality::Bilinear => {
                let sampler_ctx = pipeline::SamplerCtx {
                    gather: ctx,
                    spread_mode: self.spread_mode,
                    inv_width: 1.0 / ctx.width.get() as f32,
                    inv_height: 1.0 / ctx.height.get() as f32,
                };
                let sampler_ctx = rec.ctx_storage.push_context(sampler_ctx);
                rec.pipeline.push_with_context(pipeline::Stage::Bilinear, sampler_ctx);
            }
            FilterQuality::Bicubic => {
                let sampler_ctx = pipeline::SamplerCtx {
                    gather: ctx,
                    spread_mode: self.spread_mode,
                    inv_width: 1.0 / ctx.width.get() as f32,
                    inv_height: 1.0 / ctx.height.get() as f32,
                };
                let sampler_ctx = rec.ctx_storage.push_context(sampler_ctx);
                rec.pipeline.push_with_context(pipeline::Stage::Bicubic, sampler_ctx);

                // Bicubic filtering naturally produces out of range values on both sides of [0,1].
                rec.pipeline.push(pipeline::Stage::Clamp0);
                rec.pipeline.push(pipeline::Stage::ClampA);
            }
        }

        // Unlike Skia, we do not support global opacity and only Pattern allows it.
        if self.opacity != NormalizedF32::ONE {
            debug_assert_eq!(std::mem::size_of_val(&self.opacity), 4, "alpha must be f32");
            let opacity = rec.ctx_storage.push_context(self.opacity.get());
            rec.pipeline.push_with_context(pipeline::Stage::Scale1Float, opacity);
        }

        Some(())
    }
}