gfx#
surfaces, the draw context, blend kernels, paths, strokes, masks, gradients -- crate root lib/gfx/lib.rs
gfx -- surfaces and the draw context (clip, origin, colour), fills, blits [src/gfx/surface.s]
Surface::new(w, h, fmt) zeroed pixels, stride 64-byte aligned (sides 0..65536)
Dc::new(w, h) / dc.begin(&sf) / dc.end() the draw context of a target; begin saves
clip, origin and opacity and resets them for another
target, end restores them (gfx_begin / gfx_end)
dc.begin_rows(&sf, row0, h) sf holds rows row0 .. row0 + sf.h of a target h rows
high (a row band drawn on a thread of its own): the
coordinates stay the target's, only the pixel rows move
dc: set_color(argb), set_opacity(op), clip_push(x, y, w, h) / clip_pop(), origin(x, y),
translate(dx, dy), fill / clear / hline / vline / frame / blit / blit_scaled (sf, ...)
set_parallel(f) / parallel() the loop large copies run on (the UI runtime passes the
worker pool's): a blit that copies XRGB rows from
COPY_PAR_MIN bytes on is cut into row bands on it, from
COPY_STREAM_MIN bytes on past the caches (a 4K canvas)
path (Path, 24.8 and float API), raster (Raster), stroke (Path::stroke), shapes (Shapes),
blend (row kernels), straight (straight-alpha rows), blendmode (paint.net blend modes),
tmask (tiled masks), flood (flood fill), gradient, pathdata (SVG path data), dash
Colours are straight 0xAARRGGBB; Dc keeps the premultiplied form for the kernels. The
surface is passed to every drawing call: Dc holds no pointer to it.
gfx crate root#
Re-exports: rt::fx::div255
FMT_XRGB: u8 = 0 // 0x??RRGGBB, alpha byte ignored (window framebuffer)
FMT_PARGB: u8 = 1 // premultiplied 0xAARRGGBB (images, layers)
FMT_A8: u8 = 2 // 8-bit coverage / mask
FMT_ARGB: u8 = 3 // straight 0xAARRGGBB = bytes B, G, R, A
SFF_OWNED: u8 = 1
SFF_OPAQUE: u8 = 2 // hint: every alpha is 255
FX_ONE: i32 = 256 // 24.8 fixed point: 1 pixel
RULE_NONZERO: u32 = 0
RULE_EVENODD: u32 = 1
JOIN_MITER: u32 = 0 // stroke style = join | cap << 4
JOIN_ROUND: u32 = 1
JOIN_BEVEL: u32 = 2
CAP_BUTT: u32 = 0
CAP_ROUND: u32 = 1
CAP_SQUARE: u32 = 2
ERR_FAIL: i32 = -1
ERR_NOMEM: i32 = -8
ERR_LIMIT: i32 = -15
/// a blit's plain copy (XRGB source) from this many bytes on runs in row bands on the loop of
/// set_parallel (gfxtest --bench-blit: a 1 MB copy takes about a fifth on 12 workers)
COPY_PAR_MIN: usize = 1 << 20
/// ... and from this many on with streaming stores (gfx::blend::copy_stream): source and target
/// together no longer fit the caches, the target is not read first. A 4K frame (32 MB): 1.9 ms on
/// 12 workers and the calling thread, 2.7 ms with plain stores, 5 ms on one thread (Ryzen 5 3600,
/// DDR4-3200, a loaded machine; the memory's limit for such a copy is about 1.7 ms there)
COPY_STREAM_MIN: usize = 12 << 20
type ParallelFor = fn(usize, &(dyn Fn(usize) + Sync))runs f(i) for every i in 0..n, possibly on several threads (img_core::ParallelFor)fn set_parallel(f: ParallelFor)the loop large copies run on (Dc::blit, COPY_PAR_MIN); the UI runtime passes a wrapper of plat::parallel_for -- gfx does not depend on plat. Without it they run on the calling thread (the same bytes)fn parallel() -> Option<ParallelFor>the loop set by set_parallelstruct Surfacepixels of one image: rows ofstridebytes (4 per pixel, A8: 1)px: Vec<u8>w: i32h: i32stride: i32fmt: u8flags: u8opac: u8-- layer opacity 0..255blend: u8-- layer blend mode
fn try_zeroed(n: usize) -> Option<Vec<u8>>n zeroed bytes | None when the memory is not there (instead of an abort). A probe reservation first, then vec![0; n]: that is alloc_zeroed, whose fresh pages need no clearing pass.
impl Surface
fn new(w: i32, h: i32, fmt: u8) -> Surfacezeroed pixels, stride 64-byte aligned; sides outside 0..65536 give an empty surface (surf_alloc fails). Byte lengths beyond the target's addressable allocation size also give an empty surface, before allocating pixels.fn try_new(w: i32, h: i32, fmt: u8) -> Option<Surface>likenew, but None (instead of an empty surface or an abort) when the size is invalid or the memory is not there (try_zeroed). For sizes that come from a file or from the user.fn new_a8_packed(w: i32, h: i32) -> Surfacea tightly packed A8 surface (glyph masks: stride = w)fn resize(&mut self, w: i32, h: i32)new size, same format; the contents are NOT kept [surf_resize]fn bpp(&self) -> usizebytes per pixelstruct Dcthe draw context of a target: clip (x0, y0, x1, y1 exclusive, in target pixels), origin, colour (straight and premultiplied), opacityclip: [i32; 4]ox: i32oy: i32w: i32h: i32color: u32opac: u32pcol: [u32; 4]-- premultiplied B, G, R, Apcol32: u32ia: u32-- 255 - premultiplied alpharow0: i32-- the target row in the surface's first row (begin_rows: a band of a taller target); 0 otherwise. The fills and blits here, the rasterizer (paths, shapes, panels) and the text engine's glyph blits honour it; other row writers (tmask, gradient, flood) expect 0.
impl Dc
fn new(w: i32, h: i32) -> Dca context for a w x h target: clip = the whole target, colour opaque black [gfx_init]fn begin(&mut self, sf: &Surface)draw into another target: clip, origin and opacity of the current one are saved; the clip becomes the whole new target, the origin 0 [gfx_begin]fn begin_rows(&mut self, sf: &Surface, row0: i32, h: i32)begin for a band: sf holds rows row0 .. row0 + sf.h of a target h rows high. Drawing keeps the target's coordinates (clip, origin, paths, glyph positions), so a band gets the bytes the whole target would get there; the clip starts as the band's rows.fn end(&mut self)back to the previous target with its clip, origin and opacity [gfx_end]fn set_color(&mut self, argb: u32)store the colour and its premultiplied forms [gfx_set_color]fn get_color(&self) -> u32fn set_opacity(&mut self, op: u32)global opacity 0..255 (multiplies every alpha)fn origin(&mut self, x: i32, y: i32)fn translate(&mut self, dx: i32, dy: i32)fn clip_push(&mut self, x: i32, y: i32, w: i32, h: i32)save the clip and intersect it with the rectangle (origin-relative)fn clip_pop(&mut self)fn clip_rect(&self, x: i32, y: i32, w: i32, h: i32) -> Option<[i32; 4]>origin-relative rectangle -> clipped target rectangle (x0, y0, x1, y1), or Nonefn fill(&self, sf: &mut Surface, x: i32, y: i32, w: i32, h: i32)blend the colour over a rectangle (A8 targets: store the alpha) [gfx_fill]fn clear(&self, sf: &mut Surface, argb: u32)replace every pixel inside the clip by argb (premultiplied, no blending) [gfx_clear]fn hline(&self, sf: &mut Surface, x: i32, y: i32, w: i32)fn vline(&self, sf: &mut Surface, x: i32, y: i32, h: i32)fn frame(&self, sf: &mut Surface, x: i32, y: i32, w: i32, h: i32)1-pixel outline inside the rectangle [gfx_frame]fn blit(&self, sf: &mut Surface, src: &Surface, x: i32, y: i32)draw a surface at x, y: premultiplied over (x opacity), XRGB sources are copied (a large copy in row bands on the loop of set_parallel, COPY_PAR_MIN) [gfx_blit]fn blit_scaled(&self, sf: &mut Surface, src: &Surface, x: i32, y: i32, w: i32, h: i32)nearest-neighbour blit scaled to w x h (over) [gfx_blit_scaled]
gfx/blend.rs#
Source: lib/gfx/blend.rs
blend -- pixel row kernels (premultiplied 0xAARRGGBB, bytes B G R A) [src/gfx/blend.s, raster.s]
fill_solid(row, colour) store colour into every pixel
fill_over(row, pcol, ia) blend the premultiplied colour over every pixel
mask_over(row, mask, pcol) the colour through an 8-bit coverage row
blit_over(dst, src, opacity) premultiplied src over dst (x opacity 0..255)
a8_over(dst, cov, alpha) 8-bit target: c = cov * alpha / 255, dst = c + dst * (255 - c) / 255
copy_stream(dst, src) / copy_stream_rows(...) a row copy, or a block of rows, past the
caches (simd; row bands drawn on worker threads go back to
the framebuffer so); stream_fence() is in them
"over": dst = src + dst * (255 - src_alpha) / 255 with exact rounding (div255) and the
saturation of the SSE2 kernels (packuswb). fill_over, mask_over and a8_over are SIMD
kernels (simd::Kernel; their fast paths are exact shortcuts, so SSE2 and AVX2 agree);
blit_over is the assembly's SSE2 loop on pixel pairs, because its pair skip (both
transparent: dst kept) is visible for invalid premultiplied input.
Re-exports: simd::{copy_stream, copy_stream_rows, stream_fence}
fn fill_solid(row: &mut [u8], c: u32)k_fill_solid: store one colour into every pixel of the rowfn fill_over(row: &mut [u8], pcol: &[u32; 4], ia: u32)k_fill_over: blend the premultiplied colour over every pixelfn mask_over(row: &mut [u8], mask: &[u8], pcol: &[u32; 4])k_mask_over: blend the colour through an 8-bit coverage row (mask.len() pixels)fn blit_over(dst: &mut [u8], src: &[u8], op: u32)k_blit_over: premultiplied src over dst, scaled by opacity (pixels = min of both lengths)fn a8_over(dst: &mut [u8], cov: &[u8], alpha: u32)k_a8_over: 8-bit coverage target, c = cov * alpha / 255, dst = c + dst * (255 - c) / 255
gfx/blendmode.rs#
Source: lib/gfx/blendmode.rs
blendmode -- paint.net layer blend modes on straight-alpha BGRA rows (FMT_ARGB) [src/gfx/blendmode.s]
bm_row(dst, lhs, rhs, mode_op) layer rhs over layer lhs
bm_cov_row(dst, lhs, rhs, cov, mode_op) same, rhs alpha x A8 coverage (None: full)
bm_solid_row(dst, lhs, argb, cov, mode_op) a solid colour through the coverage
*_inplace: dst = lhs; bm_px: one pixel
mode_op = mode | opacity << 8 (BM_*, unknown modes are BM_NORMAL). lhs = bottom row,
rhs = top row. The arithmetic is paint.net's UserBlendOps, all integers 0..255:
INT_SCALE(a, b) = round(a*b / 255)
rhsA = INT_SCALE(INT_SCALE(rhs.A, opacity), cov); y = INT_SCALE(lhs.A, 255 - rhsA)
x = INT_SCALE(lhs.A, rhsA); z = rhsA - x; totalA = y + rhsA (0 -> pixel 0)
c = floor((lhs.c*y + rhs.c*z + F(lhs.c, rhs.c)*x) / totalA), A = totalA
BM_OVERWRITE (tools): dst = round((lhs*(255 - m) + rhs*m) / 255) on all four channels,
m = INT_SCALE(cov, opacity). Pixels with coverage 0 keep lhs. bm_px is the scalar
reference; the row kernels are the assembly's SSE2 / AVX2 code (simd::Kernel), which
computes exactly this per pixel: its fast paths are exact shortcuts and its f32 divisions
are exact floor divisions in this range (numerators <= 65025, divisors 1..255).
BM_NORMAL: u32 = 0
BM_MULTIPLY: u32 = 1
BM_ADDITIVE: u32 = 2
BM_COLORBURN: u32 = 3
BM_COLORDODGE: u32 = 4
BM_REFLECT: u32 = 5
BM_GLOW: u32 = 6
BM_OVERLAY: u32 = 7
BM_DIFFERENCE: u32 = 8
BM_NEGATION: u32 = 9
BM_LIGHTEN: u32 = 10
BM_DARKEN: u32 = 11
BM_SCREEN: u32 = 12
BM_XOR: u32 = 13
BM_OVERWRITE: u32 = 14
BM_COUNT: u32 = 15
BM_OPAC_SHIFT: u32 = 8
fn bm_px(l: u32, r: u32, cov: u32, mode_op: u32) -> u32one pixel: rhs over lhs with coverage cov (0..255) and mode_op = mode | opacity << 8fn bm_row(dst: &mut [u8], lhs: &[u8], rhs: &[u8], mode_op: u32)k_bm_row: dst = rhs over lhs (pixels = shortest row)fn bm_row_inplace(lhs: &mut [u8], rhs: &[u8], mode_op: u32)fn bm_cov_row(dst: &mut [u8], lhs: &[u8], rhs: &[u8], cov: Option<&[u8]>, n: usize, mode_op: u32)k_bm_cov_row: rhs alpha scaled by the coverage row (None: full coverage); n pixelsfn bm_cov_row_inplace(lhs: &mut [u8], rhs: &[u8], cov: Option<&[u8]>, n: usize, mode_op: u32)fn bm_solid_row(dst: &mut [u8], lhs: &[u8], argb: u32, cov: Option<&[u8]>, n: usize, mode_op: u32)k_bm_solid_row: the straight colour argb through the coverage row (None: full); n pixelsfn bm_solid_row_inplace(lhs: &mut [u8], argb: u32, cov: Option<&[u8]>, n: usize, mode_op: u32)
gfx/dash.rs#
Source: lib/gfx/dash.rs
dash -- dashed strokes with caps (flat / round / square / arrow / filled arrow) as a path:
the path's flattened centre lines are replaced by the outline of their stroke, closed
contours to fill with RULE_NONZERO [src/gfx/dash.s]
dash_pattern(style) -> &[f64] DASH_* (DASH_SOLID / unknown: empty)
dash_stroke(path, &DStyle) -> 0 / ERR_LIMIT
Geometry (f64): every open subpath (or dash piece) becomes ONE contour: the +n side
forward with joins, the end cap, the -n side backward, the start cap (n = (dy, -dx)).
Outer joins are mitred (limit miter, else bevelled), round or bevelled; inner joins pivot
through the vertex (the non-zero fill absorbs the overlap). A closed subpath becomes two
contours (outer and inner offset loop, oriented so that the ring winds +1). Every open
contour is oriented to a positive area, so overlapping pieces unite under non-zero.
Dashes: the pattern (entries x width) runs along each subpath from its start (phase
offset x width), a closed subpath's pattern runs once around; the ends of the pieces get
dcap except at the path's own start / end (cap0 / cap1). A piece of length 0 is a dot.
Arrow caps (open subpaths): head length L = 3 w + 4, half width L / 2 at the end point,
pointing along the last segment; the open arrow is the polyline (base+, tip, base-)
stroked with the line's width and join; the filled arrow a triangle, and the line ends
L / 2 before the tip. Round arcs use steps of 2 sqrt(0.1 / hw) rad (<= 45 degrees).
f64 operations in the order of the assembly, so the outline is bit-identical.
LCAP_FLAT: u32 = 0 // = CAP_BUTT
LCAP_ROUND: u32 = 1
LCAP_SQUARE: u32 = 2
LCAP_ARROW: u32 = 3 // open arrow head (two strokes of the line width)
LCAP_ARROW_FILLED: u32 = 4 // filled triangle
LCAP_COUNT: u32 = 5
DASH_SOLID: u32 = 0
DASH_DASH: u32 = 1 // 3 1
DASH_DOT: u32 = 2 // 1 1
DASH_DASHDOT: u32 = 3 // 3 1 1 1
DASH_DASHDOTDOT: u32 = 4 // 3 1 1 1 1 1
DASH_COUNT: u32 = 5
DASH_MAXPAT: usize = 32 // entries of a custom pattern
struct DStyle<'a>a stroke style (the DSTYLE record)width: f64-- line width (px, >= 0.05)pat: &'a [f64]-- on / off lengths in units of the width (empty = solid; odd counts twice)join: u32-- JOIN_*cap0: u32-- LCAP_* at the start of every open subpathcap1: u32-- LCAP_* at its enddcap: u32-- LCAP_FLAT / ROUND / SQUARE at the inner ends of dashesoffset: f64-- dash phase (units of the width)miter: f64-- miter limit (ratio of miter length to width; < 1 = 4)
fn dash_pattern(style: u32) -> &'static [f64]the predefined pattern of style DASH_* (units of the width) [dash_pattern]fn dash_stroke(path: &mut Path, st: &DStyle) -> i32replace the path by the outline of its stroke (see the file header) [dash_stroke]
gfx/flood.rs#
Source: lib/gfx/flood.rs
flood -- flood fill (magic wand / paint bucket region) into a tiled mask [src/gfx/flood.s]
flood_fill_mask(src, x, y, tolerance_pct, flags, out) -> 0 / ERR_FAIL
src: 32-bit surface (FMT_ARGB straight; the colour test works on the raw B, G, R, A
bytes); out: a TMask at least as large as src. out is cleared, then every pixel that
matches the seed colour (x, y) and -- without FF_GLOBAL -- is 4-connected to the seed
through matching pixels becomes 255. ERR_FAIL: bad surface, mask too small, seed outside
src (out is cleared when it is usable).
Colour test = paint.net's CheckColor, a = seed colour, b = candidate:
sum = sum over c in R, G, B of floor((1 + (a.c - b.c)^2) * a.A / 256) + (a.A - b.A)^2
tol = round(tolerance_pct * 255 / 100) (pct clamped to 0..100), match: sum <= tol*tol*4
As in the assembly: a match bitmap M (1 bit per pixel, rows of ceil(w / 64) u64) computed
per row on demand by a SIMD kernel (FF_MATCH4, integer arithmetic, so SSE2 and AVX2 give
the same bits); the contiguous fill is a scanline fill on the bitmaps with an explicit stack
of run starts, filled runs move from M to the fill bitmap F (word operations); finally
64 x 64 bit blocks become Empty / Full slots or tiles.
FF_GLOBAL: u32 = 1 // every matching pixel, not only the connected ones
fn flood_fill_mask(src: &Surface, x: i32, y: i32, tolerance_pct: i32, flags: u32, out: &mut TMask) -> i32fill the region of the seed (x, y) into out [flood_fill_mask]
gfx/gradient.rs#
Source: lib/gfx/gradient.rs
gradient -- paint.net style gradients (7 shapes x 3 repeat modes) [src/gfx/gradient.s]
grad_span(dst, x, y, g) dst.len() / 4 straight ARGB pixels of row y, columns x ..
(pixel centres x + i + 0.5, y + 0.5); with GF_ALPHA_MODE the
existing pixels keep their colour and their alpha is
multiplied by the ramp A.a -> B.a: a' = round(a * ramp / 255)
grad_alpha_span(dst, x, y, g) dst.len() bytes: the ramp A.a -> B.a
grad_t_span(dst, x, y, g) positions T (0 .. GT_ONE)
With d = end - start, L2 = d.d, v = p - start, dot = vx dx + vy dy, cross = vy dx - vx dy,
r = sqrt(vx vx + vy vy): linear dot / L2, linear reflected |dot| / L2, diamond (|dot| +
|cross|) / L2, radial r / L, conical |atan2(cross, dot)| / pi, spirals frac(r / L +-
atan2 / 2pi). atan2 is the polynomial of the assembly (Abramowitz-Stegun 4.4.49). Repeat:
none clamps to [0, 1], wrap frac(t), reflect the triangle wave of period 2. T = floor(t *
16384 + 0.5); every channel c = (A (16384 - T) + B T + bias) >> 14, bias 8192 or the 4 x 4
Bayer threshold (GF_DITHER). Degenerate L2 (0 or not finite): T = 16384. f64 operations in
the order of the assembly (no FMA), lane by lane in SIMD registers, so the results are
bit-identical.
GT_LINEAR: u8 = 0
GT_LINEAR_REFLECTED: u8 = 1
GT_DIAMOND: u8 = 2
GT_RADIAL: u8 = 3
GT_CONICAL: u8 = 4
GT_SPIRAL_CW: u8 = 5
GT_SPIRAL_CCW: u8 = 6
GT_COUNT: u8 = 7
GR_NONE: u8 = 0
GR_WRAP: u8 = 1
GR_REFLECT: u8 = 2
GF_ALPHA_MODE: u16 = 1
GF_DITHER: u16 = 2
GT_ONE: i32 = 16384
struct Grada gradient (the GRAD record): type GT_*, repeat GR_*, flags GF_*, colours A (t = 0) and B (t = 1), start and end pointtyp: u8repeat: u8flags: u16col_a: u32col_b: u32sx: f64sy: f64ex: f64ey: f64
fn grad_span(dst: &mut [u8], x: i32, y: i32, g: &Grad)straight ARGB pixels of gradient g (GF_ALPHA_MODE: multiply the existing alphas) [grad_span]fn grad_alpha_span(dst: &mut [u8], x: i32, y: i32, g: &Grad)the alpha ramp A.a -> B.a (transparency mode mask) [grad_alpha_span]fn grad_t_span(dst: &mut [i32], x: i32, y: i32, g: &Grad)the positions T (0 .. GT_ONE) [grad_t_span]
gfx/path.rs#
Source: lib/gfx/path.rs
path -- vector paths: build, flatten (tolerance 0.2 px), fill [src/gfx/path.s]
Integer API in 24.8 fixed point relative to the draw origin (move_fx, line_fx, quad_fx,
cubic_fx, rect_fx, rrect_fx, ellipse_fx), float API in absolute target pixels (move_f,
line_f, quad_f, add_pt; used by the text engine). Curves are flattened at once; fill()
hands the closed subpaths to the rasterizer, stroke() (stroke.rs) their outlines.
The origin is taken from the Dc at begin() (set_origin changes it).
struct Path
impl Path
fn set_tolerance(&mut self, tolerance: f32) -> f32Set curve flattening tolerance in target pixels and return the old value. Invalid values preserve the setting; 0.2 is the legacy default.fn begin(&mut self, dc: &Dc)path_begin: an empty path; ox, oy = the draw origin used by the integer APIfn reset(&mut self)an empty path, origin kept (path_begin for the float API)fn set_origin(&mut self, ox: i32, oy: i32)fn is_empty(&self) -> boolfn pts_mut(&mut self) -> &mut [(f32, f32)]the flattened points of every subpath (target pixels), e.g. to shear them before a fill (the asm's g_pts / g_npts) // paint-tools: Kritzel's italic textfn add_pt(&mut self, p: (f32, f32))path_add_pt: append to the open subpath (a new one starts at the current point if none is open); a duplicate of the previous point is skippedfn move_fx(&mut self, x: i32, y: i32)fn move_f(&mut self, x: f32, y: f32)fn line_fx(&mut self, x: i32, y: i32)fn line_f(&mut self, x: f32, y: f32)fn close(&mut self)fn quad_fx(&mut self, cx: i32, cy: i32, x: i32, y: i32)path_quad (24.8 fixed, origin-relative)fn quad_f(&mut self, cx: f32, cy: f32, x: f32, y: f32)path_quad_f: quadratic Bezier from the current point (float pixels)fn cubic_fx(&mut self, c1x: i32, c1y: i32, c2x: i32, c2y: i32, x: i32, y: i32)path_cubic (24.8 fixed, origin-relative)fn cubic_f(&mut self, p1: (f32, f32), p2: (f32, f32), p3: (f32, f32))a cubic Bezier from the current point in float pixels (the flattening of path_cubic)fn rect_fx(&mut self, x: i32, y: i32, w: i32, h: i32)fn rrect_fx(&mut self, x: i32, y: i32, w: i32, h: i32, r: i32)path_rrect: closed rounded rectangle, r clamped to min(w, h) / 2fn ellipse_fx(&mut self, cx: i32, cy: i32, rx: i32, ry: i32)path_ellipse: closed ellipse from four cubic arcsfn fill_lines(&self, ras: &mut Raster)the line list of path_fill: every subpath of 2+ points closed implicitlyfn fill(&self, ras: &mut Raster, dc: &Dc, sf: &mut Surface, rule: u32)path_fill: every subpath closed implicitly; rule 0 non-zero, 1 even-odd
gfx/panel.rs#
Source: lib/gfx/panel.rs
Fractional UI panels: compose fill and border coverage once, avoiding a dark
halo from drawing two antialiased shapes on top of the same boundary pixel.
impl Shapes<'_>
fn panel_fx(&mut self, x: i32, y: i32, w: i32, h: i32, r: i32, t: i32, fill: u32, stroke: u32)Rounded panel in 24.8 pixels, with an inside border. Fill and stroke are straight ARGB. Honors draw origin, clipping and opacity, on PARGB and A8. Temporary mask storage is bounded to two 64-row bands of the visible area. The bands start at the panel's first row whatever the clip, so a row gets the same coverage when the clip cuts the panel (dirty rectangles, row bands).
gfx/pathdata.rs#
Source: lib/gfx/pathdata.rs
pathdata -- path data: a growable list of absolute path commands, the SVG / XAML path
mini-language and its output into a Path [src/gfx/pathdata.s]
PData::new() / clear() empty (rule non-zero, error cleared)
move_to(x, y), line_to(x, y) (an implicit move to the current point opens a subpath)
cubic(&[f64; 6]), quad(&[f64; 4]) (a quadratic Bezier is stored as the cubic)
close()
arc(&[f64; 9]) SVG elliptical arc {x1, y1, rx, ry, rotation (deg),
large-arc 0/1, sweep 0/1, x2, y2} as up to 4 cubics
rrect(&[f64; 5]) closed rounded rectangle {x0, y0, x1, y1, r}
parse(text) -> (0 / PDE_* / ERR_LIMIT, byte offset) M L H V C S Q T A Z (upper case
absolute, lower case relative), implicit repetition,
"F0" / "F1" (XAML even-odd / non-zero)
emit(path, Option<&Matrix>) -> 0 / ERR_FAIL the commands into the path (curves flattened
to 0.05 px), the matrix applied first
bounds(Option<&Matrix>) -> Option<[f64; 4]> of the transformed, finely flattened outline
bounds_box(Option<&Matrix>) -> (any, [f64; 4]) the same as the assembly leaves it
Every builder call checks its coordinates (finite, |v| <= COORD_MAX) and the size
(MAX_SLOTS); the first failure is kept in err and later calls do nothing. The commands
are slots like the assembly's (op, then f64 arguments), so the limits are the same.
PDO_MOVE: u64 = 1
PDO_LINE: u64 = 2
PDO_CUBIC: u64 = 3
PDO_CLOSE: u64 = 4
MAX_SLOTS: usize = 0x40_0000 // 4 Mi slots per PData
MAX_TEXT: usize = 0x100_0000 // parse input limit (16 MB)
COORD_MAX: f64 = 10_000_000.0 // |coordinate| limit of the builder
PDE_SYNTAX: i32 = -40 // unexpected character / missing command
PDE_NUMBER: i32 = -41 // a number was expected
PDE_RANGE: i32 = -42 // a number / coordinate out of range (NaN, > COORD_MAX)
struct PDatapath data (the PDATA record)rule: u32err: i32ncmd: u32
impl PData
fn new() -> PDatafn clear(&mut self)no commands, no error [pd_reset]fn slot_count(&self) -> usizethe slots used (op words and f64 arguments)fn current(&self) -> (f64, f64)the current pointfn move_to(&mut self, x: f64, y: f64)start a subpath [pd_move]fn line_to(&mut self, x: f64, y: f64)straight segment [pd_line]fn cubic(&mut self, p: &[f64; 6])cubic Bezier from the current point: c1, c2, end [pd_cubic]fn quad(&mut self, q: &[f64; 4])quadratic Bezier (control, end) as the equivalent cubic [pd_quad]fn close(&mut self)close the open subpath; the current point returns to its start [pd_close]fn arc(&mut self, p: &[f64; 9])elliptical arc {x1, y1, rx, ry, phi (deg), large, sweep, x2, y2} (SVG 1.1 F.6.5 / F.6.6: radii scaled up when too small, 0 radius = line) [pd_arc]fn rrect(&mut self, p: &[f64; 5])closed rounded rectangle {x0, y0, x1, y1, r} (corners in any order, r clamped to 0 .. half the shorter side), clockwise on screen from the top edge [pd_rrect]fn parse(&mut self, text: &[u8]) -> (i32, usize)append SVG / XAML path data: (0 or the error, byte offset of the error or len) [pd_parse]fn emit(&self, path: &mut Path, m: Option<&Matrix>) -> i32append the commands to the path (matrix applied first) [pd_emit]fn bounds(&self, m: Option<&Matrix>) -> Option<[f64; 4]>{min x, min y, max x, max y} of the (transformed, finely flattened) outline [pd_bounds]fn bounds_box(&self, m: Option<&Matrix>) -> (bool, [f64; 4])pd_bounds as the assembly leaves its output: (any point, box); without a point the box is {1e300, 1e300, -1e300, -1e300}
gfx/raster.rs#
Source: lib/gfx/raster.rs
raster -- anti-aliased scanline rasterizer (signed-area accumulation) [src/gfx/raster.s]
Every line deposits its signed area (integers in 1/65536 of a pixel) into an
accumulation buffer; the running sum along a row is the coverage. Rows go in bands
of 64. The float operations and their order are those of the assembly, so the
coverage bytes are identical (see raster.s for the clip-determinism argument).
struct Raster
impl Raster
fn lines_begin(&mut self)fn emit_line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32)fn has_lines(&self) -> boolfn lbox(&self) -> [f32; 4]the bounding box of the line list (f32 minx, miny, maxx, maxy)fn fill(&mut self, dc: &Dc, sf: &mut Surface, rule: u32)ras_fill: rasterize the line list with the current colour into the target, clippedfn fill_rows(&mut self, clip: [i32; 4], rule: u32, emit: &mut dyn FnMut(i32, i32, &[u8]))rasterize the line list inside clip (x0, y0, x1, y1 exclusive): emit(y, x, coverage) for every touched row part, rows top to bottom (the coverage of a pixel does not depend on the clip)
gfx/shapes.rs#
Source: lib/gfx/shapes.rs
shapes -- anti-aliased convenience shapes (current colour) [src/gfx/shapes.s]
Integer pixels (UI): fill_rrect(x, y, w, h, r), stroke_rrect(x, y, w, h, r, t) -- only
the corner bands are rasterized, the rows in between are plain fills.
24.8 fixed point: fill_circle_fx, stroke_circle_fx (ring of thickness t centred on radius
r), fill_ellipse_fx, line_fx (round caps).
struct Shapes<'a>dc: &'a mut Dcsf: &'a mut Surfacepath: &'a mut Pathras: &'a mut Raster
impl Shapes<'_>
fn fill_rrect(&mut self, x: i32, y: i32, w: i32, h: i32, r: i32)gfx_fill_rrect(x, y, w, h, r)fn stroke_rrect(&mut self, x: i32, y: i32, w: i32, h: i32, r: i32, t: i32)gfx_stroke_rrect(x, y, w, h, r, t): border of thickness t inside the rectanglefn fill_circle_fx(&mut self, cx: i32, cy: i32, r: i32)gfx_fill_circle_fx(cx, cy, r)fn fill_ellipse_fx(&mut self, cx: i32, cy: i32, rx: i32, ry: i32)gfx_fill_ellipse_fx(cx, cy, rx, ry)fn stroke_circle_fx(&mut self, cx: i32, cy: i32, r: i32, t: i32)gfx_stroke_circle_fx(cx, cy, r, t): ring of thickness t centred on radius rfn line_fx(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, width: i32)gfx_line_fx(x0, y0, x1, y1, width): round-capped line
gfx/straight.rs#
Source: lib/gfx/straight.rs
straight -- row kernels on straight (not premultiplied) 0xAARRGGBB pixels [src/gfx/straight.s]
premul_row(dst, src) straight -> premultiplied: c' = round(c * a / 255)
unpremul_row(dst, src) premultiplied -> straight, the rounding of png.s:
c = min(255, (c * ceil(255 * 2^24 / a) + 2^23) >> 24)
lerp_mask_row(dst, a, b, m) dst = round((a * (255 - m) + b * m) / 255), 4 channels
lerp_mask_into_a / _into_b the same with dst = a / dst = b
erase_row(dst, cov, strength) alpha = round(alpha * (255 - e) / 255), e = round(cov *
strength / 255); colour kept
view_row(dst, src, x0, y0, cfg) straight src over a checkerboard -> XRGB row
view_row_pm(dst, src, x0, y0, cfg) premultiplied src over a checkerboard -> XRGB row
*_px: the same for one pixel (u32), for callers whose rows alias
Rows hold 4 bytes per pixel (B, G, R, A); a kernel works on as many pixels as its
shortest row has. The assembly's fast paths (opaque / transparent groups) are exact
shortcuts of these per-pixel formulas, so the results are the same bytes.
struct ViewCfgthe checkerboard of view_row: cell size (>= 1), colour of the even cells (cx + cy) and of the odd ones (alpha ignored)cell: i32c0: u32c1: u32
fn premul_px(p: u32) -> u32fn unpremul_px(p: u32) -> u32fn lerp_px(a: u32, b: u32, m: u32) -> u32fn erase_px(p: u32, cov: u32, strength: u32) -> u32fn view_bg(x: i32, y: i32, cfg: &ViewCfg) -> u32the opaque checkerboard colour of pixel (x, y)fn view_mix(s: u32, bg: u32) -> u32straight s over bg: round((s * a + bg * (255 - a)) / 255), alpha 255fn view_mix_pm(s: u32, bg: u32) -> u32premultiplied s over bg: s + round(bg * (255 - a) / 255) (saturated), alpha 255fn premul_row(dst: &mut [u8], src: &[u8])k_premul_rowfn premul_inplace(buf: &mut [u8])fn unpremul_row(dst: &mut [u8], src: &[u8])k_unpremul_rowfn unpremul_inplace(buf: &mut [u8])fn lerp_mask_row(dst: &mut [u8], a: &[u8], b: &[u8], m: &[u8])k_lerp_mask_row: pixels = m.len() (bounded by the rows)fn lerp_mask_into_a(a: &mut [u8], b: &[u8], m: &[u8])k_lerp_mask_row with dst = afn lerp_mask_into_b(a: &[u8], b: &mut [u8], m: &[u8])k_lerp_mask_row with dst = bfn erase_row(dst: &mut [u8], cov: &[u8], strength: u32)k_erase_row: pixels = cov.len() (bounded by the row)fn view_row(dst: &mut [u8], src: &[u8], x0: i32, y0: i32, cfg: &ViewCfg)k_view_row: straight src over the checkerboard; (x0, y0) = checkerboard coordinates of the first pixelfn view_row_pm(dst: &mut [u8], src: &[u8], x0: i32, y0: i32, cfg: &ViewCfg)k_view_row_pm: premultiplied src over the checkerboard
gfx/stroke.rs#
Source: lib/gfx/stroke.rs
stroke -- stroke outlines of a path [src/gfx/stroke.s]
path.stroke(ras, dc, sf, width, style) width 24.8 fixed pixels; style = join | cap << 4
(JOIN_MITER (limit 4, else bevel) / ROUND / BEVEL,
CAP_BUTT / ROUND / SQUARE)
path.stroke_lines(ras, width, style) only the outline line list (for other targets)
Every flattened subpath becomes closed contours (outer side forward, inner side
backward, with joins and caps) that are filled with the non-zero rule. Inner joins
pivot through the vertex; the non-zero fill absorbs the overlap. Offsets use
n = (dy, -dx) * half_width, so with y pointing down a positive cross product din x dout
means the +n side is the outer side of the turn. The float operations follow the
assembly one by one (0 - x instead of -x, comparisons with its NaN behaviour).
impl Path
fn stroke_lines(&self, ras: &mut Raster, width: i32, style: u32)the outline lines of path_stroke (ras.lines_begin + the contours); the caller fills them with the non-zero rulefn stroke(&self, ras: &mut Raster, dc: &Dc, sf: &mut Surface, width: i32, style: u32)path_stroke: the outline filled (non-zero) with the current colour
gfx/tmask.rs#
Source: lib/gfx/tmask.rs
tmask -- sparse tiled A8 masks [src/gfx/tmask.s]
TMask::new(w, h) -> Option 1 <= w, h <= 65535, every pixel 0
clear(value) every pixel = value (0 / 255 need no memory)
get(x, y) -> u8 coverage of one pixel (0 outside the mask)
span(x, y, maxn) -> (Span, n) run of n (1..maxn) pixels from (x, y): Empty (all 0),
Full (all 255) or Bytes inside one tile (n <= 64);
sentinel runs span tiles; outside -> Empty
row(x, y, n, buf) -> (&[u8], bool) the n bytes of (x .. x+n-1, y): inside a tile when
possible, else buf is filled (true = buf returned)
row_w(x, y) -> Option<&mut [u8]> writable bytes from (x, y) to the end of its tile row
(at most w - x); materialises the tile
tile_w(tx, ty) -> Option<&mut [u8]> writable 64 x 64 tile; tile_set(tx, ty, full)
fill_rect(x0, y0, x1, y1, value) (x1, y1 exclusive, clipped)
combine(src, op) / combine_block(tx, ty, Block, op) / copy(src) / clone()
invert(), threshold(level), bbox() -> Option<[i32; 4]>, optimize(), count_tiles()
load_a8(src, stride), store_a8(dst, stride)
raster_path(path, ras, rule, op), raster_polygon(path, ras, pts, rule, op)
trace(cb) -> i32 outlines of the pixels >= 128 as closed polylines in
pixel-edge coordinates, cb(points) -> 0 = go on
Tiles are 64 x 64 bytes (row stride 64). A slot holds Empty, Full or a tile; tiles come
from a pool (count_tiles reports the ones in use, as the assembly does). Pixels of edge
tiles outside w x h are ignored everywhere. Ops return 0 / ERR_* like the assembly.
TM_TILE: usize = 64
TM_MAX_SIDE: u32 = 65535
TM_REPLACE: u32 = 0 // src
TM_ADD: u32 = 1 // max(dst, src)
TM_SUB: u32 = 2 // round(dst * (255 - src) / 255)
TM_INTERSECT: u32 = 3 // round(dst * src / 255)
TM_XOR: u32 = 4 // |dst - src|
TM_OP_COUNT: u32 = 5
TM_TRACE_LEVEL: u8 = 128
enum Span<'a>a run of tm_spanEmptyFullBytes(&'a [u8])
enum Block<'a>a 64 x 64 source block of combine_blockEmptyFullData(&'a [u8], usize)-- bytes, row stride (64 readable bytes in each of 64 rows)
struct TMaskw: u32h: u32
impl TMask
fn new(w: u32, h: u32) -> Option<TMask>a mask of w x h pixels, every pixel 0 (None: bad size) [tm_alloc]fn tiles_x(&self) -> u32fn tiles_y(&self) -> u32fn clear(&mut self, value: u8) -> i32every pixel = value [tm_clear]fn get(&self, x: i32, y: i32) -> u8coverage of one pixel (0 outside) [tm_get]fn span(&self, x: i32, y: i32, maxn: i32) -> (Span<'_>, i32)a run of n (1..maxn) pixels from (x, y) [tm_span]fn row<'a>(&'a self, x: i32, y: i32, n: i32, buf: &'a mut [u8]) -> (&'a [u8], bool)the n bytes of (x .. x+n-1, y): (bytes, true when they are buf) [tm_row]fn row_w(&mut self, x: i32, y: i32) -> Option<&mut [u8]>writable bytes from (x, y) to the end of its tile row (at most w - x) [tm_row_w]fn tile_w(&mut self, tx: u32, ty: u32) -> Option<&mut [u8]>writable 64 x 64 tile (materialised with its content) [tm_tile_w]fn tile_set(&mut self, tx: u32, ty: u32, full: bool)tile (tx, ty) := all 0 / all 255 [tm_tile_set]fn fill_rect(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, value: u8) -> i32set the pixels of the rectangle (x1, y1 exclusive, clipped) to value; whole tiles of 0 / 255 become sentinels [tm_fill_rect]fn combine_block(&mut self, tx: u32, ty: u32, src: Block, op: u32) -> i32combine a 64 x 64 block into tile (tx, ty) [tm_combine_block]fn combine(&mut self, src: &TMask, op: u32) -> i32dst = dst OP src per pixel (same size) [tm_combine]fn combine_self(&mut self, op: u32) -> i32dst = dst OP dst (tm_combine with the same mask as both operands)fn copy(&mut self, src: &TMask) -> i32dst = src (same size) [tm_copy]fn invert(&mut self)v = 255 - v [tm_invert]fn threshold(&mut self, level: i32)v = v >= level ? 255 : 0 (level clamped to 1..255) [tm_threshold]fn optimize(&mut self)every uniform tile becomes a sentinel [tm_optimize]fn count_tiles(&self) -> (u32, u32)(tiles held in memory, slots that are all 255) [tm_count_tiles]fn bbox(&self) -> Option<[i32; 4]>x0, y0, x1, y1 (exclusive) of the pixels != 0, None when the mask is empty [tm_bbox]fn load_a8(&mut self, src: &[u8], stride: usize) -> i32the mask becomes a copy of the dense w x h A8 image at src (row stridestride) [tm_load_a8]fn store_a8(&self, dst: &mut [u8], stride: usize)write the mask as a dense w x h A8 image (row stridestride) [tm_store_a8]fn raster_path(&mut self, path: &Path, ras: &mut Raster, rule: u32, op: u32) -> i32rasterize the path (subpaths closed implicitly, rule RULE_*) with exact anti-aliased coverage and combine it into the mask with op (TM_*) [tm_raster_path]fn raster_polygon(&mut self, path: &mut Path, ras: &mut Raster, pts: &[(f32, f32)], rule: u32, op: u32) -> i32raster_path of one closed polygon given as points in mask pixels (replaces the path)fn trace(&self, cb: &mut dyn FnMut(&[(i32, i32)]) -> i32) -> i32outlines of the pixels with coverage >= 128 along pixel edges: cb(points) for every closed contour (corners in pixel-edge coordinates, implicitly closed, inside on the right); returns 0 or the first nonzero cb result [tm_trace]
gfx/xform.rs#
Source: lib/gfx/xform.rs
xform -- affine matrices and the sine / cosine of the transform code [src/img/xform.s]
Matrix {a, b, c, d, e, f}: (x, y) -> (a x + b y + c, d x + e y + f)
Matrix::IDENTITY, m.apply(x, y)
sincos(angle) -> (sin, cos) polynomial with a two-part pi/2 reduction (xf_sincos)
Used by pathdata (arcs, transformed output) and dash (round joins); img_xform (R6) builds
on the same functions. f64 operations in the order of the assembly.
struct Matrixan affine matrix (XM_*)a: f64b: f64c: f64d: f64e: f64f: f64
impl Matrix
const IDENTITY: Matrix = Matrix { a: 1.0, b: 0.0, c: 0.0, d: 0.0, e: 1.0, f: 0.0 }fn apply(&self, x: f64, y: f64) -> (f64, f64)xy = m * xy [xf_apply]fn sincos(angle: f64) -> (f64, f64)(sin angle, cos angle) [xf_sincos]