Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.1

0.6.1 / src / raster / mask.lucb

#==============================================================================================
#
#   mask - 8-bit clip masks
#
#   DESCRIPTION:
#       Port of tiny-skia mask.rs: MaskType, Mask (owns its bytes; `release()` frees them),
#       Mask.fill_path, intersect_path, invert, clear, and SubMaskRef. A mask is what Skia
#       holds as a clip (see blitter_clip.lucb), so filling a path into it follows Skia
#       m144's SkAAClip::setPath and SkRegion::setPath (the analytic AA filler forced into
#       its run-length mode, writing through MaskBuilderBlitter, the SkAAClip builder's
#       blitter).
#
#==============================================================================================

## A mask type.
pub enum MaskType as u8:
    ## Transfers only the Alpha channel from `Pixmap` to `Mask`.
    alpha = 0
    ## Transfers RGB channels as luminance from `Pixmap` to `Mask`. Formula:
    ## `Y = 0.2125 * R + 0.7154 * G + 0.0721 * B`
    luminance = 1

## A mask. During drawing over `Pixmap`, mask's black (0) "pixels" would block rendering and
## white (255) will allow it. Anything in between is used for anti-aliasing and to represent
## partially transparent drawing. Unlike Skia, we're using just a simple 8bit alpha mask.
## It's way slower, but easier to implement.
pub struct Mask:
    var data_: u8[]
    var size_: IntSize

    ## Creates a new mask by taking ownership over a mask buffer. The size needs to match
    ## the data provided.
    pub static func new_(width: u32, height: u32) -> Mask?:
        let size = IntSize.from_wh(width, height) else return none
        let data = (new u8[(usize)width * (usize)height] in memory.heap) else trap("raster: out of memory")
        return Mask(data_ = data, size_ = size)

    ## Creates a new mask from a `PixmapRef`.
    pub static func from_pixmap(pixmap: PixmapRef, mask_type: MaskType) -> Mask:
        let data_len = (usize)pixmap.width() * (usize)pixmap.height()
        let data = (new u8[data_len] in memory.heap) else trap("raster: out of memory")
        let mask = Mask(data_ = data, size_ = pixmap.size())

        # TODO: optimize
        let pixels = pixmap.pixels()
        match mask_type:
            .alpha:
                for i in 0..<data_len:
                    data[i] = pixels[i].alpha()
            .luminance:
                for i in 0..<data_len:
                    let p = pixels[i]
                    # Normalize.
                    var r = (f32)p.red() / 255.0
                    var g = (f32)p.green() / 255.0
                    var b = (f32)p.blue() / 255.0
                    let a = (f32)p.alpha() / 255.0

                    # Demultiply.
                    if p.alpha() != 0:
                        r /= a
                        g /= a
                        b /= a

                    let luma = r * 0.2126 + g * 0.7152 + b * 0.0722
                    data[i] = (u8)math32.ceil(clamp_f32((luma * a) * 255.0, 0.0, 255.0))
            _:
                return mask

        return mask

    ## Creates a new mask by taking ownership over a mask buffer allocated in `memory.heap`.
    ## The size needs to match the data provided.
    pub static func from_vec(data: u8[], size: IntSize) -> Mask?:
        let data_len = (usize)size.width() * (usize)size.height()
        if data.length != data_len:
            return none
        return Mask(data_ = data, size_ = size)

    ## Returns mask's width.
    pub func width() -> u32:
        return self.size_.width()

    ## Returns mask's height.
    pub func height() -> u32:
        return self.size_.height()

    func size() -> IntSize:
        return self.size_

    ## Returns the internal data.
    pub func data() -> const u8[]:
        return self.data_

    ## Returns the mutable internal data.
    pub func data_mut() -> u8[]:
        return self.data_

    ## Consumes the internal data. The caller owns the bytes (free them in `memory.heap`).
    pub func take() -> u8[]:
        let data = self.data_
        self.data_ = self.data_[..<0]
        return data

    ## Frees the mask.
    pub func release():
        if self.data_.length > 0:
            free(self.data_) in memory.heap
        self.data_ = self.data_[..<0]

    func as_submask() -> SubMaskRef:
        return SubMaskRef(data = self.data_, size = self.size_, real_width = self.size_.width())

    func submask(rect0: IntRect) -> SubMaskRef?:
        let rect = self.size_.to_int_rect(0, 0).intersect(rect0) else return none
        let row_bytes = (usize)self.width()
        let offset = (usize)rect.top() * row_bytes + (usize)rect.left()
        return SubMaskRef(data = self.data_[offset..], size = rect.size(), real_width = self.size_.width())

    func as_subpixmap() -> SubPixmapMut:
        return SubPixmapMut(data = self.data_, size = self.size_, real_width = (usize)self.size_.width())

    func subpixmap(rect0: IntRect) -> SubPixmapMut?:
        let rect = self.size_.to_int_rect(0, 0).intersect(rect0) else return none
        let row_bytes = (usize)self.width()
        let offset = (usize)rect.top() * row_bytes + (usize)rect.left()
        return SubPixmapMut(data = self.data_[offset..], size = rect.size(), real_width = (usize)self.size_.width())

    ## Draws a filled path onto the mask. In terms of RGB (no alpha) image, draws a white
    ## path on top of black mask. Doesn't reset the existing mask content and draws the path
    ## on top of existing data. If the above behavior is undesired, `Mask.clear()` should
    ## be called first. On a clear mask the result is the clip Skia's SkAAClip::setPath (or,
    ## without anti-aliasing, SkRegion::setPath) makes of the path. For more complex masks
    ## prefer `Mask.from_pixmap`.
    pub func fill_path(path: const Path*, fill_rule: FillRule, anti_alias: bool, transform: Transform):
        self.fill_path_clipped(path, fill_rule, anti_alias, transform, IRect.ltrb(0, 0, (i32)self.width(), (i32)self.height()))

    ## fill_path, with the path's coverage clipped to `clip` (the bounds of the clip the path
    ## is set in).
    func fill_path_clipped(path: const Path*, fill_rule: FillRule, anti_alias: bool, transform: Transform, clip: IRect):
        if not transform.is_identity():
            var transformed = path.clone()
            defer transformed.release()
            # SkRasterClip::op(path, matrix): SkPath::makeTransform.
            if not transformed.transform_with(transform, .path_iter):
                # log::warn!("path transformation failed")
                return
            self.fill_path_clipped(&transformed, fill_rule, anti_alias, Transform.identity(), clip)
            return

        if is_too_big_for_math(path):
            # log::warn!("path coordinates are too big")
            return

        # Since we assert that the BuilderBlitter will never blit outside the intersection of
        # clip and ibounds, we create the builder with the snug bounds.
        let bounds = irect_round_out(path.bounds()).intersect(clip) else return
        var builder = MaskBuilderBlitter(mask = &self, bounds = bounds)
        let rect_clip = RasterClip(kind = .rect, bounds = bounds, mask = none)
        if anti_alias:
            anti_fill_path_rgn(path, fill_rule, &rect_clip, &builder, true)
        else:
            fill_path_rgn(path, fill_rule, &rect_clip, &builder)

    ## Intersects the provided path with the current clipping path. A temporary mask with
    ## the same size as the current one will be created. The coverages multiply, as
    ## SkAAClip's intersection does.
    pub func intersect_path(path: const Path*, fill_rule: FillRule, anti_alias: bool, transform: Transform):
        var submask = Mask.new_(self.width(), self.height()) else trap("unreachable")
        defer submask.release()
        # The new path's coverage is computed within the current clip's bounds
        # (SkRasterClip::op builds the path's clip with getBounds()).
        let info = MaskClipInfo.of(&self)
        var clip = IRect.ltrb(0, 0, (i32)self.width(), (i32)self.height())
        if info.kind != .empty:
            clip = info.bounds
        submask.fill_path_clipped(path, fill_rule, anti_alias, transform, clip)

        for i in 0..<self.data_.length:
            self.data_[i] = premultiply_u8(self.data_[i], submask.data_[i])

    ## Inverts the mask.
    pub func invert():
        for a in &self.data_:
            *a = 255 - *a

    ## Clears the mask. Zero-fills the internal data buffer.
    pub func clear():
        for a in &self.data_:
            *a = 0

## Rust's `f32::clamp`: NaN stays NaN.
func clamp_f32(x: f32, min: f32, max: f32) -> f32:
    var v = x
    if v < min:
        v = min
    if v > max:
        v = max
    return v

struct SubMaskRef:
    var data: const u8[]
    var size: IntSize
    var real_width: u32

    func mask_ctx() -> MaskCtx:
        return MaskCtx(data = self.data, real_width = self.real_width)

# mark: MaskBuilderBlitter ====================================================================

## SkAAClip::Builder::Blitter: writes coverage into a mask, within `bounds` (the builder
## trims the analytic filler's tiny spills past the path's bounds). The coverage is drawn
## over the existing value (on a clear mask it is the coverage).
struct MaskBuilderBlitter: Blitter:
    var mask: Mask*
    var bounds: IRect

    func put(x: i32, y: i32, alpha: u8):
        if x < self.bounds.left or x >= self.bounds.right or y < self.bounds.top or y >= self.bounds.bottom:
            return
        let i = (usize)y * (usize)self.mask.width() + (usize)x
        let old = (u32)self.mask.data_[i]
        let a = (u32)alpha
        self.mask.data_[i] = (u8)(a + mul_div255_round(old, 255 - a))

    pub func blit_h(x: i32, y: i32, width: i32):
        for i in 0..<width:
            self.put(x + i, y, 0xFF)

    pub func blit_anti_h(x: i32, y: i32, antialias: AlphaU8[], runs: AlphaRun[]):
        var i: usize = 0
        while runs[i] != 0:
            let count = (usize)runs[i]
            for j in 0..<count:
                self.put(x + (i32)(i + j), y, antialias[i])
            i += count

    pub func blit_v(x: i32, y: i32, height: i32, alpha: AlphaU8):
        for i in 0..<height:
            self.put(x, y + i, alpha)

    pub func blit_rect(x: i32, y: i32, width: i32, height: i32):
        for yy in y..<y + height:
            self.blit_h(x, yy, width)

    pub func blit_anti_rect(x0: i32, y: i32, width0: i32, height: i32, left_alpha: AlphaU8, right_alpha: AlphaU8):
        # addAntiRectRun: no matter whether left_alpha is 0 or positive, [x, x+1] is the
        # left-most column and [x+1, x+1+width] the rect with full alpha.
        for row in y..<y + height:
            if left_alpha > 0:
                self.put(x0, row, left_alpha)
            for i in 0..<width0:
                self.put(x0 + 1 + i, row, 0xFF)
            if right_alpha > 0:
                self.put(x0 + 1 + width0, row, right_alpha)

    pub func blit_mask(mask: const BlitMask*, clip: IRect):
        trap("raster: ---- did not expect to get called here")

    pub func blit_anti_h2(x: i32, y: i32, alpha0: AlphaU8, alpha1: AlphaU8):
        blitter_default_blit_anti_h2(&self, x, y, alpha0, alpha1)

    pub func blit_anti_v2(x: i32, y: i32, alpha0: AlphaU8, alpha1: AlphaU8):
        blitter_default_blit_anti_v2(&self, x, y, alpha0, alpha1)