Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.2

0.6.2 / src / raster / pipeline_blitter.lucb

#==============================================================================================
#
#   pipeline_blitter - the blitter that runs raster pipelines
#
#   DESCRIPTION:
#       Port of tiny-skia pipeline/blitter.rs, brought to Skia m144's
#       SkRasterPipelineBlitter::Create (src/core/SkRasterPipelineBlitter.cpp) and the paint
#       tweaks of SkBlitter::Choose, for Ladybird's destination (8888 premultiplied with a
#       color space, so srcover_rgba_8888 is never used):
#
#       - Choose: a blend mode that acts like SourceOver becomes it (Source with an opaque
#         solid color), Destination and DestinationIn with an opaque solid color draw
#         nothing, Clear becomes Source with transparent black; dither only non-constant
#         shaders.
#       - The color pipeline: the shader's stages (a solid color is a uniform color, the
#         constant pipeline Skia collapses back into one), the paint's alpha
#         (scale_1_float) after a non-solid shader, then dither at 1/255.
#       - SourceOver becomes Source when the color pipeline is opaque, and a constant color
#         with Source fills rects with a memset.
#       - The blit pipelines: color, clamp_01, then for rects load_dst + blend (unless
#         Source); for anti-aliased runs and masks either the pre-scaled coverage
#         (scale_1_float / scale_u8, for the modes SkBlendMode_ShouldPreScaleCoverage
#         allows) then load_dst + blend, or load_dst + blend then lerp_1_float / lerp_u8;
#         then store.
#
#       Clipping is done by the blitters that wrap this one (blitter.lucb,
#       blitter_clip.lucb), as Skia's clip blitters wrap SkRasterPipelineBlitter. A blitter
#       owns its compiled pipelines; `release()` frees them.
#
#       Copyright (c) 2016 Google Inc. All rights reserved.
#       Copyright (c) 2020 Yevhenii Reizner All rights reserved.
#       SPDX-License-Identifier: BSD-3-Clause (see LICENSE-skia, LICENSE-tiny-skia)
#
#==============================================================================================

## The dither rate of an 8888 destination.
let dither_rate_8888: f32 = 1.0 / 255.0

## What SkBlitter::Choose and create_pipeline_for_blitter decide about a paint.
struct PipelineSource:
    var shader: Shader
    var blend_mode: BlendMode
    var paint_alpha: f32  # the paint's alpha, applied after a non-solid shader
    var is_opaque: bool
    var is_constant: bool
    var dither: bool
    var colorspace: ColorSpace
    var linear_to_srgb: bool  # SkColorFilters::LinearToSRGBGamma after the paint's alpha

    ## The color pipeline into `p`: the shader, the paint's alpha, dither, and clamp_01
    ## (appendClampIfNormalized; skipped where it is a no-op).
    func push_color_stages(p: RasterPipelineBuilder*) -> bool:
        if not self.shader.push_stages(self.colorspace, p):
            return false
        if not self.is_constant and self.paint_alpha != 1.0:
            p.ctx.paint_alpha = self.paint_alpha
            p.push(.scale_paint_alpha)
        if self.linear_to_srgb:
            # SkColorSpaceXformColorFilter::appendStages: unpremul unless opaque, the steps from
            # linear sRGB to sRGB (encode only), premul unless opaque.
            if not self.is_opaque:
                p.push(.unpremul)
            let linear = icc.ColorSpace.srgb_linear()
            let srgb = icc.ColorSpace.srgb()
            p.ctx.color_filter_xform = ColorXform.make(icc.Steps.make(&linear, .unpremul, &srgb, .unpremul)) else trap("raster: linear sRGB to sRGB encodes")
            p.push(.color_filter_xform)
            if not self.is_opaque:
                p.push(.premultiply)
        if self.dither:
            p.ctx.dither_rate = dither_rate_8888
            p.push(.dither)
        # A constant color is in range already: its clamp changes nothing.
        if not self.is_constant:
            p.push(.clamp_01)
        return true

    ## load_dst and the blend mode's stages.
    func push_load_and_blend(p: RasterPipelineBuilder*):
        p.push(.load_destination)
        if let stage = colorspace_expand_dest_stage(self.colorspace):
            p.push(stage)
        if let blend_stage = blend_mode_to_stage(self.blend_mode):
            p.push(blend_stage)

    ## A blit pipeline with coverage: `scale` pre-scales it, `lerp` lerps by it.
    func build_coverage(scale: Stage, lerp: Stage) -> RasterPipeline?:
        var b = RasterPipelineBuilder.new_()
        if not self.push_color_stages(&b):
            b.release()
            return none
        if blend_mode_should_pre_scale_coverage(self.blend_mode):
            b.push(scale)
            self.push_load_and_blend(&b)
        else:
            self.push_load_and_blend(&b)
            b.push(lerp)
        if let stage = colorspace_compress_stage(self.colorspace):
            b.push(stage)
        b.push(.store)
        return b.compile()

    ## The blitRect pipeline.
    func build_rect() -> RasterPipeline?:
        var b = RasterPipelineBuilder.new_()
        if not self.push_color_stages(&b):
            b.release()
            return none
        if self.blend_mode != .source:
            self.push_load_and_blend(&b)
        if let stage = colorspace_compress_stage(self.colorspace):
            b.push(stage)
        b.push(.store)
        return b.compile()

## CheckFastPath's "just a solid color": an opaque one.
func just_solid_color(shader: Shader) -> bool:
    match shader:
        .solid_color(c): return c.is_opaque()
        _: return false

## SkBlitter::Choose and create_pipeline_for_blitter's decisions about `paint`: the source its
## pipelines draw with and a pattern's pixmap; none when the paint draws nothing. Shared by the
## blitter and the GPU player's stage programs (paint_stage_program).
func pipeline_source_of(paint: const Paint*) -> (PipelineSource, PixmapRef)?:
    var src = PipelineSource(shader = paint.shader, blend_mode = paint.blend_mode, paint_alpha = 1.0, is_opaque = false, is_constant = false, dither = false, colorspace = paint.colorspace,
                             linear_to_srgb = paint.linear_to_srgb)

    # SkBlitter::Choose. We have the most fast-paths for SrcOver, so see if we can act
    # like SrcOver (CheckFastPath; an 8888 destination is not always opaque).
    if src.blend_mode == .source and just_solid_color(src.shader):
        src.blend_mode = .source_over
    elif src.blend_mode == .destination:
        return none
    elif src.blend_mode == .destination_in and just_solid_color(src.shader):
        return none
    # A Clear blend mode will ignore the entire color pipeline, as if Src mode with
    # 0x00000000.
    if src.blend_mode == .clear:
        src.shader = .solid_color(color = Color.transparent())
        src.blend_mode = .source
    # Dither is only needed for non-constant shaders.
    src.dither = paint.dither and not src.shader.is_constant()

    # create_pipeline_for_blitter: the paint's alpha is a pattern's opacity.
    var pixmap_src = dummy_pixmap_ref()
    match src.shader:
        .solid_color(color):
            # A color shader takes the paint's alpha into its color.
            var c = color
            if paint.alpha != 1.0:
                c.apply_opacity(paint.alpha)
                src.shader = .solid_color(color = c)
            src.is_constant = true
            src.is_opaque = c.alpha() == 1.0
        .pattern(patt):
            src.paint_alpha = patt.opacity * paint.alpha
            src.is_opaque = src.shader.is_opaque() and src.paint_alpha == 1.0
            pixmap_src = patt.pixmap
        _:
            src.paint_alpha = paint.alpha
            src.is_opaque = src.shader.is_opaque() and paint.alpha == 1.0

    # A color filter keeps the pipeline (no memset of a constant color).
    if paint.linear_to_srgb:
        src.is_constant = false

    # We can strength-reduce SrcOver into Src when opaque.
    if src.is_opaque and src.blend_mode == .source_over:
        src.blend_mode = .source
    return (src, pixmap_src)

## SkRasterPipelineBlitter: blits a paint through the raster pipeline.
struct RasterPipelineBlitter: Blitter:
    var pixmap_src: PixmapRef
    var pixmap: SubPixmapMut*
    var memset2d_color: PremultipliedColorU8?
    var blit_anti_h_rp: RasterPipeline
    var blit_rect_rp: RasterPipeline
    var blit_mask_rp: RasterPipeline

    ## SkBlitter::Choose and SkRasterPipelineBlitter::Create for `paint`; none when the paint
    ## draws nothing (SkNullBlitter) or its shader cannot draw.
    static func new_(paint: const Paint*, pixmap: SubPixmapMut*) -> RasterPipelineBlitter?:
        let chosen = pipeline_source_of(paint) else return none
        let src = chosen.0
        let pixmap_src = chosen.1
        var memset2d_color: PremultipliedColorU8? = none

        # When we're drawing a constant color in Src mode, we can sometimes just memset: the
        # color pipeline's uniform color, stored.
        if src.is_constant and src.blend_mode == .source:
            match src.shader:
                .solid_color(color):
                    let c = colorspace_expand_color(paint.colorspace, color).premultiply()
                    memset2d_color = PremultipliedColorU8.from_rgba_unchecked((u8)(c.red() * 255.0 + 0.5), (u8)(c.green() * 255.0 + 0.5), (u8)(c.blue() * 255.0 + 0.5), (u8)(c.alpha() * 255.0 + 0.5))
                _:
                    memset2d_color = none

        # Only the shader's stages can fail (a non-invertible matrix), so the first build
        # decides for all three.
        let blit_anti_h_rp = src.build_coverage(.scale_1_float, .lerp_1_float) else return none
        let blit_rect_rp = src.build_rect() else trap("unreachable")
        let blit_mask_rp = src.build_coverage(.scale_u8, .lerp_u8) else trap("unreachable")

        return RasterPipelineBlitter(
            pixmap_src = pixmap_src,
            pixmap = pixmap,
            memset2d_color = memset2d_color,
            blit_anti_h_rp = blit_anti_h_rp,
            blit_rect_rp = blit_rect_rp,
            blit_mask_rp = blit_mask_rp,
        )

    ## Frees the compiled pipelines.
    func release():
        self.blit_anti_h_rp.release()
        self.blit_rect_rp.release()
        self.blit_mask_rp.release()

    pub func blit_h(x: i32, y: i32, width: i32):
        self.blit_rect(x, y, width, 1)

    pub func blit_anti_h(x0: i32, y: i32, aa: AlphaU8[], runs: AlphaRun[]):
        var x = x0
        var aa_offset: usize = 0
        var run_offset: usize = 0
        var run = runs[0]
        while run != 0:
            let width = (i32)run

            let alpha = aa[aa_offset]
            if alpha == alpha_u8_opaque:
                self.blit_h(x, y, width)
            elif alpha != alpha_u8_transparent:
                self.blit_anti_h_rp.ctx.current_coverage = (f32)alpha * (1.0 / 255.0)

                let rect = ScreenIntRect.from_xywh_safe((u32)x, (u32)y, (u32)width, 1)
                self.blit_anti_h_rp.run(rect, AAMaskCtx(), MaskCtx(), self.pixmap_src, self.pixmap)

            x += width
            run_offset += (usize)run
            aa_offset += (usize)run
            run = runs[run_offset]

    pub func blit_v(x: i32, y: i32, height: i32, alpha: AlphaU8):
        let bounds = IRect.xywh(x, y, 1, height)
        let image: u8[1] = [alpha]
        let mask = BlitMask(image = image, bounds = bounds, row_bytes = 0)  # so we reuse the 1 "row" for all of height

        self.blit_mask(&mask, bounds)

    pub func blit_anti_h2(x: i32, y: i32, alpha0: AlphaU8, alpha1: AlphaU8):
        let bounds = IRect.xywh(x, y, 2, 1)
        let image: u8[2] = [alpha0, alpha1]
        let mask = BlitMask(image = image, bounds = bounds, row_bytes = 2)

        self.blit_mask(&mask, bounds)

    pub func blit_anti_v2(x: i32, y: i32, alpha0: AlphaU8, alpha1: AlphaU8):
        let bounds = IRect.xywh(x, y, 1, 2)
        let image: u8[2] = [alpha0, alpha1]
        let mask = BlitMask(image = image, bounds = bounds, row_bytes = 1)

        self.blit_mask(&mask, bounds)

    pub func blit_rect(x: i32, y: i32, width: i32, height: i32):
        let rect = ScreenIntRect.from_xywh_safe((u32)x, (u32)y, (u32)width, (u32)height)
        if let c = self.memset2d_color:
            let pixels = self.pixmap.pixels_mut()
            for yy in 0..<rect.height():
                let start = self.pixmap.offset((usize)rect.x(), (usize)(rect.y() + yy))
                let end = start + (usize)rect.width()
                for p in &pixels[start..<end]:
                    *p = c
            return

        self.blit_rect_rp.run(rect, AAMaskCtx(), MaskCtx(), self.pixmap_src, self.pixmap)

    pub func blit_anti_rect(x: i32, y: i32, width: i32, height: i32, left_alpha: AlphaU8, right_alpha: AlphaU8):
        blitter_default_blit_anti_rect(&self, x, y, width, height, left_alpha, right_alpha)

    pub func blit_mask(mask: const BlitMask*, clip: IRect):
        # The mask's pixels from the clip's top-left, lined up with the pixmap at (0, 0).
        let start = mask.index(clip.left, clip.top)
        let aa_mask_ctx = AAMaskCtx(pixels = mask.image[start..], stride = mask.row_bytes, shift = (usize)clip.left + (usize)clip.top * (usize)mask.row_bytes)

        self.blit_mask_rp.run(clip.to_screen(), aa_mask_ctx, MaskCtx(), self.pixmap_src, self.pixmap)

## The 1x1 transparent pixmap the pipeline gets when there is no pattern.
let dummy_pixel: u8[4] = [0, 0, 0, 0]

func dummy_pixmap_ref() -> PixmapRef:
    return PixmapRef.from_bytes(dummy_pixel, 1, 1) else trap("unreachable")