Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.1

0.6.1 / src / raster / module.lucb

#==============================================================================================
#
#   raster - the CPU rasterizer of luce-browser: tiny-skia made to paint as Skia m144
#
#   DESCRIPTION:
#       A port of tiny-skia 0.12.0 (linebender/tiny-skia at 5d47547) and its
#       tiny-skia-path crate to luce-base -- pixmaps and masks, premultiplied colors, paints
#       and shaders (solid color, linear, radial and sweep gradients, patterns), every
#       blend mode, the raster pipeline (lowp and highp stages), paths (builder, transforms,
#       stroker, dasher, bezier math), the scan converters and clip masks -- changed
#       wherever Skia m144 (the libskia Ladybird 47c82b38d0 paints with) computes something
#       else, so that every pixel is the one Ladybird's Skia backend produces on arm64:
#
#       - Anti-aliased filling is Skia's analytic AA (SkScan_AAAPath: analytic_edge*,
#         scan_aaa_*), not 4x4 supersampling; non-AA filling sorts and walks edges as
#         SkScan_Path does, with SkTQSort (tsort) and convexity (path_convexity).
#       - Clips follow SkRasterClip (scan_raster_clip, blitter_clip): a Mask is a rect, a
#         region or an SkAAClip, and Mask.fill_path builds it the way SkAAClip::setPath does.
#       - Paths keep conics (SkConic, AutoConicToQuads) and convert them where Skia does.
#         Chopping uses m144's SkChopCubicAt and the double-precision SkChopMonoCubicAt
#         (cubics); anti-aliased hairlines are m144's (scan_antihair); the stroker keeps
#         m144's tangent vectors and conic stroking (stroker_conics).
#       - Transforms keep SkMatrix's perspective row (transform.lucb): paths under
#         perspective are cut at w = 0 and projected as SkPath::transform does
#         (path_perspective), and shaders sample through matrix_perspective.
#       - Drawing follows SkDraw (draw.lucb): the blitter is SkRasterPipelineBlitter, as
#         Ladybird's BGRA surfaces are not kN32 in this Skia build, except for solid colors
#         in the kN32 layers Skia makes for image filters (Pixmap.set_n32), which take the
#         legacy SkARGB32 blitters (legacy_blitter.lucb). The pipeline, its
#         blitter and the shaders' stages compute what m144 computes on arm64 NEON: lowp's
#         rounding div255, highp's fused mad and NEON min/max/rounding/reciprocal
#         estimates, m144's lowp stage set, gradient stops and stages, image sampling (the
#         NEON arithmetic is isolated in lowp's `div255`, `highp_mad` and wide.lucb's "NEON
#         arithmetic"). x86 Skia rounds differently there and is not matched.
#
#       tests/raster checks tiny-skia's scenes, the pipeline scenes and Ladybird-style
#       scenes against images rendered by Skia m144 itself. Fragments ported from Skia
#       credit it in their header (see LICENSE-skia). Elsewhere the port keeps
#       tiny-skia's structure, constants, comments and names (snake_case; `Type::new` is
#       `Type.new_`, since `new` is reserved). The design notes that apply to every
#       fragment:
#
#       - Rust's SIMD wrapper types become arrays of 16-byte Luce vectors: f32x8 is
#         `F4[2]`, u16x16 is `U16x8[2]`, f32x16 is `F4[4]`, with the lane-wise operators
#         where Luce has them and small per-lane helpers where it does not (min, max,
#         comparisons, select). The lane counts (8 for highp, 16 for lowp) are kept,
#         because tiny-skia's mask stages skip whole chunks.
#       - Memory: every buffer is allocated from `memory.heap` (the raster module is
#         standalone and does not use the browser's GC, DESIGN.md ยง3). Types that own
#         memory (Pixmap, Mask, Path, PathBuilder, StrokeDash, gradient shaders, the
#         pipeline) have a `release()` method, the Rust `Drop`. Running out of memory traps,
#         as Rust aborts.
#       - `Option<T>` is `T?`; tiny-skia's strict number types (FiniteF32, NormalizedF32,
#         NonZeroPositiveF32, LengthU32, NonZeroU16) are the plain scalars, validated where
#         tiny-skia constructs them. `debug_assert!`s are not ported.
#       - Rust integer arithmetic is checked (`+` traps like a Rust debug build); Skia's
#         intentional wrap-arounds (u16 lowp lanes, unsigned "in range" tricks) use the
#         wrapping operators.
#       - Rust's f32::min/max ignore NaN: `fmin`/`fmax`. tiny-skia's "faster" min/max are
#         `pmin`/`pmax`.
#       - Bit-exactness needs IEEE f32 arithmetic without contraction (Skia builds with
#         -ffp-contract=off; where it fuses, the port calls math32.fma): both backends give
#         it (the C backend fused `a * b + c` before Luce 0.8.13, see
#         .donors/luce-browser-tools/compiler-issues/c_backend_float_contraction.lucb).
#       - The two crates and their Rust submodules share one Luce module, so free
#         functions whose names collide carry the name of their Rust module as a prefix:
#         `highp_`/`lowp_` for the pipeline stages, `scan_`, `scan_aa_`, `hairline_`,
#         `hairline_aa_` for the scan converters.
#
#       Copyright (c) 2011 Google Inc. All rights reserved.
#       Copyright (c) 2020 Yevhenii Reizner All rights reserved.
#       Copyright (c) 2026 the luce-browser authors.
#       SPDX-License-Identifier: BSD-3-Clause (see LICENSE-tiny-skia, LICENSE-skia)
#
#==============================================================================================

import memory
from luce_std import math32, math
from luce_color import icc

# mark: Vec ===================================================================================

## A growable array in `memory.heap`: Rust's `Vec<T>`, private to the module. Out of memory
## traps, as Rust's allocation failure aborts.
struct Vec[T]:
    var data: T[]
    var len: usize

    ## The elements.
    func view() -> T[]:
        return self.data[..<self.len]

    ## Whether there are no elements.
    func is_empty() -> bool:
        return self.len == 0

    ## The last element, if any.
    func last() -> T?:
        if self.len == 0:
            return none
        return self.data[self.len - 1]

    ## Make room for `additional` more elements.
    func reserve(additional: usize):
        let needed = self.len + additional
        if needed <= self.data.length:
            return
        var capacity = self.data.length * 2
        if capacity < needed:
            capacity = needed
        if capacity < 4:
            capacity = 4
        let fresh = (new T[capacity] --- in memory.heap) else trap("raster: out of memory")
        for i in 0..<self.len:
            fresh[i] = self.data[i]
        if self.data.length > 0:
            free(self.data) in memory.heap
        self.data = fresh

    ## Append `value`.
    func push(value: T):
        if self.len == self.data.length:
            self.reserve(1)
        self.data[self.len] = value
        self.len += 1

    ## Remove and return the last element.
    func pop() -> T?:
        if self.len == 0:
            return none
        self.len -= 1
        return self.data[self.len]

    ## Insert `value` at `index`, shifting the rest up.
    func insert(index: usize, value: T):
        if self.len == self.data.length:
            self.reserve(1)
        var i = self.len
        while i > index:
            self.data[i] = self.data[i - 1]
            i -= 1
        self.data[index] = value
        self.len += 1

    ## Append every element of `values`.
    func extend(values: const T[]):
        self.reserve(values.length)
        for value in values:
            self.data[self.len] = value
            self.len += 1

    ## Remove every element, keeping the storage.
    func clear():
        self.len = 0

    ## A copy with its own storage.
    func clone() -> Vec[T]:
        var copy: Vec[T]
        copy.extend(self.view())
        return copy

    ## Free the storage.
    func release():
        if self.data.length > 0:
            free(self.data) in memory.heap
        self.data = self.data[..<0]
        self.len = 0