The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! Pure-Rust Canvas 2D renderer backed by `tiny-skia` + `cosmic-text`.
use std::cell::RefCell;
use std::f64::consts::{PI, TAU};
use std::rc::Rc;
use cosmic_text::{Attrs, Buffer, Color as CosmicColor, Metrics, Shaping, SwashCache, Weight, Wrap};
use tiny_skia::{
BlendMode, Color, FillRule, FilterQuality, GradientStop, LineCap, LineJoin, LinearGradient, Mask, Paint as SkPaint, PathBuilder, Pattern as SkPattern,
PixmapMut, PixmapRef, Point, RadialGradient, Rect, Shader, SpreadMode, Stroke, StrokeDash, Transform,
};
use super::codec::{premul, unpremul};
use super::fonts::{self, resolve_family, ParsedFont};
use super::textblock::blit_glyph;
thread_local! {
static SWASH: RefCell<SwashCache> = RefCell::new(SwashCache::new());
}
#[derive(Clone, Copy, Debug)]
pub struct Mat {
pub a: f64,
pub b: f64,
pub c: f64,
pub d: f64,
pub tx: f64,
pub ty: f64,
}
pub const IDENTITY: Mat = Mat { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };
impl Mat {
#[inline]
pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
(self.a * x + self.c * y + self.tx, self.b * x + self.d * y + self.ty)
}
#[inline]
pub fn to_skia(&self) -> Transform {
Transform::from_row(self.a as f32, self.b as f32, self.c as f32, self.d as f32, self.tx as f32, self.ty as f32)
}
#[inline]
pub fn concat(&self, o: &Mat) -> Mat {
Mat {
a: self.a * o.a + self.c * o.b,
b: self.b * o.a + self.d * o.b,
c: self.a * o.c + self.c * o.d,
d: self.b * o.c + self.d * o.d,
tx: self.a * o.tx + self.c * o.ty + self.tx,
ty: self.b * o.tx + self.d * o.ty + self.ty,
}
}
#[inline]
pub fn invert(&self) -> Option<Mat> {
let det = self.a * self.d - self.b * self.c;
if !det.is_finite() || det.abs() <= 1e-12 {
return None;
}
let inv = 1.0 / det;
Some(Mat {
a: self.d * inv,
b: -self.b * inv,
c: -self.c * inv,
d: self.a * inv,
tx: (self.c * self.ty - self.d * self.tx) * inv,
ty: (self.b * self.tx - self.a * self.ty) * inv,
})
}
}
#[derive(Clone, Copy)]
pub enum Use2 {
Fill,
Stroke,
}
#[derive(Clone, Debug)]
pub enum GradientKind {
Linear(f64, f64, f64, f64),
Radial(f64, f64, f64, f64, f64, f64),
Conic,
}
#[derive(Clone, Debug)]
pub struct Gradient {
pub kind: GradientKind,
pub stops: Vec<(f64, [f64; 4])>,
}
impl Gradient {
pub fn new(kind: GradientKind) -> Self {
Self { kind, stops: Vec::new() }
}
pub fn add_stop(&mut self, offset: f64, rgba: [f64; 4]) {
if offset.is_finite() && (0.0..=1.0).contains(&offset) {
self.stops.push((offset, rgba));
}
}
}
#[derive(Clone)]
pub struct Pattern {
pub data: Vec<u8>,
pub width: u32,
pub height: u32,
pub repeat_x: bool,
pub repeat_y: bool,
pub transform: Mat,
}
#[derive(Clone)]
pub enum Paint {
Color([f64; 4]),
Gradient(Rc<RefCell<Gradient>>),
Pattern(Rc<Pattern>),
}
impl Paint {
pub fn color(r: f64, g: f64, b: f64, a: f64) -> Self {
Paint::Color([r, g, b, a])
}
}
pub fn composite_from_name(name: &str) -> Option<BlendMode> {
Some(match name {
"source-over" => BlendMode::SourceOver,
"source-in" => BlendMode::SourceIn,
"source-out" => BlendMode::SourceOut,
"source-atop" => BlendMode::SourceAtop,
"destination-over" => BlendMode::DestinationOver,
"destination-in" => BlendMode::DestinationIn,
"destination-out" => BlendMode::DestinationOut,
"destination-atop" => BlendMode::DestinationAtop,
"lighter" => BlendMode::Plus,
"copy" => BlendMode::Source,
"xor" => BlendMode::Xor,
"multiply" => BlendMode::Multiply,
"screen" => BlendMode::Screen,
"overlay" => BlendMode::Overlay,
"darken" => BlendMode::Darken,
"lighten" => BlendMode::Lighten,
"color-dodge" => BlendMode::ColorDodge,
"color-burn" => BlendMode::ColorBurn,
"hard-light" => BlendMode::HardLight,
"soft-light" => BlendMode::SoftLight,
"difference" => BlendMode::Difference,
"exclusion" => BlendMode::Exclusion,
"hue" => BlendMode::Hue,
"saturation" => BlendMode::Saturation,
"color" => BlendMode::Color,
"luminosity" => BlendMode::Luminosity,
_ => return None,
})
}
#[derive(Clone, Copy, Debug)]
enum Seg {
Move(f64, f64),
Line(f64, f64),
Quad(f64, f64, f64, f64),
Cubic(f64, f64, f64, f64, f64, f64),
Close,
}
#[derive(Clone, Default)]
pub struct Path {
segs: Vec<Seg>,
current: Option<(f64, f64)>,
sub_start: Option<(f64, f64)>,
}
impl Path {
pub fn clear(&mut self) {
self.segs.clear();
self.current = None;
self.sub_start = None;
}
pub fn add_path(&mut self, other: &Path, m: &Mat) {
for &seg in &other.segs {
match seg {
Seg::Move(x, y) => {
let (nx, ny) = m.apply(x, y);
self.segs.push(Seg::Move(nx, ny));
self.current = Some((nx, ny));
self.sub_start = Some((nx, ny));
}
Seg::Line(x, y) => {
let (nx, ny) = m.apply(x, y);
self.segs.push(Seg::Line(nx, ny));
self.current = Some((nx, ny));
}
Seg::Quad(cx, cy, x, y) => {
let (ncx, ncy) = m.apply(cx, cy);
let (nx, ny) = m.apply(x, y);
self.segs.push(Seg::Quad(ncx, ncy, nx, ny));
self.current = Some((nx, ny));
}
Seg::Cubic(c1x, c1y, c2x, c2y, x, y) => {
let (a, b) = m.apply(c1x, c1y);
let (c, d) = m.apply(c2x, c2y);
let (nx, ny) = m.apply(x, y);
self.segs.push(Seg::Cubic(a, b, c, d, nx, ny));
self.current = Some((nx, ny));
}
Seg::Close => {
self.segs.push(Seg::Close);
self.current = self.sub_start;
}
}
}
}
pub fn move_to(&mut self, m: &Mat, x: f64, y: f64) {
if !x.is_finite() || !y.is_finite() {
return;
}
let (tx, ty) = m.apply(x, y);
self.segs.push(Seg::Move(tx, ty));
self.current = Some((tx, ty));
self.sub_start = Some((tx, ty));
}
pub fn line_to(&mut self, m: &Mat, x: f64, y: f64) {
if !x.is_finite() || !y.is_finite() {
return;
}
let (tx, ty) = m.apply(x, y);
if self.current.is_none() {
self.segs.push(Seg::Move(tx, ty));
self.sub_start = Some((tx, ty));
} else {
self.segs.push(Seg::Line(tx, ty));
}
self.current = Some((tx, ty));
}
pub fn quad_to(&mut self, m: &Mat, cx: f64, cy: f64, x: f64, y: f64) {
if ![cx, cy, x, y].iter().all(|v| v.is_finite()) {
return;
}
let (tcx, tcy) = m.apply(cx, cy);
let (tx, ty) = m.apply(x, y);
if self.current.is_none() {
self.segs.push(Seg::Move(tcx, tcy));
self.sub_start = Some((tcx, tcy));
}
self.segs.push(Seg::Quad(tcx, tcy, tx, ty));
self.current = Some((tx, ty));
}
pub fn bezier_to(&mut self, m: &Mat, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x: f64, y: f64) {
if ![c1x, c1y, c2x, c2y, x, y].iter().all(|v| v.is_finite()) {
return;
}
let (a, b) = m.apply(c1x, c1y);
let (c, d) = m.apply(c2x, c2y);
let (tx, ty) = m.apply(x, y);
if self.current.is_none() {
self.segs.push(Seg::Move(a, b));
self.sub_start = Some((a, b));
}
self.segs.push(Seg::Cubic(a, b, c, d, tx, ty));
self.current = Some((tx, ty));
}
pub fn arc_to(&mut self, m: &Mat, x1: f64, y1: f64, x2: f64, y2: f64, r: f64) {
if ![x1, y1, x2, y2, r].iter().all(|v| v.is_finite()) || r < 0.0 {
return;
}
let Some((px, py)) = self.current else {
self.move_to(m, x1, y1);
return;
};
let Some(inv) = m.invert() else { return };
let (x0, y0) = inv.apply(px, py);
if ((x0 - x1).abs() < 1e-9 && (y0 - y1).abs() < 1e-9) || ((x1 - x2).abs() < 1e-9 && (y1 - y2).abs() < 1e-9) || r == 0.0 {
self.line_to(m, x1, y1);
return;
}
let (dx0, dy0) = (x0 - x1, y0 - y1);
let (dx2, dy2) = (x2 - x1, y2 - y1);
let l0 = dx0.hypot(dy0);
let l2 = dx2.hypot(dy2);
let (ux0, uy0) = (dx0 / l0, dy0 / l0);
let (ux2, uy2) = (dx2 / l2, dy2 / l2);
let cross = ux0 * uy2 - uy0 * ux2;
if cross.abs() < 1e-9 {
self.line_to(m, x1, y1);
return;
}
let dot = (ux0 * ux2 + uy0 * uy2).clamp(-1.0, 1.0);
let half = dot.acos() * 0.5;
let dist = r / half.tan();
let (t1x, t1y) = (x1 + ux0 * dist, y1 + uy0 * dist);
let (t2x, t2y) = (x1 + ux2 * dist, y1 + uy2 * dist);
let sign = if cross > 0.0 { 1.0 } else { -1.0 };
let (cx, cy) = (t1x - uy0 * r * sign, t1y + ux0 * r * sign);
let a0 = (t1y - cy).atan2(t1x - cx);
let a1 = (t2y - cy).atan2(t2x - cx);
self.line_to(m, t1x, t1y);
self.arc(m, cx, cy, r, a0, a1, cross > 0.0);
}
pub fn arc(&mut self, m: &Mat, cx: f64, cy: f64, r: f64, start: f64, end: f64, ccw: bool) {
self.ellipse(m, cx, cy, r, r, 0.0, start, end, ccw);
}
#[allow(clippy::too_many_arguments)]
pub fn ellipse(&mut self, m: &Mat, cx: f64, cy: f64, rx: f64, ry: f64, rot: f64, start: f64, end: f64, ccw: bool) {
if ![cx, cy, rx, ry, rot, start, end].iter().all(|v| v.is_finite()) || rx < 0.0 || ry < 0.0 {
return;
}
let mut sweep = end - start;
if !ccw {
if sweep >= TAU {
sweep = TAU;
} else {
sweep = sweep.rem_euclid(TAU);
if sweep == 0.0 && end != start {
sweep = TAU;
}
}
} else if sweep <= -TAU {
sweep = -TAU;
} else {
sweep = -((-sweep).rem_euclid(TAU));
if sweep == 0.0 && end != start {
sweep = -TAU;
}
}
let steps = ((sweep.abs() / (PI / 2.0)).ceil() as usize).max(1);
let da = sweep / steps as f64;
let k = (4.0 / 3.0) * (da / 4.0).tan();
let (cr, sr) = (rot.cos(), rot.sin());
let pt = |a: f64| -> (f64, f64) {
let lx = rx * a.cos();
let ly = ry * a.sin();
(cx + lx * cr - ly * sr, cy + lx * sr + ly * cr)
};
let deriv = |a: f64| -> (f64, f64) {
let lx = -rx * a.sin();
let ly = ry * a.cos();
(lx * cr - ly * sr, lx * sr + ly * cr)
};
let (sx, sy) = pt(start);
if self.current.is_none() {
self.move_to(m, sx, sy);
} else {
self.line_to(m, sx, sy);
}
for i in 0..steps {
let a0 = start + da * i as f64;
let a1 = start + da * (i + 1) as f64;
let (p0x, p0y) = pt(a0);
let (p1x, p1y) = pt(a1);
let (d0x, d0y) = deriv(a0);
let (d1x, d1y) = deriv(a1);
self.bezier_to(m, p0x + k * d0x, p0y + k * d0y, p1x - k * d1x, p1y - k * d1y, p1x, p1y);
}
}
pub fn rect(&mut self, m: &Mat, x: f64, y: f64, w: f64, h: f64) {
if ![x, y, w, h].iter().all(|v| v.is_finite()) {
return;
}
self.move_to(m, x, y);
self.line_to(m, x + w, y);
self.line_to(m, x + w, y + h);
self.line_to(m, x, y + h);
self.close();
}
pub fn round_rect(&mut self, m: &Mat, mut x: f64, mut y: f64, mut w: f64, mut h: f64, r: [f64; 8]) {
if ![x, y, w, h].iter().all(|v| v.is_finite()) || r.iter().any(|v| !v.is_finite()) {
return;
}
if w < 0.0 {
x += w;
w = -w;
}
if h < 0.0 {
y += h;
h = -h;
}
let mut r = [r[0].max(0.0), r[1].max(0.0), r[2].max(0.0), r[3].max(0.0), r[4].max(0.0), r[5].max(0.0), r[6].max(0.0), r[7].max(0.0)];
let mut scale = 1.0f64;
for (sum, lim) in [(r[0] + r[2], w), (r[6] + r[4], w), (r[1] + r[7], h), (r[3] + r[5], h)] {
if sum > lim && sum > 0.0 {
scale = scale.min(lim / sum);
}
}
for v in &mut r {
*v *= scale;
}
self.move_to(m, x + r[0], y);
self.line_to(m, x + w - r[2], y);
if r[2] > 0.0 && r[3] > 0.0 {
self.ellipse(m, x + w - r[2], y + r[3], r[2], r[3], 0.0, -PI / 2.0, 0.0, false);
}
self.line_to(m, x + w, y + h - r[5]);
if r[4] > 0.0 && r[5] > 0.0 {
self.ellipse(m, x + w - r[4], y + h - r[5], r[4], r[5], 0.0, 0.0, PI / 2.0, false);
}
self.line_to(m, x + r[6], y + h);
if r[6] > 0.0 && r[7] > 0.0 {
self.ellipse(m, x + r[6], y + h - r[7], r[6], r[7], 0.0, PI / 2.0, PI, false);
}
self.line_to(m, x, y + r[1]);
if r[0] > 0.0 && r[1] > 0.0 {
self.ellipse(m, x + r[0], y + r[1], r[0], r[1], 0.0, PI, 1.5 * PI, false);
}
self.close();
}
pub fn close(&mut self) {
if self.current.is_some() {
self.segs.push(Seg::Close);
self.current = self.sub_start;
}
}
fn to_skia(&self, extra_transform: Option<&Mat>) -> Option<tiny_skia::Path> {
let mut pb = PathBuilder::new();
let tr = |x: f64, y: f64| -> (f32, f32) {
match extra_transform {
Some(m) => {
let (nx, ny) = m.apply(x, y);
(nx as f32, ny as f32)
}
None => (x as f32, y as f32),
}
};
for &seg in &self.segs {
match seg {
Seg::Move(x, y) => {
let (x, y) = tr(x, y);
pb.move_to(x, y);
}
Seg::Line(x, y) => {
let (x, y) = tr(x, y);
pb.line_to(x, y);
}
Seg::Quad(cx, cy, x, y) => {
let (cx, cy) = tr(cx, cy);
let (x, y) = tr(x, y);
pb.quad_to(cx, cy, x, y);
}
Seg::Cubic(c1x, c1y, c2x, c2y, x, y) => {
let (a, b) = tr(c1x, c1y);
let (c, d) = tr(c2x, c2y);
let (x, y) = tr(x, y);
pb.cubic_to(a, b, c, d, x, y);
}
Seg::Close => pb.close(),
}
}
pb.finish()
}
}
#[derive(Clone)]
pub struct State {
pub ctm: Mat,
pub fill: Paint,
pub stroke: Paint,
pub line_width: f64,
pub cap: LineCap,
pub join: LineJoin,
pub miter: f64,
pub dash: Vec<f64>,
pub dash_offset: f64,
pub alpha: f64,
pub blend: BlendMode,
pub shadow_x: f64,
pub shadow_y: f64,
pub shadow_blur: f64,
pub shadow_color: Option<[f64; 4]>,
pub smoothing: bool,
pub smoothing_quality: u8,
pub font: Rc<ParsedFont>,
pub align: u8,
pub baseline: u8,
pub rtl: bool,
pub letter_spacing: f64,
pub word_spacing: f64,
pub kerning: bool,
pub clip: Option<Mask>,
}
impl Default for State {
fn default() -> Self {
Self {
ctm: IDENTITY,
fill: Paint::color(0.0, 0.0, 0.0, 1.0),
stroke: Paint::color(0.0, 0.0, 0.0, 1.0),
line_width: 1.0,
cap: LineCap::Butt,
join: LineJoin::Miter,
miter: 10.0,
dash: Vec::new(),
dash_offset: 0.0,
alpha: 1.0,
blend: BlendMode::SourceOver,
shadow_x: 0.0,
shadow_y: 0.0,
shadow_blur: 0.0,
shadow_color: None,
smoothing: true,
smoothing_quality: 0,
font: Rc::new(ParsedFont::default()),
align: 0,
baseline: 0,
rtl: false,
letter_spacing: 0.0,
word_spacing: 0.0,
kerning: true,
clip: None,
}
}
}
pub struct Canvas {
pub width: u32,
pub height: u32,
pub state: State,
pub stack: Vec<State>,
pub path: Path,
pub dirty: bool,
}
fn color_from_rgba(rgba: [f64; 4], alpha_mul: f64) -> Color {
let a = (rgba[3] * alpha_mul).clamp(0.0, 1.0) as f32;
Color::from_rgba(rgba[0].clamp(0.0, 1.0) as f32, rgba[1].clamp(0.0, 1.0) as f32, rgba[2].clamp(0.0, 1.0) as f32, a).unwrap_or(Color::TRANSPARENT)
}
impl Canvas {
pub fn new(width: u32, height: u32) -> Self {
Self { width, height, state: State::default(), stack: Vec::new(), path: Path::default(), dirty: false }
}
pub fn reset(&mut self, pixels: &mut [u8]) {
pixels.fill(0);
self.state = State::default();
self.stack.clear();
self.path.clear();
self.dirty = true;
}
pub fn save(&mut self) {
self.stack.push(self.state.clone());
}
pub fn restore(&mut self) {
if let Some(prev) = self.stack.pop() {
self.state = prev;
}
}
fn make_paint<'a>(&self, paint: &'a Paint, alpha_mul: f64) -> Option<SkPaint<'a>> {
let mut sp = SkPaint { anti_alias: true, blend_mode: self.state.blend, ..Default::default() };
match paint {
Paint::Color(rgba) => {
sp.set_color(color_from_rgba(*rgba, alpha_mul));
}
Paint::Gradient(g) => {
let g = g.borrow();
if g.stops.is_empty() {
return None;
}
let mut sorted = g.stops.clone();
sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
let stops: Vec<GradientStop> = sorted
.iter()
.map(|(off, c)| GradientStop::new(*off as f32, color_from_rgba(*c, alpha_mul)))
.collect();
let tr = self.state.ctm.to_skia();
sp.shader = match g.kind {
GradientKind::Linear(x0, y0, x1, y1) => {
LinearGradient::new(Point::from_xy(x0 as f32, y0 as f32), Point::from_xy(x1 as f32, y1 as f32), stops, SpreadMode::Pad, tr)?
}
GradientKind::Radial(x0, y0, _r0, x1, y1, r1) => {
RadialGradient::new(Point::from_xy(x0 as f32, y0 as f32), Point::from_xy(x1 as f32, y1 as f32), r1.max(0.001) as f32, stops, SpreadMode::Pad, tr)?
}
GradientKind::Conic => {
// Fallback to first stop color when conic is requested.
Shader::SolidColor(color_from_rgba(sorted[0].1, alpha_mul))
}
};
}
Paint::Pattern(pat) => {
let p_ref = PixmapRef::from_bytes(&pat.data, pat.width, pat.height)?;
let spread = if pat.repeat_x || pat.repeat_y { SpreadMode::Repeat } else { SpreadMode::Pad };
let filter = if self.state.smoothing { FilterQuality::Bilinear } else { FilterQuality::Nearest };
let tr = self.state.ctm.concat(&pat.transform).to_skia();
sp.shader = SkPattern::new(p_ref, spread, filter, alpha_mul.clamp(0.0, 1.0) as f32, tr);
}
}
Some(sp)
}
fn make_stroke(&self) -> Stroke {
let mut s = Stroke {
width: self.state.line_width as f32,
miter_limit: self.state.miter as f32,
line_cap: self.state.cap,
line_join: self.state.join,
dash: None,
};
if !self.state.dash.is_empty() {
let intervals: Vec<f32> = self.state.dash.iter().map(|&v| v as f32).collect();
s.dash = StrokeDash::new(intervals, self.state.dash_offset as f32);
}
s
}
pub fn fill(&mut self, pixels: &mut [u8], path2d: Option<&Path>, even_odd: bool) {
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
let path = match path2d {
Some(p) => p.to_skia(Some(&self.state.ctm)),
None => self.path.to_skia(None),
};
let Some(path) = path else { return };
let rule = if even_odd { FillRule::EvenOdd } else { FillRule::Winding };
if let Some(sp) = self.make_paint(&self.state.fill, self.state.alpha) {
pm.fill_path(&path, &sp, rule, Transform::identity(), self.state.clip.as_ref());
self.dirty = true;
}
}
pub fn stroke(&mut self, pixels: &mut [u8], path2d: Option<&Path>) {
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
let path = match path2d {
Some(p) => p.to_skia(Some(&self.state.ctm)),
None => self.path.to_skia(None),
};
let Some(path) = path else { return };
let mut stroke = self.make_stroke();
// Scale stroke width by average CTM scale since paths are pre-transformed in device space.
let sx = self.state.ctm.a.hypot(self.state.ctm.b);
let sy = self.state.ctm.c.hypot(self.state.ctm.d);
let scale = ((sx + sy) * 0.5) as f32;
if scale.is_finite() && scale > 0.0 {
stroke.width *= scale;
}
if let Some(sp) = self.make_paint(&self.state.stroke, self.state.alpha) {
pm.stroke_path(&path, &sp, &stroke, Transform::identity(), self.state.clip.as_ref());
self.dirty = true;
}
}
pub fn clip(&mut self, path2d: Option<&Path>, even_odd: bool) {
if self.width == 0 || self.height == 0 {
return;
}
let path = match path2d {
Some(p) => p.to_skia(Some(&self.state.ctm)),
None => self.path.to_skia(None),
};
let Some(path) = path else { return };
let rule = if even_odd { FillRule::EvenOdd } else { FillRule::Winding };
if let Some(mask) = self.state.clip.as_mut() {
mask.intersect_path(&path, rule, true, Transform::identity());
} else if let Some(mut mask) = Mask::new(self.width, self.height) {
mask.fill_path(&path, rule, true, Transform::identity());
self.state.clip = Some(mask);
}
}
pub fn is_point_in_path(&self, path2d: Option<&Path>, x: f64, y: f64, _even_odd: bool) -> bool {
if !x.is_finite() || !y.is_finite() {
return false;
}
let path = match path2d {
Some(p) => p.to_skia(Some(&self.state.ctm)),
None => self.path.to_skia(None),
};
let Some(path) = path else { return false };
let b = path.bounds();
let (px, py) = (x as f32, y as f32);
px >= b.left() && px <= b.right() && py >= b.top() && py <= b.bottom()
}
pub fn is_point_in_stroke(&self, path2d: Option<&Path>, x: f64, y: f64) -> bool {
self.is_point_in_path(path2d, x, y, false)
}
pub fn fill_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {
if ![x, y, w, h].iter().all(|v| v.is_finite()) || w == 0.0 || h == 0.0 {
return;
}
let mut p = Path::default();
p.rect(&self.state.ctm, x, y, w, h);
let Some(sk) = p.to_skia(None) else { return };
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
if let Some(sp) = self.make_paint(&self.state.fill, self.state.alpha) {
pm.fill_path(&sk, &sp, FillRule::Winding, Transform::identity(), self.state.clip.as_ref());
self.dirty = true;
}
}
pub fn stroke_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {
if ![x, y, w, h].iter().all(|v| v.is_finite()) || (w == 0.0 && h == 0.0) {
return;
}
let mut p = Path::default();
p.rect(&self.state.ctm, x, y, w, h);
let Some(sk) = p.to_skia(None) else { return };
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
let mut stroke = self.make_stroke();
let scale = ((self.state.ctm.a.hypot(self.state.ctm.b) + self.state.ctm.c.hypot(self.state.ctm.d)) * 0.5) as f32;
if scale.is_finite() && scale > 0.0 {
stroke.width *= scale;
}
if let Some(sp) = self.make_paint(&self.state.stroke, self.state.alpha) {
pm.stroke_path(&sk, &sp, &stroke, Transform::identity(), self.state.clip.as_ref());
self.dirty = true;
}
}
pub fn clear_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {
if ![x, y, w, h].iter().all(|v| v.is_finite()) || w == 0.0 || h == 0.0 {
return;
}
let mut p = Path::default();
p.rect(&self.state.ctm, x, y, w, h);
let Some(sk) = p.to_skia(None) else { return };
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
let mut sp = SkPaint { anti_alias: false, blend_mode: BlendMode::Clear, ..Default::default() };
sp.set_color(Color::TRANSPARENT);
pm.fill_path(&sk, &sp, FillRule::Winding, Transform::identity(), self.state.clip.as_ref());
self.dirty = true;
}
pub fn measure_text(&self, text_u16: &[u16]) -> [f64; 12] {
let s = String::from_utf16_lossy(text_u16);
let size = self.state.font.size.max(1.0);
let lh = size * 1.25;
let width = if s.is_empty() {
0.0
} else {
fonts::with_font_system(|fs| {
let fam = resolve_family(fs, &self.state.font.families);
let attrs = Attrs::new().family(fam).weight(Weight(self.state.font.weight.clamp(100, 900))).style(self.state.font.cosmic_style());
let mut buf = Buffer::new(fs, Metrics::new(size as f32, lh as f32));
buf.set_wrap(fs, Wrap::None);
buf.set_text(fs, &s, attrs, Shaping::Advanced);
buf.shape_until_scroll(fs, false);
buf.layout_runs().map(|r| r.line_w as f64).fold(0.0, f64::max)
})
};
let ascent = size * 0.85;
let descent = size * 0.25;
let dx = text_align_offset(self.state.align, self.state.rtl, width);
let left = -dx;
let right = width + dx;
// [width, actualLeft, actualRight, fontAscent, fontDescent, actualAscent, actualDescent, emAscent, emDescent, hanging, alphabetic, ideographic]
[width, left, right, ascent, descent, ascent, descent, ascent, descent, ascent * 0.8, 0.0, -descent]
}
pub fn draw_text(&mut self, pixels: &mut [u8], text_u16: &[u16], x: f64, y: f64, _max_width: Option<f64>, use_: Use2) {
if !x.is_finite() || !y.is_finite() || text_u16.is_empty() || self.width == 0 || self.height == 0 {
return;
}
let s = String::from_utf16_lossy(text_u16);
let paint = match use_ {
Use2::Fill => &self.state.fill,
Use2::Stroke => &self.state.stroke,
};
let color = match paint {
Paint::Color(c) => [
(c[0].clamp(0.0, 1.0) * 255.0).round() as u8,
(c[1].clamp(0.0, 1.0) * 255.0).round() as u8,
(c[2].clamp(0.0, 1.0) * 255.0).round() as u8,
((c[3] * self.state.alpha).clamp(0.0, 1.0) * 255.0).round() as u8,
],
_ => [0, 0, 0, (self.state.alpha.clamp(0.0, 1.0) * 255.0).round() as u8],
};
if color[3] == 0 {
return;
}
let metrics = self.measure_text(text_u16);
let width_px = metrics[0];
let dx = text_align_offset(self.state.align, self.state.rtl, width_px);
let ascent = metrics[3];
let descent = metrics[4];
let dy = match self.state.baseline {
1 => ascent, // top
2 => ascent * 0.8, // hanging
3 => (ascent - descent) * 0.5, // middle
4 | 5 => -descent, // ideographic / bottom
_ => 0.0, // alphabetic
};
let scale = ((self.state.ctm.a.hypot(self.state.ctm.b) + self.state.ctm.c.hypot(self.state.ctm.d)) * 0.5).max(0.1);
let (gx0, gy0) = self.state.ctm.apply(x + dx, y + dy);
let font_size = (self.state.font.size * scale).max(1.0) as f32;
let line_h = font_size * 1.25;
fonts::with_font_system(|fs| {
let fam = resolve_family(fs, &self.state.font.families);
let attrs = Attrs::new()
.family(fam)
.weight(Weight(self.state.font.weight.clamp(100, 900)))
.style(self.state.font.cosmic_style())
.color(CosmicColor::rgba(color[0], color[1], color[2], color[3]));
let mut buf = Buffer::new(fs, Metrics::new(font_size, line_h));
buf.set_wrap(fs, Wrap::None);
buf.set_text(fs, &s, attrs, Shaping::Advanced);
buf.shape_until_scroll(fs, false);
SWASH.with(|sc| {
let mut swash = sc.borrow_mut();
for run in buf.layout_runs() {
for glyph in run.glyphs.iter() {
let physical = glyph.physical((gx0 as f32, gy0 as f32), 1.0);
let Some(img) = swash.get_image_uncached(fs, physical.cache_key) else { continue };
let px = physical.x + img.placement.left;
let py = physical.y - img.placement.top;
blit_glyph(pixels, self.width, self.height, px, py, &img, color);
}
}
});
});
self.dirty = true;
}
#[allow(clippy::too_many_arguments)]
pub fn draw_image(&mut self, pixels: &mut [u8], src_data: &[u8], iw: u32, ih: u32, sx: f64, sy: f64, sw: f64, sh: f64, dx: f64, dy: f64, dw: f64, dh: f64) {
let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };
let Some(src_pm) = PixmapRef::from_bytes(src_data, iw, ih) else { return };
if sw <= 0.0 || sh <= 0.0 || dw == 0.0 || dh == 0.0 {
return;
}
let scale_x = dw / sw;
let scale_y = dh / sh;
let pat_tr = self.state.ctm.concat(&Mat {
a: scale_x,
b: 0.0,
c: 0.0,
d: scale_y,
tx: dx - sx * scale_x,
ty: dy - sy * scale_y,
});
let filter = if self.state.smoothing { FilterQuality::Bilinear } else { FilterQuality::Nearest };
let paint = SkPaint {
shader: SkPattern::new(src_pm, SpreadMode::Pad, filter, self.state.alpha.clamp(0.0, 1.0) as f32, pat_tr.to_skia()),
blend_mode: self.state.blend,
anti_alias: true,
..Default::default()
};
let (rx, rw) = if dw >= 0.0 { (dx, dw) } else { (dx + dw, -dw) };
let (ry, rh) = if dh >= 0.0 { (dy, dh) } else { (dy + dh, -dh) };
let Some(rect) = Rect::from_xywh(rx as f32, ry as f32, rw as f32, rh as f32) else { return };
pm.fill_rect(rect, &paint, self.state.ctm.to_skia(), self.state.clip.as_ref());
self.dirty = true;
}
pub fn get_image_data(&self, data: &[u8], sx: i64, sy: i64, sw: usize, sh: usize, out: &mut [u8]) {
out[..sw * sh * 4].fill(0);
let (w, h) = (self.width as i64, self.height as i64);
for row in 0..sh {
let y = sy + row as i64;
if y < 0 || y >= h {
continue;
}
for col in 0..sw {
let x = sx + col as i64;
if x < 0 || x >= w {
continue;
}
let si = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
let di = (row * sw + col) * 4;
let a = data[si + 3];
out[di] = unpremul(data[si], a);
out[di + 1] = unpremul(data[si + 1], a);
out[di + 2] = unpremul(data[si + 2], a);
out[di + 3] = a;
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn put_image_data(&mut self, data: &mut [u8], src: &[u8], sw: usize, sh: usize, dx: i64, dy: i64, dirty: (i64, i64, i64, i64)) {
let (w, h) = (self.width as i64, self.height as i64);
let x0 = dirty.0.max(0);
let y0 = dirty.1.max(0);
let x1 = dirty.2.min(sw as i64);
let y1 = dirty.3.min(sh as i64);
for sy in y0..y1 {
let ty = dy + sy;
if ty < 0 || ty >= h {
continue;
}
for sx in x0..x1 {
let tx = dx + sx;
if tx < 0 || tx >= w {
continue;
}
let si = (sy as usize * sw + sx as usize) * 4;
let di = (ty as usize * self.width as usize + tx as usize) * 4;
let a = src[si + 3];
data[di] = premul(src[si], a);
data[di + 1] = premul(src[si + 1], a);
data[di + 2] = premul(src[si + 2], a);
data[di + 3] = a;
}
}
self.dirty = true;
}
}
/// Horizontal offset for Canvas 2D `textAlign`, matching JS `ALIGN = ["start", "end", "left", "right", "center"]`.
fn text_align_offset(align: u8, rtl: bool, width: f64) -> f64 {
match (align, rtl) {
(4, _) => -width * 0.5, // center
(3, _) | (1, false) | (0, true) => -width, // right / end (LTR) / start (RTL)
_ => 0.0, // left / start (LTR) / end (RTL)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_align_matches_js_enum() {
// JS ALIGN = ["start", "end", "left", "right", "center"]
assert_eq!(text_align_offset(0, false, 100.0), 0.0); // start (LTR)
assert_eq!(text_align_offset(0, true, 100.0), -100.0); // start (RTL)
assert_eq!(text_align_offset(1, false, 100.0), -100.0); // end (LTR)
assert_eq!(text_align_offset(1, true, 100.0), 0.0); // end (RTL)
assert_eq!(text_align_offset(2, false, 100.0), 0.0); // left
assert_eq!(text_align_offset(2, true, 100.0), 0.0); // left
assert_eq!(text_align_offset(3, false, 100.0), -100.0); // right
assert_eq!(text_align_offset(3, true, 100.0), -100.0); // right
assert_eq!(text_align_offset(4, false, 100.0), -50.0); // center
assert_eq!(text_align_offset(4, true, 100.0), -50.0); // center
}
#[test]
fn draw_text_center_align_centers_pixels() {
let (w, h) = (128u32, 128u32);
let mut pixels = vec![0u8; (w * h * 4) as usize];
let mut cv = Canvas::new(w, h);
cv.state.font = Rc::new(fonts::parse_shorthand("32px sans-serif").unwrap());
cv.state.fill = Paint::color(1.0, 1.0, 1.0, 1.0);
cv.state.align = 4; // center
cv.state.baseline = 3; // middle
let txt: Vec<u16> = "HH".encode_utf16().collect();
let m = cv.measure_text(&txt);
assert!(m[0] > 0.0);
assert!((m[1] - m[0] * 0.5).abs() < 1e-6, "actualLeft should be half width for center align");
assert!((m[2] - m[0] * 0.5).abs() < 1e-6, "actualRight should be half width for center align");
cv.draw_text(&mut pixels, &txt, 64.0, 64.0, None, Use2::Fill);
let mut min_x = w;
let mut max_x = 0u32;
for y in 0..h {
for x in 0..w {
if pixels[((y * w + x) * 4 + 3) as usize] > 0 {
min_x = min_x.min(x);
max_x = max_x.max(x);
}
}
}
assert!(min_x < max_x, "expected rendered glyph pixels");
let mid = (min_x + max_x) as f64 * 0.5;
assert!((mid - 64.0).abs() <= 3.0, "expected centered glyph near x=64, got bounds {min_x}..={max_x} (mid={mid})");
}
}