Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.1

0.6.1 / src / raster / painter.lucb

#==============================================================================================
#
#   painter - Paint, and drawing pixmaps onto a pixmap
#
#   DESCRIPTION:
#       Port of tiny-skia painter.rs: FillRule, Paint (with Skia's dither flag), the
#       bodies of PixmapMut's draw_pixmap and apply_mask (declared in pixmap.lucb),
#       treat_as_hairline (Skia's DrawTreatAsHairline), is_too_big_for_math and DrawTiler
#       (drawing onto pixmaps larger than 8191 pixels in tiles). Filling and stroking follow
#       Skia's SkDraw, in draw.lucb. Where Rust clones a Paint to change its shader, the
#       clone is a copy whose gradient stops are copied only when they are modified
#       (apply_opacity), and released afterwards.
#
#==============================================================================================

## A path filling rule.
pub enum FillRule as u8:
    ## Specifies that "inside" is computed by a non-zero sum of signed edge crossings.
    winding = 0
    ## Specifies that "inside" is computed by an odd number of edge crossings.
    even_odd = 1

## Controls how a shape should be painted.
pub struct Paint:
    ## A paint shader. Default: black color
    pub var shader: Shader = .solid_color(color = Color(r = 0.0, g = 0.0, b = 0.0, a = 1.0))

    ## Paint blending mode. Default: SourceOver
    pub var blend_mode: BlendMode = .source_over

    ## Enables anti-aliased painting. Default: true
    pub var anti_alias: bool = true

    ## Colorspace for blending (gamma correction). Default: Linear
    pub var colorspace: ColorSpace = .linear

    ## Forces a high quality/precision rendering pipeline. Default: false
    pub var force_hq_pipeline: bool = false

    ## Dithers the colors of non-constant shaders (gradients, patterns), as Skia does with
    ## SkPaint::setDither. Default: false
    pub var dither: bool = false

    ## The paint's alpha (SkPaint::setAlphaf), applied after the shader. Default: 1
    pub var alpha: f32 = 1.0

    ## SkColorFilters::LinearToSRGBGamma as the paint's color filter: the shader's colors,
    ## taken as linear sRGB, encoded to sRGB. Default: false
    pub var linear_to_srgb: bool = false

    ## Sets a paint source to a solid color.
    pub func set_color(color: Color):
        self.shader = .solid_color(color = color)

    ## Sets a paint source to a solid color. `self.shader = Shader.solid_color(Color.from_rgba8(50, 127, 150, 200))`
    ## shorthand.
    pub func set_color_rgba8(r: u8, g: u8, b: u8, a: u8):
        self.set_color(Color.from_rgba8(r, g, b, a))

    ## Checks that the paint source is a solid color.
    pub func is_solid_color() -> bool:
        match self.shader:
            .solid_color(_): return true
            _: return false

    ## Frees the shader's gradient stops.
    pub func release():
        self.shader.release()

## A copy of the paint whose gradient stops are its own (release it).
func shader_clone_paint(paint: const Paint*) -> Paint:
    var copy = *paint
    copy.shader = paint.shader.clone()
    return copy

# mark: draw_pixmap and apply_mask ============================================================

func painter_draw_pixmap(pixmap_dst: PixmapMut*, x: i32, y: i32, pixmap: PixmapRef, pixmap_paint: const PixmapPaint*, transform: Transform, mask: const Mask*?):
    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 patt_transform = Transform.from_translate((f32)x, (f32)y)

    let paint = Paint(
        shader = Pattern.new_(pixmap, .pad_, pixmap_paint.quality, pixmap_paint.opacity, patt_transform), blend_mode = pixmap_paint.blend_mode,
        anti_alias = false, force_hq_pipeline = false, colorspace = .linear,
    )
    # Pad, otherwise we will get weird borders overlap.
    # Skia doesn't use it too.
    # Pattern will use hq anyway.

    draw_fill_rect(pixmap_dst, rect, &paint, transform, mask)

func painter_apply_mask(pixmap: PixmapMut*, mask: const Mask*):
    if pixmap.size().width() != mask.size().width() or pixmap.size().height() != mask.size().height():
        # log::warn!("Pixmap and Mask are expected to have the same size")
        return

    # Just a dummy.
    let pixmap_src = dummy_pixmap_ref()

    var b = RasterPipelineBuilder.new_()
    b.push(.load_mask_u8)
    b.push(.load_destination)
    b.push(.destination_in)
    b.push(.store)
    var p = b.compile()
    defer p.release()
    let rect = pixmap.size().to_screen_int_rect(0, 0)
    var subpix = pixmap.as_subpixmap()
    p.run(rect, AAMaskCtx(), mask.as_submask().mask_ctx(), pixmap_src, &subpix)

# mark: Helpers ===============================================================================

func fast_len(p: Point) -> f32:
    var x = math32.abs(p.x)
    var y = math32.abs(p.y)
    if x < y:
        let t = x
        x = y
        y = t

    return x + half(y)

func treat_as_hairline(paint: const Paint*, stroke: const Stroke*, ts0: Transform) -> f32?:
    if stroke.width == 0.0:
        return 1.0

    if not paint.anti_alias:
        return none

    # DrawTreatAAStrokeAsHairline: no hairlines under perspective.
    if ts0.has_perspective():
        return none

    # We don't care about translate.
    var ts = ts0
    ts.tx = 0.0
    ts.ty = 0.0

    # We need to try to fake a thick-stroke with a modulated hairline.
    var points: Point[2] = [Point.from_xy(stroke.width, 0.0), Point.from_xy(0.0, stroke.width)]
    ts.map_points(points)

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

    if len0 <= 1.0 and len1 <= 1.0:
        # sk_float_midpoint: double math to avoid underflow and overflow.
        return (f32)(0.5 * ((f64)len0 + (f64)len1))

    return none

func is_too_big_for_math(path: const Path*) -> bool:
    # This value is just a guess. smaller is safer, but we don't want to reject largish paths
    # that we don't have to.
    let scale_down_to_allow_for_small_multiplies: f32 = 0.25
    let max = scalar_max * scale_down_to_allow_for_small_multiplies

    let b = path.bounds()

    # use ! expression so we return true if bounds contains NaN
    return not (b.left() >= -max and b.top() >= -max and b.right() <= max and b.bottom() <= max)

struct DrawTiler:
    var image_width: u32
    var image_height: u32
    var x_offset: u32
    var y_offset: u32
    var finished: bool

    # 8K is 1 too big, since 8K << supersample == 32768 which is too big for Fixed.
    static func max_dimensions() -> u32:
        return 8192 - 1

    static func required(image_width: u32, image_height: u32) -> bool:
        return image_width > DrawTiler.max_dimensions() or image_height > DrawTiler.max_dimensions()

    static func new_(image_width: u32, image_height: u32) -> DrawTiler?:
        if DrawTiler.required(image_width, image_height):
            return DrawTiler(image_width = image_width, image_height = image_height, x_offset = 0, y_offset = 0, finished = false)
        return none

    func next() -> ScreenIntRect?:
        if self.finished:
            return none

        # TODO: iterate only over tiles that actually affected by the shape

        if self.x_offset < self.image_width and self.y_offset < self.image_height:
            let max_dim = DrawTiler.max_dimensions()
            var h: u32
            if self.y_offset < self.image_height:
                let rest = self.image_height - self.y_offset
                h = rest if rest < max_dim else max_dim
            else:
                h = self.image_height

            let wrest = self.image_width - self.x_offset
            let r = ScreenIntRect.from_xywh(self.x_offset, self.y_offset, wrest if wrest < max_dim else max_dim, h)

            self.x_offset += max_dim
            if self.x_offset >= self.image_width:
                self.x_offset = 0
                self.y_offset += max_dim

            return r

        return none