dymokomi/luce-browser-render
Source of release 0.6.1
0.6.1 / src / raster / pipeline.lucb
#==============================================================================================
#
# pipeline - the raster pipeline: stages, contexts, builder and compiled pipeline
#
# DESCRIPTION:
# Port of tiny-skia pipeline/mod.rs, brought to Skia m144's SkRasterPipeline
# (src/core/SkRasterPipeline.cpp) as Ladybird's libskia runs it on arm64:
#
# 1. A pipeline consists of stages; each calls the next one when it is done.
# 2. A pipeline has one context shared by all stages (Skia gives each stage its own).
# 3. Each stage has a high precision implementation (highp*.lucb); the stages m144 has
# a lowp implementation of have one too (lowp*.lucb).
# 4. Compiling picks lowp when **all** stages have a lowp implementation (Skia's
# buildLowpPipeline), unless high precision is forced (Skia's test hook
# gForceHighPrecisionRasterPipeline: `set_force_highp_pipeline`, or a builder's
# `set_force_hq_pipeline`).
# 5. The compiled program is a list of function pointers ending in "return".
#
# Where Skia runs a chain of stages that only pass state through their contexts (the
# bilinear and bicubic samplers: *_setup, the per-tap x/y setup, tiling, gather and
# accumulate), one fused stage here computes the same operations in the same order.
#
# A compiled RasterPipeline owns its gradient context; `release()` frees it.
#
# 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)
#
#==============================================================================================
let max_stages: usize = 32 # More than enough.
enum Stage as u8:
move_source_to_destination = 0
move_destination_to_source = 1
clamp_01 = 2
clamp_gamut = 3
premultiply = 4
uniform_color = 5
seed_shader = 6
load_destination = 7
store = 8
load_destination_u8 = 9
store_u8 = 10
gather = 11
load_mask_u8 = 12
mask_u8 = 13
scale_u8 = 14
lerp_u8 = 15
scale_1_float = 16
lerp_1_float = 17
scale_paint_alpha = 18
dither = 19
destination_atop = 20
destination_in = 21
destination_out = 22
destination_over = 23
source_atop = 24
source_in = 25
source_out = 26
source_over = 27
clear = 28
modulate = 29
multiply = 30
plus = 31
screen = 32
xor = 33
color_burn = 34
color_dodge = 35
darken = 36
difference = 37
exclusion = 38
hard_light = 39
lighten = 40
overlay = 41
soft_light = 42
hue = 43
saturation = 44
color = 45
luminosity = 46
transform = 47
scale_translate_x = 48
repeat = 49
mirror = 50
bilinear = 51
bicubic = 52
bilerp_clamp_8888 = 53
bicubic_clamp_8888 = 54
clamp_x_1 = 55
mirror_x_1 = 56
repeat_x_1 = 57
gradient = 58
evenly_spaced_gradient = 59
evenly_spaced_2_stop_gradient = 60
xy_to_unit_angle = 61
xy_to_radius = 62
xy_to_2pt_conical_focal_on_circle = 63
xy_to_2pt_conical_well_behaved = 64
xy_to_2pt_conical_smaller = 65
xy_to_2pt_conical_greater = 66
xy_to_2pt_conical_strip = 67
mask_2pt_conical_nan = 68
mask_2pt_conical_degenerates = 69
apply_vector_mask = 70
alter_2pt_conical_compensate_focal = 71
alter_2pt_conical_unswap = 72
negate_x = 73
gamma_expand_2 = 74
gamma_expand_destination_2 = 75
gamma_compress_2 = 76
gamma_expand_22 = 77
gamma_expand_destination_22 = 78
gamma_compress_22 = 79
gamma_expand_srgb = 80
gamma_expand_destination_srgb = 81
gamma_compress_srgb = 82
transform_perspective = 83
unpremul = 84
unpremul_polar = 85
css_lab_to_xyz = 86
css_oklab_to_linear_srgb = 87
css_hcl_to_lab = 88
css_hsl_to_srgb = 89
css_hwb_to_srgb = 90
bilinear_mipmap = 91
color_xform = 92
color_filter_xform = 93
let stages_count: usize = 94
## Skia's gForceHighPrecisionRasterPipeline: every pipeline compiles to highp while set.
var force_highp: bool = false
## Forces every raster pipeline built from now on to high precision (Skia's test hook
## gForceHighPrecisionRasterPipeline), or lets them pick lowp again.
pub func set_force_highp_pipeline(force: bool):
force_highp = force
# mark: Contexts ==============================================================================
## The coverage of a blitted mask (Skia's MemoryCtx of scale_u8 / lerp_u8): lane `i` of the
## stage at (dx, dy) reads `pixels[stride * dy + dx + i - shift]`. `shift` is the offset of the
## span's first byte in pixmap coordinates (mask left + mask top * stride); a zero stride
## repeats one row.
struct AAMaskCtx:
var pixels: const u8[]
var stride: u32 # can be zero
var shift: usize # mask offset/position in pixmap coordinates
## The coverage of `count` lanes from (dx, dy) into `out`.
func load(dx: usize, dy: usize, count: usize, out: u8[]):
let offset = ((usize)self.stride * dy + dx) - self.shift
for i in 0..<count:
out[i] = self.pixels[offset + i]
struct MaskCtx:
var data: const u8[]
var real_width: u32
func offset(dx: usize, dy: usize) -> usize:
return (usize)self.real_width * dy + dx
struct Context:
var current_coverage: f32 # blitAntiH's coverage (scale_1_float, lerp_1_float)
var paint_alpha: f32 # the paint's alpha after the shader (scale_paint_alpha)
var dither_rate: f32
var uniform_color: UniformColorCtx
var evenly_spaced_2_stop_gradient: EvenlySpaced2StopGradientCtx
var gradient: GradientCtx
var two_point_conical_gradient: TwoPointConicalGradientCtx
var scale_translate_x: ScaleTranslateCtx
var limit_x: TileCtx
var limit_y: TileCtx
var gather: GatherCtx
var sampler: SamplerCtx
var color_xform: ColorXform # the shader's steps to the destination's color space
var color_filter_xform: ColorXform # the steps of a color space transform color filter
var transform: Transform = Transform()
var mipmap: MipmapCtx # the mip levels a mipmapped pattern samples
## The tile modes of the fused bilinear / bicubic samplers (Skia appends repeat_x / mirror_x
## and repeat_y / mirror_y per tap).
struct SamplerCtx:
var spread_mode: SpreadMode
## Skia's GatherCtx: the image is the pipeline's source pixmap (stride = width).
struct GatherCtx:
var width: f32
var height: f32
var round_down_at_integer: u32 # 1 for nearest sampling: integer coordinates snap left/up
var weights: f32[16] # the bicubic resampler's matrix, column-major
struct UniformColorCtx:
var r: f32
var g: f32
var b: f32
var a: f32
var rgba: u16[4] # [0,255] in a 16-bit lane.
# A gradient color is an RGBA not in a 0..1 range (unpremultiplied unless the gradient
# interpolates premultiplied). It basically can have any float value.
struct GradientColor:
var r: f32
var g: f32
var b: f32
var a: f32
static func new_(r: f32, g: f32, b: f32, a: f32) -> GradientColor:
return GradientColor(r = r, g = g, b = b, a = a)
static func from_color(c: Color) -> GradientColor:
return GradientColor(r = c.red(), g = c.green(), b = c.blue(), a = c.alpha())
func equals(o: GradientColor) -> bool:
return self.r == o.r and self.g == o.g and self.b == o.b and self.a == o.a
struct EvenlySpaced2StopGradientCtx:
var factor: GradientColor
var bias: GradientColor
## Skia's GradientCtx: `len` stops, each a factor and a bias (color = factor * t + bias), and
## the t where each stop starts (the arbitrary-stop search; unused by evenly spaced ones).
## The arrays hold at least 16 entries, so any lane index below 16 is in bounds.
struct GradientCtx:
var len: usize
var factors: Vec[GradientColor]
var biases: Vec[GradientColor]
var t_values: Vec[f32]
func push_stop(factor: GradientColor, bias: GradientColor):
self.factors.push(factor)
self.biases.push(bias)
func push_const_color(color: GradientColor):
self.push_stop(GradientColor.new_(0.0, 0.0, 0.0, 0.0), color)
func release():
self.factors.release()
self.biases.release()
self.t_values.release()
struct TwoPointConicalGradientCtx:
# This context is used only in highp, where we use Tx4.
var mask: M8
var p0: f32
var p1: f32
## A scale-translate matrix appended after the gradient's main one (Skia's appendMatrix of the
## sweep's t scale and bias, or the concentric radial's): x = x * sx + tx.
struct ScaleTranslateCtx:
var sx: f32
var tx: f32
## The mip levels of a mipmapped pattern (SkMipmapAccessor's upper and lower levels and
## SkRasterPipelineContexts::MipmapCtx). The pipeline owns `levels`.
struct MipmapCtx:
var levels: Vec[Pixmap]
## The level sampled instead of the source pixmap, if any.
var upper: PixmapRef?
## The level below it and its weight (bilinear_mipmap).
var lower: PixmapRef?
var lower_weight: f32
## The lower level's size over the upper's.
var scale_x: f32
var scale_y: f32
var lower_gather: GatherCtx
var lower_limit_x: TileCtx
var lower_limit_y: TileCtx
func release():
for i in 0..<self.levels.len:
self.levels.data[i].release()
self.levels.release()
self.upper = none
self.lower = none
struct TileCtx:
var scale: f32
var inv_scale: f32 # cache of 1/scale
var mirror_bias_dir: u32 # 1 for nearest sampling, else -1 (see SkImageShader's MipLevelHelper)
# mark: Builder ===============================================================================
struct RasterPipelineBuilder:
var stages: Stage[32]
var stages_len: usize
var force_hq_pipeline: bool
var ctx: Context
static func new_() -> RasterPipelineBuilder:
return RasterPipelineBuilder(ctx = Context())
## Compiles this pipeline to highp (a test hook, as Skia's global one).
func set_force_hq_pipeline(hq: bool):
self.force_hq_pipeline = hq
func push(stage: Stage):
if self.stages_len == max_stages:
trap("raster: too many pipeline stages")
self.stages[self.stages_len] = stage
self.stages_len += 1
## Skia's appendMatrix: nothing for the identity, matrix_perspective for a matrix with
## perspective (the affine stage computes the same values for every other kind).
func push_transform(ts: Transform):
if ts.is_finite() and not ts.is_identity():
self.push(.transform_perspective if ts.has_perspective() else .transform)
self.ctx.transform = ts
## SkColorSpaceXformSteps::apply(SkRasterPipeline*): unpremul and premul as their own
## stages (premul has a lowp form), the steps between them as one color_xform.
func push_color_xform(x: ColorXform):
let flags = x.steps.flags
if flags.unpremul:
self.push(.unpremul)
var middle = x
middle.steps.flags.unpremul = false
middle.steps.flags.premul = false
if not middle.steps.is_identity():
self.ctx.color_xform = middle
self.push(.color_xform)
if flags.premul:
self.push(.premultiply)
## Skia's appendMatrix of a matrix that only scales and translates x.
func push_scale_translate_x(sx: f32, tx: f32):
if sx != 1.0 or tx != 0.0:
self.ctx.scale_translate_x = ScaleTranslateCtx(sx = sx, tx = tx)
self.push(.scale_translate_x)
## Skia's appendConstantColor of a premultiplied color in range.
func push_uniform_color(c: PremultipliedColor):
let r = c.red()
let g = c.green()
let b = c.blue()
let a = c.alpha()
# To make loads more direct, we store 8-bit values in 16-bit slots.
let rgba: u16[4] = [(u16)(r * 255.0 + 0.5), (u16)(g * 255.0 + 0.5), (u16)(b * 255.0 + 0.5), (u16)(a * 255.0 + 0.5)]
self.push(.uniform_color)
self.ctx.uniform_color = UniformColorCtx(r = r, g = g, b = b, a = a, rgba = rgba)
## Frees the builder's context (when it is not compiled).
func release():
self.ctx.gradient.release()
self.ctx.mipmap.release()
## Compiles the pipeline; the builder's context moves into it.
func compile() -> RasterPipeline:
var p: RasterPipeline = ---
p.len = 0
p.is_lowp = false
if self.stages_len == 0:
p.ctx = Context()
self.release()
return p
var is_lowp_compatible = not force_highp and not self.force_hq_pipeline
for stage in self.stages[..<self.stages_len]:
if (void*)lowp_stages[(usize)stage] == (void*)lowp_null_fn:
is_lowp_compatible = false
if not is_lowp_compatible:
for i in 0..<self.stages_len:
p.highp_functions[i] = highp_stages[(usize)self.stages[i]]
p.highp_functions[self.stages_len] = highp_just_return
p.len = self.stages_len + 1
# Skia patches the memory contexts of the last, partial chunk of a row to point at
# scratch memory; here the load and store stages have "tail" variants instead.
for i in 0..<p.len:
let fun = p.highp_functions[i]
var tail_fun = fun
if (void*)fun == (void*)highp_load_dst:
tail_fun = highp_load_dst_tail
elif (void*)fun == (void*)highp_store:
tail_fun = highp_store_tail
elif (void*)fun == (void*)highp_load_dst_u8:
tail_fun = highp_load_dst_u8_tail
elif (void*)fun == (void*)highp_store_u8:
tail_fun = highp_store_u8_tail
p.highp_tail_functions[i] = tail_fun
else:
p.is_lowp = true
var n: usize = 0
var k: usize = 0
while k < self.stages_len:
# load_dst, srcover, store in one stage: the same u16 math with one call.
if k + 2 < self.stages_len and self.stages[k] == .load_destination and self.stages[k + 1] == .source_over and self.stages[k + 2] == .store:
p.lowp_functions[n] = lowp_source_over_rgba
k += 3
else:
p.lowp_functions[n] = lowp_stages[(usize)self.stages[k]]
k += 1
n += 1
p.lowp_functions[n] = lowp_just_return
p.len = n + 1
# See above.
for i in 0..<p.len:
let fun = p.lowp_functions[i]
var tail_fun = fun
if (void*)fun == (void*)lowp_load_dst:
tail_fun = lowp_load_dst_tail
elif (void*)fun == (void*)lowp_store:
tail_fun = lowp_store_tail
elif (void*)fun == (void*)lowp_load_dst_u8:
tail_fun = lowp_load_dst_u8_tail
elif (void*)fun == (void*)lowp_store_u8:
tail_fun = lowp_store_u8_tail
elif (void*)fun == (void*)lowp_source_over_rgba:
tail_fun = lowp_source_over_rgba_tail
p.lowp_tail_functions[i] = tail_fun
p.ctx = self.ctx
self.ctx = Context()
return p
# mark: Pipeline ==============================================================================
struct RasterPipeline:
var is_lowp: bool
var len: usize
var highp_functions: HighpStageFn[33]
var highp_tail_functions: HighpStageFn[33]
var lowp_functions: LowpStageFn[33]
var lowp_tail_functions: LowpStageFn[33]
var ctx: Context
func run(rect: ScreenIntRect, aa_mask_ctx: AAMaskCtx, mask_ctx: MaskCtx, pixmap_src0: PixmapRef, pixmap_dst: SubPixmapMut*):
# A mipmapped pattern samples its upper level instead of the source image.
let pixmap_src = self.ctx.mipmap.upper else pixmap_src0
if self.is_lowp:
lowp_start(self.lowp_functions[..<self.len], self.lowp_tail_functions[..<self.len], rect, aa_mask_ctx, mask_ctx, &self.ctx, pixmap_src, pixmap_dst)
else:
highp_start(self.highp_functions[..<self.len], self.highp_tail_functions[..<self.len], rect, aa_mask_ctx, mask_ctx, &self.ctx, pixmap_src, pixmap_dst)
func release():
self.ctx.gradient.release()
self.ctx.mipmap.release()