Files
chandra/compositor/renderer/renderer.mbt
T
nandi 52b42890d6
CI / test (push) Canceled after 0s
Camera: C ISP pipeline, contrast autofocus, and VFR video
- Add chandra-camera-isp.c (C/OpenMP) for Quad-Bayer unpack, CCM, and tone mapping, with a NumPy fallback when it is not built
- Add non-blocking contrast-detection VCM autofocus, with lens subdev discovery on the sensor's I2C bus
- Tune Quad-Bayer AE: a video-mode vblank cap, damped steps, and full analog gain before extending blanking
- Record variable-frame-rate video through a streaming Matroska muxer, and count dropped frames
- Ship libcamera IPA tuning files for imx376, imx519, and uncalibrated sensors
- Map camera buffers by fd and sync them with dma-buf ioctls
2026-11-28 19:25:43 -08:00

1050 lines
30 KiB
MoonBit

///| Pure MoonBit ARGB8888/RGBA8888 software rasterizer, wl_shm blitter, and PNG/PPM encoder.
///|
pub(all) struct Pixmap {
width : Int
height : Int
/// RGBA8888 byte buffer (4 bytes per pixel: R, G, B, A)
data : FixedArray[Byte]
}
///|
pub fn Pixmap::new(width : Int, height : Int) -> Pixmap {
let w = if width < 1 { 1 } else { width }
let h = if height < 1 { 1 } else { height }
{ width: w, height: h, data: FixedArray::make(w * h * 4, b'\x00') }
}
///|
pub fn Pixmap::pixel(self : Pixmap, x : Int, y : Int) -> @scene.Rgba? {
if x < 0 || y < 0 || x >= self.width || y >= self.height {
return None
}
let off = (y * self.width + x) * 4
Some({
r: self.data[off],
g: self.data[off + 1],
b: self.data[off + 2],
a: self.data[off + 3],
})
}
///|
fn blend_pixel(
dst : Pixmap,
x : Int,
y : Int,
r : Int,
g : Int,
b : Int,
a : Int,
clip : @scene.Rect?,
) -> Unit {
if x < 0 || y < 0 || x >= dst.width || y >= dst.height || a <= 0 {
return
}
match clip {
Some(c) =>
if x < c.x || y < c.y || x >= c.x + c.w || y >= c.y + c.h {
return
}
None => ()
}
let off = (y * dst.width + x) * 4
if a >= 255 {
dst.data[off] = r.to_byte()
dst.data[off + 1] = g.to_byte()
dst.data[off + 2] = b.to_byte()
dst.data[off + 3] = b'\xff'
return
}
let inv = 255 - a
let dr = dst.data[off].to_int()
let dg = dst.data[off + 1].to_int()
let db = dst.data[off + 2].to_int()
let da = dst.data[off + 3].to_int()
dst.data[off] = ((r * a + dr * inv + 127) / 255).to_byte()
dst.data[off + 1] = ((g * a + dg * inv + 127) / 255).to_byte()
dst.data[off + 2] = ((b * a + db * inv + 127) / 255).to_byte()
dst.data[off + 3] = (a + (da * inv + 127) / 255).clamp(min=0, max=255).to_byte()
}
///|
fn in_rounded_rect(
px : Int,
py : Int,
rx : Int,
ry : Int,
rw : Int,
rh : Int,
rad : Int,
) -> Bool {
if px < rx || py < ry || px >= rx + rw || py >= ry + rh {
return false
}
if rad <= 0 {
return true
}
let max_r = (if rw < rh { rw } else { rh }) / 2
let r = if rad > max_r { max_r } else { rad }
if r <= 0 {
return true
}
let x_left = rx + r
let x_right = rx + rw - r - 1
let y_top = ry + r
let y_bot = ry + rh - r - 1
if px < x_left && py < y_top {
let dx = x_left - px
let dy = y_top - py
dx * dx + dy * dy <= r * r
} else if px > x_right && py < y_top {
let dx = px - x_right
let dy = y_top - py
dx * dx + dy * dy <= r * r
} else if px < x_left && py > y_bot {
let dx = x_left - px
let dy = py - y_bot
dx * dx + dy * dy <= r * r
} else if px > x_right && py > y_bot {
let dx = px - x_right
let dy = py - y_bot
dx * dx + dy * dy <= r * r
} else {
true
}
}
///| Blend a colour over the pixels [xa, xb) of row `y`. The caller has already clipped the span to
/// the pixmap and the clip rectangle, so this is a bare loop over the buffer.
fn blend_span(dst : Pixmap, y : Int, xa : Int, xb : Int, r : Int, g : Int, b : Int, a : Int) -> Unit {
if xa >= xb || a <= 0 {
return
}
let data = dst.data
let mut off = (y * dst.width + xa) * 4
let end = (y * dst.width + xb) * 4
if a >= 255 {
let rb = r.to_byte()
let gb = g.to_byte()
let bb = b.to_byte()
while off < end {
data[off] = rb
data[off + 1] = gb
data[off + 2] = bb
data[off + 3] = b'\xff'
off = off + 4
}
return
}
let inv = 255 - a
let ra = r * a + 127
let ga = g * a + 127
let ba = b * a + 127
while off < end {
data[off] = ((ra + data[off].to_int() * inv) / 255).to_byte()
data[off + 1] = ((ga + data[off + 1].to_int() * inv) / 255).to_byte()
data[off + 2] = ((ba + data[off + 2].to_int() * inv) / 255).to_byte()
data[off + 3] = (a + (data[off + 3].to_int() * inv + 127) / 255).clamp(min=0, max=255).to_byte()
off = off + 4
}
}
///|
fn fill_rounded_rect(
dst : Pixmap,
rect : @scene.Rect,
color : @scene.Rgba,
radius : Int,
clip : @scene.Rect?,
) -> Unit {
if rect.w <= 0 || rect.h <= 0 || color.a.to_int() == 0 {
return
}
// Visible part of the rectangle: the pixmap, intersected with the clip.
let mut x0 = if rect.x < 0 { 0 } else { rect.x }
let mut y0 = if rect.y < 0 { 0 } else { rect.y }
let mut x1 = if rect.x + rect.w > dst.width { dst.width } else { rect.x + rect.w }
let mut y1 = if rect.y + rect.h > dst.height { dst.height } else { rect.y + rect.h }
match clip {
Some(c) => {
if c.x > x0 { x0 = c.x }
if c.y > y0 { y0 = c.y }
if c.x + c.w < x1 { x1 = c.x + c.w }
if c.y + c.h < y1 { y1 = c.y + c.h }
}
None => ()
}
if x0 >= x1 || y0 >= y1 {
return
}
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
if radius <= 0 {
for y = y0; y < y1; y = y + 1 {
blend_span(dst, y, x0, x1, cr, cg, cb, ca)
}
return
}
// Rounded: the rows outside the corner bands are plain spans; inside a band only the pixels
// within `r` of a side need the circle test (exactly the test `in_rounded_rect` applies).
let max_r = (if rect.w < rect.h { rect.w } else { rect.h }) / 2
let r = if radius > max_r { max_r } else { radius }
let x_left = rect.x + r
let x_right = rect.x + rect.w - r - 1
let y_top = rect.y + r
let y_bot = rect.y + rect.h - r - 1
for y = y0; y < y1; y = y + 1 {
if y >= y_top && y <= y_bot {
blend_span(dst, y, x0, x1, cr, cg, cb, ca)
continue
}
// Corner band: left corner pixels, middle span, right corner pixels.
let mut x = x0
while x < x1 && x < x_left {
if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) {
blend_span(dst, y, x, x + 1, cr, cg, cb, ca)
}
x = x + 1
}
let mid_a = if x_left > x0 { x_left } else { x0 }
let mid_b = if x_right + 1 < x1 { x_right + 1 } else { x1 }
blend_span(dst, y, mid_a, mid_b, cr, cg, cb, ca)
x = if x_right + 1 > x0 { x_right + 1 } else { x0 }
if x < mid_a { x = mid_a }
while x < x1 {
if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) {
blend_span(dst, y, x, x + 1, cr, cg, cb, ca)
}
x = x + 1
}
}
}
///|
fn stroke_rounded_rect(
dst : Pixmap,
rect : @scene.Rect,
color : @scene.Rgba,
width : Int,
radius : Int,
clip : @scene.Rect?,
) -> Unit {
if rect.w <= 0 || rect.h <= 0 || width <= 0 || color.a.to_int() == 0 {
return
}
let x0 = if rect.x < 0 { 0 } else { rect.x }
let y0 = if rect.y < 0 { 0 } else { rect.y }
let x1 = if rect.x + rect.w > dst.width { dst.width } else { rect.x + rect.w }
let y1 = if rect.y + rect.h > dst.height {
dst.height
} else {
rect.y + rect.h
}
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
let inner_x = rect.x + width
let inner_y = rect.y + width
let inner_w = rect.w - width * 2
let inner_h = rect.h - width * 2
let inner_r = if radius > width { radius - width } else { 0 }
// Visible columns and rows after the clip, for the span path below.
let (cx0, cx1, cy0, cy1) = match clip {
Some(c) => (c.x, c.x + c.w, c.y, c.y + c.h)
None => (0, dst.width, 0, dst.height)
}
// Rows where the inner rectangle is full width (clear of its rounded corners) only have the
// two side strips to draw; every pixel between them is the interior. The other rows (the top
// and bottom bands) take the exact per-pixel test.
let mid_a = inner_y + inner_r
let mid_b = inner_y + inner_h - inner_r
for y = y0; y < y1; y = y + 1 {
if inner_w > 0 && inner_h > 0 && y >= mid_a && y < mid_b {
if y >= cy0 && y < cy1 {
let l0 = if x0 > cx0 { x0 } else { cx0 }
let l1 = if inner_x < x1 { inner_x } else { x1 }
blend_span(dst, y, l0, if l1 < cx1 { l1 } else { cx1 }, cr, cg, cb, ca)
let r0 = if inner_x + inner_w > x0 { inner_x + inner_w } else { x0 }
blend_span(dst, y, if r0 > cx0 { r0 } else { cx0 }, if x1 < cx1 { x1 } else { cx1 }, cr, cg, cb, ca)
}
continue
}
for x = x0; x < x1; x = x + 1 {
let in_outer = in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius)
let in_inner = inner_w > 0 &&
inner_h > 0 &&
in_rounded_rect(x, y, inner_x, inner_y, inner_w, inner_h, inner_r)
if in_outer && !in_inner {
blend_pixel(dst, x, y, cr, cg, cb, ca, clip)
}
}
}
}
///|
fn draw_line(
dst : Pixmap,
x0_in : Int,
y0_in : Int,
x1_in : Int,
y1_in : Int,
color : @scene.Rgba,
width : Int,
clip : @scene.Rect?,
) -> Unit {
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
let half = if width <= 1 { 0 } else { width / 2 }
let mut x0 = x0_in
let mut y0 = y0_in
let dx = (x1_in - x0_in).abs()
let sx = if x0_in < x1_in { 1 } else { -1 }
let dy = -(y1_in - y0_in).abs()
let sy = if y0_in < y1_in { 1 } else { -1 }
let mut err = dx + dy
while true {
for oy = -half; oy <= half; oy = oy + 1 {
for ox = -half; ox <= half; ox = ox + 1 {
blend_pixel(dst, x0 + ox, y0 + oy, cr, cg, cb, ca, clip)
}
}
if x0 == x1_in && y0 == y1_in {
break
}
let e2 = 2 * err
if e2 >= dy {
err = err + dy
x0 = x0 + sx
}
if e2 <= dx {
err = err + dx
y0 = y0 + sy
}
}
}
///|
fn draw_circle(
dst : Pixmap,
cx : Int,
cy : Int,
radius : Int,
color : @scene.Rgba,
filled : Bool,
clip : @scene.Rect?,
) -> Unit {
if radius <= 0 {
return
}
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
// Antialiased: per-pixel coverage from the distance to the edge (1px wide ring when unfilled).
let rad = radius.to_double()
for dy = -radius - 1; dy <= radius + 1; dy = dy + 1 {
for dx = -radius - 1; dx <= radius + 1; dx = dx + 1 {
let d = (dx * dx + dy * dy).to_double().sqrt()
let outer = rad + 0.5 - d
let mut cov = if outer > 1.0 { 1.0 } else { outer }
if !filled {
let inner = d - (rad - 1.0 - 0.5)
let ic = if inner > 1.0 { 1.0 } else { inner }
if ic < cov {
cov = ic
}
}
if cov > 0.02 {
blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, (ca.to_double() * cov).round().to_int(), clip)
}
}
}
}
///| Minimal 5x7 ASCII bitmap glyph rows (5 bits wide, 7 rows).
fn glyph_rows(ch : Int) -> Array[Int] {
match ch {
// Space
32 => [0, 0, 0, 0, 0, 0, 0]
// Digits 0-9
48 => [14, 17, 19, 21, 25, 17, 14]
49 => [4, 12, 4, 4, 4, 4, 14]
50 => [14, 17, 1, 2, 4, 8, 31]
51 => [31, 2, 4, 2, 1, 17, 14]
52 => [2, 6, 10, 18, 31, 2, 2]
53 => [31, 16, 30, 1, 1, 17, 14]
54 => [6, 8, 16, 30, 17, 17, 14]
55 => [31, 1, 2, 4, 8, 8, 8]
56 => [14, 17, 17, 14, 17, 17, 14]
57 => [14, 17, 17, 15, 1, 2, 12]
// Uppercase A-Z (mapped for both A-Z and a-z fallback if needed, plus lowercase)
65 => [14, 17, 17, 31, 17, 17, 17] // A
66 => [30, 17, 17, 30, 17, 17, 30] // B
67 => [14, 17, 16, 16, 16, 17, 14] // C
68 => [28, 18, 17, 17, 17, 18, 28] // D
69 => [31, 16, 16, 30, 16, 16, 31] // E
70 => [31, 16, 16, 30, 16, 16, 16] // F
71 => [14, 17, 16, 23, 17, 17, 15] // G
72 => [17, 17, 17, 31, 17, 17, 17] // H
73 => [14, 4, 4, 4, 4, 4, 14] // I
74 => [7, 2, 2, 2, 2, 18, 12] // J
75 => [17, 18, 20, 24, 20, 18, 17] // K
76 => [16, 16, 16, 16, 16, 16, 31] // L
77 => [17, 27, 21, 21, 17, 17, 17] // M
78 => [17, 17, 25, 21, 19, 17, 17] // N
79 => [14, 17, 17, 17, 17, 17, 14] // O
80 => [30, 17, 17, 30, 16, 16, 16] // P
81 => [14, 17, 17, 17, 21, 18, 13] // Q
82 => [30, 17, 17, 30, 20, 18, 17] // R
83 => [15, 16, 16, 14, 1, 1, 30] // S
84 => [31, 4, 4, 4, 4, 4, 4] // T
85 => [17, 17, 17, 17, 17, 17, 14] // U
86 => [17, 17, 17, 17, 17, 10, 4] // V
87 => [17, 17, 17, 21, 21, 27, 17] // W
88 => [17, 17, 10, 4, 10, 17, 17] // X
89 => [17, 17, 10, 4, 4, 4, 4] // Y
90 => [31, 1, 2, 4, 8, 16, 31] // Z
// Lowercase a-z
97 => [0, 0, 14, 1, 15, 17, 15] // a
98 => [16, 16, 22, 25, 17, 17, 30] // b
99 => [0, 0, 14, 16, 16, 17, 14] // c
100 => [1, 1, 13, 19, 17, 17, 15] // d
101 => [0, 0, 14, 17, 31, 16, 14] // e
102 => [6, 9, 8, 28, 8, 8, 8] // f
103 => [0, 0, 15, 17, 15, 1, 14] // g
104 => [16, 16, 22, 25, 17, 17, 17] // h
105 => [4, 0, 12, 4, 4, 4, 14] // i
106 => [2, 0, 6, 2, 2, 18, 12] // j
107 => [16, 16, 18, 20, 24, 20, 18] // k
108 => [12, 4, 4, 4, 4, 4, 14] // l
109 => [0, 0, 26, 21, 21, 17, 17] // m
110 => [0, 0, 22, 25, 17, 17, 17] // n
111 => [0, 0, 14, 17, 17, 17, 14] // o
112 => [0, 0, 30, 17, 30, 16, 16] // p
113 => [0, 0, 15, 17, 15, 1, 1] // q
114 => [0, 0, 22, 25, 16, 16, 16] // r
115 => [0, 0, 14, 16, 14, 1, 30] // s
116 => [8, 8, 28, 8, 8, 9, 6] // t
117 => [0, 0, 17, 17, 17, 19, 13] // u
118 => [0, 0, 17, 17, 17, 10, 4] // v
119 => [0, 0, 17, 17, 21, 21, 10] // w
120 => [0, 0, 17, 10, 4, 10, 17] // x
121 => [0, 0, 17, 17, 15, 1, 14] // y
122 => [0, 0, 31, 2, 4, 8, 31] // z
// Punctuation
45 => [0, 0, 0, 14, 0, 0, 0] // -
46 => [0, 0, 0, 0, 0, 12, 12] // .
58 => [0, 12, 12, 0, 12, 12, 0] // :
47 => [1, 2, 2, 4, 8, 8, 16] // /
95 => [0, 0, 0, 0, 0, 0, 31] // _
33 => [4,4,4,4,4,0,4] // !
34 => [10,10,10,0,0,0,0] // "
35 => [10,10,31,10,31,10,10] // #
36 => [4,15,20,14,5,30,4] // $
37 => [24,25,2,4,8,19,3] // %
38 => [12,18,20,8,21,18,13] // &
39 => [4,4,8,0,0,0,0] // '
40 => [2,4,8,8,8,4,2] // (
41 => [8,4,2,2,2,4,8] // )
42 => [0,4,21,14,21,4,0] // *
43 => [0,4,4,31,4,4,0] // +
44 => [0,0,0,0,12,4,8] // ,
59 => [0,12,12,0,12,4,8] // ;
60 => [2,4,8,16,8,4,2] // <
61 => [0,0,31,0,31,0,0] // =
62 => [8,4,2,1,2,4,8] // >
63 => [14,17,1,2,4,0,4] // ?
64 => [14,17,23,21,23,16,14] // @
91 => [14,8,8,8,8,8,14] // [
92 => [16,8,8,4,2,2,1] // \
93 => [14,2,2,2,2,2,14] // ]
94 => [4,10,17,0,0,0,0] // ^
96 => [8,4,2,0,0,0,0] // `
123 => [2,4,4,8,4,4,2] // {
124 => [4,4,4,4,4,4,4] // |
125 => [8,4,4,2,4,4,8] // }
126 => [0,0,8,21,2,0,0] // ~
_ => [31, 17, 21, 21, 21, 17, 31]
}
}
///| A rasterised glyph: 8-bit coverage `w`x`h`, top-left at (xoff, yoff)
/// relative to the pen position on the baseline.
pub(all) struct Glyph {
w : Int
h : Int
xoff : Int
yoff : Int
advance : Int
coverage : Bytes
/// Draw twice, 1px apart (faces without a real bold).
embolden : Bool
}
///| Optional real-font glyph source: (codepoint, pixel size, bold) -> glyph.
/// Unset (e.g. in wasm builds), text uses the built-in 5x7 bitmap font.
let glyph_source : Ref[((Int, Int, Bool, Bool) -> Glyph)?] = { val: None }
///|
pub fn set_glyph_source(f : (Int, Int, Bool, Bool) -> Glyph) -> Unit {
glyph_source.val = Some(f)
}
///| Pixel square size for inline colour emoji at font `size` (~1.2em, matching UI line height).
pub fn inline_emoji_px(size : Int) -> Int {
if size <= 0 {
0
} else {
(size * 6 + 4) / 5
}
}
///| Optional inline emoji matcher and image provider for general UI text.
let emoji_match_source : Ref[((Array[Char], Int, Bool, Bool) -> (Int, String)?)?] = {
val: None,
}
///|
let emoji_image_source : Ref[((String, Int) -> UInt)?] = { val: None }
///| Register inline colour emoji lookup (`match_at`) and image rasteriser (`image`).
pub fn set_emoji_source(
match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?,
image : (String, Int) -> UInt,
) -> Unit {
emoji_match_source.val = Some(match_at)
emoji_image_source.val = Some(image)
}
///|
priv enum TextPiece {
TextGlyph(Glyph)
TextEmoji(String)
}
///|
fn renderer_may_have_emoji(text : String) -> Bool {
for ch in text {
if ch.to_int() >= 0x203C {
return true
}
}
false
}
///|
fn renderer_ignorable_mod(cp : Int) -> Bool {
cp == 0xFE0E || cp == 0xFE0F || cp == 0x200D
}
///| Segment `text` into text glyphs and inline emoji clusters, returning `(pieces, total_w)`.
fn layout_text(
src : (Int, Int, Bool, Bool) -> Glyph,
match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?,
text : String,
size : Int,
bold : Bool,
mono : Bool,
) -> (Array[TextPiece], Int) {
let chars = text.to_array()
let epx = inline_emoji_px(size)
let pieces : Array[TextPiece] = []
let mut total_w = 0
let mut i = 0
while i < chars.length() {
match match_at(chars, i, bold, mono) {
Some((next, seq)) => {
pieces.push(TextEmoji(seq))
total_w = total_w + epx
i = next
}
None => {
let cp = chars[i].to_int()
if !renderer_ignorable_mod(cp) {
let g = src(cp, size, bold, mono)
pieces.push(TextGlyph(g))
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
}
i = i + 1
}
}
}
(pieces, total_w)
}
///| Pixel width `text` would occupy when drawn with the given face.
pub fn text_width(text : String, size : Int, bold : Bool, mono : Bool) -> Int {
match glyph_source.val {
Some(src) => {
match emoji_match_source.val {
Some(match_at) if renderer_may_have_emoji(text) => {
let (_, w) = layout_text(src, match_at, text, size, bold, mono)
return w
}
_ => ()
}
let mut w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
w = w + g.advance + (if g.embolden { 1 } else { 0 })
}
w
}
None => text.length() * (if size >= 14 { 12 } else { 6 })
}
}
///|
fn draw_text_font(
dst : Pixmap,
src : (Int, Int, Bool, Bool) -> Glyph,
mono : Bool,
x : Int,
y : Int,
text : String,
size : Int,
color : @scene.Rgba,
align : @scene.TextAlign,
bold : Bool,
clip : @scene.Rect?,
) -> Unit {
let epx = inline_emoji_px(size)
let (pieces, total_w) = match (emoji_match_source.val, emoji_image_source.val) {
(Some(match_at), Some(_)) if renderer_may_have_emoji(text) =>
layout_text(src, match_at, text, size, bold, mono)
_ => {
let pieces : Array[TextPiece] = []
let mut total_w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
pieces.push(TextGlyph(g))
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
}
(pieces, total_w)
}
}
let start_x = match align {
Left => x
Center => x - total_w / 2
Right => x - total_w
}
// `y` is the vertical centre of the text; centre the capital height on it.
let cap = src(72, size, false, mono) // 'H'
let baseline = y + (-cap.yoff) / 2
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
let mut pen = start_x
for piece in pieces {
match piece {
TextGlyph(g) => {
for row = 0; row < g.h; row = row + 1 {
for col = 0; col < g.w; col = col + 1 {
let cov = g.coverage[row * g.w + col].to_int()
if cov > 0 {
let px = pen + g.xoff + col
let py = baseline + g.yoff + row
blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip)
if g.embolden {
blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip)
}
}
}
}
pen = pen + g.advance + (if g.embolden { 1 } else { 0 })
}
TextEmoji(seq) => {
match emoji_image_source.val {
Some(img_fn) if epx > 0 => {
let h = img_fn(seq, epx)
if h != 0U {
draw_image(dst, h, @scene.Rect::new(pen, y - epx / 2, epx, epx), clip)
}
}
_ => ()
}
pen = pen + epx
}
}
}
}
///|
fn draw_text(
mono : Bool,
dst : Pixmap,
x : Int,
y : Int,
text : String,
size : Int,
color : @scene.Rgba,
align : @scene.TextAlign,
bold : Bool,
clip : @scene.Rect?,
) -> Unit {
if text.length() == 0 || color.a.to_int() == 0 {
return
}
match glyph_source.val {
Some(src) => {
draw_text_font(dst, src, mono, x, y, text, size, color, align, bold, clip)
return
}
None => ()
}
let scale = if size >= 14 { 2 } else { 1 }
let char_w = 6 * scale
let total_w = text.length() * char_w
let start_x = match align {
Left => x
Center => x - total_w / 2
Right => x - total_w
}
let start_y = y - 7 * scale / 2
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
let mut idx = 0
for ch in text {
let rows = glyph_rows(ch.to_int())
let gx = start_x + idx * char_w
for row = 0; row < 7; row = row + 1 {
let bits = rows[row]
for col = 0; col < 5; col = col + 1 {
if ((bits >> (4 - col)) & 1) != 0 {
for sy = 0; sy < scale; sy = sy + 1 {
for sx = 0; sx < scale; sx = sx + 1 {
let px = gx + col * scale + sx
let py = start_y + row * scale + sy
blend_pixel(dst, px, py, cr, cg, cb, ca, clip)
if bold {
blend_pixel(dst, px + 1, py, cr, cg, cb, ca, clip)
}
}
}
}
}
}
idx = idx + 1
}
}
///|
pub fn draw_ops(
dst : Pixmap,
ops : Array[@scene.DrawOp],
ox : Int,
oy : Int,
) -> Unit {
let clip_stack : Array[@scene.Rect] = []
for op in ops {
let cur_clip : @scene.Rect? = if clip_stack.length() > 0 {
Some(clip_stack[clip_stack.length() - 1])
} else {
None
}
match op {
FillRect(r, col, rad) =>
fill_rounded_rect(
dst,
@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h),
col,
rad,
cur_clip,
)
StrokeRect(r, col, w, rad) =>
stroke_rounded_rect(
dst,
@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h),
col,
w,
rad,
cur_clip,
)
Line(x0, y0, x1, y1, col, w) =>
draw_line(dst, x0 + ox, y0 + oy, x1 + ox, y1 + oy, col, w, cur_clip)
Circle(cx, cy, rad, col, filled) =>
draw_circle(dst, cx + ox, cy + oy, rad, col, filled, cur_clip)
Text(x, y, txt, sz, col, align, bold) =>
draw_text(false, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip)
MonoText(x, y, txt, sz, col, align, bold) =>
draw_text(true, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip)
PushClip(r) =>
clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h))
PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) }
Image(r, handle) =>
draw_image(dst, handle, @scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h), cur_clip)
}
}
}
///| Blit a Wayland wl_shm client buffer (ARGB8888=0, XRGB8888=1, little-endian [B,G,R,A]).
pub fn blit_shm_surface(
dst : Pixmap,
buf : @scene.ShmBufferSnapshot,
dst_rect : @scene.Rect,
) -> Unit {
if buf.width <= 0 || buf.height <= 0 || dst_rect.w <= 0 || dst_rect.h <= 0 {
return
}
// While the client catches up with a resize, its buffer is smaller than the window:
// extend the buffer's bottom-right colour over the rest instead of showing the wallpaper.
if (buf.width < dst_rect.w || buf.height < dst_rect.h) &&
buf.stride * buf.height <= buf.bytes.length() &&
buf.width > 0 {
let o = (buf.height - 1) * buf.stride + (buf.width - 1) * 4
let a = if buf.format == 1 { 255 } else { buf.bytes[o + 3].to_int() }
fill_rounded_rect(
dst,
dst_rect,
@scene.Rgba::new(
buf.bytes[o + 2].to_int(),
buf.bytes[o + 1].to_int(),
buf.bytes[o].to_int(),
a,
),
0,
None,
)
}
let copy_w = if buf.width < dst_rect.w { buf.width } else { dst_rect.w }
let copy_h = if buf.height < dst_rect.h { buf.height } else { dst_rect.h }
let is_xrgb = buf.format == 1
// Visible columns/rows only (the window may hang off the screen).
let c0 = if dst_rect.x < 0 { 0 - dst_rect.x } else { 0 }
let c1 = if dst_rect.x + copy_w > dst.width { dst.width - dst_rect.x } else { copy_w }
let src = buf.bytes
let data = dst.data
for row = 0; row < copy_h; row = row + 1 {
let dy = dst_rect.y + row
if dy < 0 || dy >= dst.height {
continue
}
let mut col = c0
let mut so = row * buf.stride + c0 * 4
let mut d = (dy * dst.width + dst_rect.x + c0) * 4
// Never read past the buffer, even if a client lied about its stride.
let last = if row * buf.stride + c1 * 4 > src.length() {
(src.length() - row * buf.stride) / 4
} else {
c1
}
while col < last {
let a = if is_xrgb { 255 } else { src[so + 3].to_int() }
if a >= 255 {
data[d] = src[so + 2]
data[d + 1] = src[so + 1]
data[d + 2] = src[so]
data[d + 3] = b'\xff'
} else if a > 0 {
// wl_shm ARGB8888 is premultiplied: the colour already carries its alpha.
let inv = 255 - a
data[d] = (src[so + 2].to_int() + (data[d].to_int() * inv + 127) / 255).clamp(min=0, max=255).to_byte()
data[d + 1] = (src[so + 1].to_int() + (data[d + 1].to_int() * inv + 127) / 255).clamp(min=0, max=255).to_byte()
data[d + 2] = (src[so].to_int() + (data[d + 2].to_int() * inv + 127) / 255).clamp(min=0, max=255).to_byte()
data[d + 3] = (a + (data[d + 3].to_int() * inv + 127) / 255).clamp(min=0, max=255).to_byte()
}
col = col + 1
so = so + 4
d = d + 4
}
}
}
///| The last rendered wallpaper and the ops it was drawn from.
let wallpaper_cache : Ref[(Array[@scene.DrawOp], Pixmap)?] = { val: None }
///|
pub fn render_scene(scene : @scene.SceneGraph) -> Pixmap {
let pixmap = Pixmap::new(scene.output_w, scene.output_h)
// 1. Background layer: the wallpaper is rendered once and copied while it is unchanged.
if scene.wallpaper_ops.length() > 0 {
match wallpaper_cache.val {
Some((ops, cached)) if cached.width == pixmap.width && cached.height == pixmap.height && ops == scene.wallpaper_ops =>
pixmap.data.unsafe_blit(0, cached.data, 0, cached.data.length())
_ => {
draw_ops(pixmap, scene.wallpaper_ops, 0, 0)
let copy = Pixmap::new(pixmap.width, pixmap.height)
copy.data.unsafe_blit(0, pixmap.data, 0, pixmap.data.length())
wallpaper_cache.val = Some((scene.wallpaper_ops, copy))
}
}
}
draw_ops(pixmap, scene.background_ops, 0, 0)
// 2. Windows layer (bottom-to-top)
for win in scene.windows {
if !win.fullscreen {
let (top, _, _, left) = win.deco_insets
// The frame: title bar, outline, buttons and its shadow (`@scene.build_window_decoration`).
draw_ops(pixmap, win.deco_ops, win.geometry.x - left, win.geometry.y - top)
}
// Client wl_shm surface
match win.surface {
Some(buf) => blit_shm_surface(pixmap, buf, win.geometry)
None =>
fill_rounded_rect(
pixmap,
win.geometry,
@scene.Rgba::new(0x1e, 0x29, 0x3b, 0xff),
0,
None,
)
}
}
// 3. Panel layer
draw_ops(pixmap, scene.panel_ops, 0, 0)
for widget in scene.widgets {
draw_ops(pixmap, widget.ops, widget.rect.x, widget.rect.y)
}
// 4. Overlay layer
for widget in scene.widgets {
match widget.popup {
Some((pr, pops)) => draw_ops(pixmap, pops, pr.x, pr.y)
None => ()
}
}
// 5. Client popups (menus) above everything
for pu in scene.popups {
blit_shm_surface(pixmap, pu.1, pu.0)
}
pixmap
}
///| Encode Pixmap as binary PPM (P6).
pub fn encode_ppm(p : Pixmap) -> Bytes {
let header = "P6\n" +
p.width.to_string() +
" " +
p.height.to_string() +
"\n255\n"
let out : Array[Byte] = []
for ch in header {
out.push(ch.to_int().to_byte())
}
let count = p.width * p.height
for i = 0; i < count; i = i + 1 {
let off = i * 4
out.push(p.data[off])
out.push(p.data[off + 1])
out.push(p.data[off + 2])
}
Bytes::from_array(out)
}
///|
fn push_u32_be(out : Array[Byte], v : UInt) -> Unit {
out.push(((v >> 24) & 0xFFU).to_byte())
out.push(((v >> 16) & 0xFFU).to_byte())
out.push(((v >> 8) & 0xFFU).to_byte())
out.push((v & 0xFFU).to_byte())
}
///|
fn crc32(bytes : Array[Byte], start : Int, len : Int) -> UInt {
let mut c = 0xFFFF_FFFFU
for i = 0; i < len; i = i + 1 {
c = c ^ bytes[start + i].to_uint()
for _b = 0; _b < 8; _b = _b + 1 {
if (c & 1U) != 0U {
c = (c >> 1) ^ 0xEDB8_8320U
} else {
c = c >> 1
}
}
}
c ^ 0xFFFF_FFFFU
}
///|
fn push_png_chunk(out : Array[Byte], tag : String, payload : Array[Byte]) -> Unit {
push_u32_be(out, payload.length().reinterpret_as_uint())
let crc_start = out.length()
for ch in tag {
out.push(ch.to_int().to_byte())
}
for b in payload {
out.push(b)
}
let crc = crc32(out, crc_start, 4 + payload.length())
push_u32_be(out, crc)
}
///| Encode Pixmap as a valid uncompressed RGBA PNG in pure MoonBit.
pub fn encode_png(p : Pixmap) -> Bytes {
let out : Array[Byte] = [
b'\x89', b'\x50', b'\x4e', b'\x47', b'\x0d', b'\x0a', b'\x1a', b'\x0a',
]
// IHDR
let ihdr : Array[Byte] = []
push_u32_be(ihdr, p.width.reinterpret_as_uint())
push_u32_be(ihdr, p.height.reinterpret_as_uint())
ihdr.push(b'\x08') // bit depth = 8
ihdr.push(b'\x06') // color type = RGBA
ihdr.push(b'\x00') // compression = 0
ihdr.push(b'\x00') // filter = 0
ihdr.push(b'\x00') // interlace = 0
push_png_chunk(out, "IHDR", ihdr)
// Raw scanlines: 1 filter byte (0) + width * 4 bytes per row
let row_bytes = 1 + p.width * 4
let raw : Array[Byte] = Array(capacity=row_bytes * p.height)
let mut s1 = 1U
let mut s2 = 0U
for y = 0; y < p.height; y = y + 1 {
raw.push(b'\x00')
s1 = (s1 + 0U) % 65521U
s2 = (s2 + s1) % 65521U
let row_off = y * p.width * 4
for i = 0; i < p.width * 4; i = i + 1 {
let b = p.data[row_off + i]
raw.push(b)
s1 = (s1 + b.to_uint()) % 65521U
s2 = (s2 + s1) % 65521U
}
}
// Zlib stream with stored (uncompressed) deflate blocks (max 65535 bytes each)
let idat : Array[Byte] = [b'\x78', b'\x01']
let mut pos = 0
let total = raw.length()
while pos < total {
let rem = total - pos
let blk = if rem > 65535 { 65535 } else { rem }
let is_last = pos + blk >= total
idat.push(if is_last { b'\x01' } else { b'\x00' })
idat.push((blk & 0xFF).to_byte())
idat.push(((blk >> 8) & 0xFF).to_byte())
let nlen = blk ^ 0xFFFF
idat.push((nlen & 0xFF).to_byte())
idat.push(((nlen >> 8) & 0xFF).to_byte())
for i = 0; i < blk; i = i + 1 {
idat.push(raw[pos + i])
}
pos = pos + blk
}
let adler = (s2 << 16) | s1
push_u32_be(idat, adler)
push_png_chunk(out, "IDAT", idat)
// IEND
push_png_chunk(out, "IEND", [])
Bytes::from_array(out)
}