use pltrs_core::{Affine2D, Path, Point};
use pltrs_font::ScanOutline;
use pltrs_raster::{Clip, CoverageRounding, GrayBitmap};
use pltrs_text::{Hinting, TextEngine, TextRun};
use super::RasterRenderer;
use super::bitmap::{GlyphShape, smooth_bitmap};
use super::glyph::{GlyphTransform, is_axis_aligned};
use super::mono;
use crate::gc::{Dashes, GraphicsContext, SnapMode};
use crate::renderer::Renderer;
use crate::renderer::text_placement;
fn quantize(v: f64) -> f64 {
(v * 64.0).round_ties_even() / 64.0
}
const MAX_GLYPH_REACH: f64 = 2_147_483_648.0;
pub(super) fn within_reach(p: Point) -> bool {
p.x.abs() <= MAX_GLYPH_REACH && p.y.abs() <= MAX_GLYPH_REACH
}
fn outline_reach(outline: &ScanOutline) -> f64 {
let reach = (outline.points.iter())
.map(|p| p.x.unsigned_abs().max(p.y.unsigned_abs()))
.max()
.unwrap_or(0);
reach as f64 / 64.0
}
fn touches_canvas(pen: Point, reach: f64, (width, height): (f64, f64)) -> bool {
let reach = reach * std::f64::consts::SQRT_2 + 1.0;
pen.x + reach >= 0.0
&& pen.x - reach <= width
&& pen.y + reach >= 0.0
&& pen.y - reach <= height
}
pub(super) fn text_contexts(gc: &GraphicsContext) -> (GraphicsContext, GraphicsContext) {
let fill_gc = GraphicsContext {
linewidth: 0.0,
dashes: Dashes::solid(),
hatch: None,
sketch: None,
antialiased: true,
clip_rect: None,
clip_path: None,
..gc.clone()
};
let glyph_gc = GraphicsContext {
snap: SnapMode::Never,
clip_rect: gc.clip_rect,
..fill_gc.clone()
};
(fill_gc, glyph_gc)
}
impl RasterRenderer {
pub(super) fn draw_text_run(
&mut self,
gc: &GraphicsContext,
run: &TextRun,
origin: Point,
angle: f64,
) {
let engine = TextEngine::global();
let placement = self.glyph_placement(origin, angle);
let (fill_gc, glyph_gc) = text_contexts(gc);
let hinting = run
.source
.as_ref()
.map_or(Hinting::None, |source| source.font().hinting);
let axis_aligned = is_axis_aligned(angle);
self.painter
.set_coverage_rounding(CoverageRounding::FreeType);
for glyph in &run.glyphs {
let pen = pen_position(&placement, glyph.x, glyph.y);
if !within_reach(pen) {
continue;
}
let outline = engine.scan_glyph_outline(
glyph.font,
glyph.glyph,
glyph.size,
run.dpi,
hinting,
axis_aligned,
);
if let Ok(outline) = outline {
let shape = if gc.antialiased {
GlyphShape::Smooth(outline)
} else {
GlyphShape::Mono(outline)
};
self.blit_glyph(&glyph_gc, &shape, &GlyphTransform::new(angle, pen), pen);
}
}
self.painter.set_coverage_rounding(CoverageRounding::Agg);
let rules = run.rects.iter().map(pltrs_core::Bbox::bounds);
self.draw_rules(gc, &fill_gc, rules, &placement);
}
pub(super) fn glyph_placement(&self, origin: Point, angle: f64) -> Affine2D {
let height = f64::from(self.height());
text_placement(Point::new(origin.x, height - (height - origin.y)), angle)
}
pub(super) fn blit_glyph(
&mut self,
glyph_gc: &GraphicsContext,
shape: &GlyphShape,
transform: &GlyphTransform,
pen: Point,
) {
match shape {
GlyphShape::Smooth(outline) => {
let reach = outline_reach(outline);
if reach > MAX_GLYPH_REACH || !touches_canvas(pen, reach, self.size) {
return;
}
match smooth_bitmap(outline, transform) {
Ok(Some(bitmap)) => self.blit_bitmap(glyph_gc, &bitmap),
Ok(None) => {}
Err(err) => self.record(Err(err)),
}
}
GlyphShape::Mono(outline) => {
let Some(bitmap) = mono::render(outline, transform) else {
return;
};
let color = glyph_gc.stroke_color();
self.draw_path(
glyph_gc,
&bitmap.to_path(),
&Affine2D::IDENTITY,
Some(color),
);
}
}
}
fn blit_bitmap(&mut self, glyph_gc: &GraphicsContext, bitmap: &GrayBitmap) {
let color = glyph_gc.stroke_color();
let clip = Clip::rect(self.clip_box(glyph_gc).unwrap_or_else(|| self.full_box()));
let Some(top) = i32::try_from(self.height())
.ok()
.and_then(|height| height.checked_sub(bitmap.top))
else {
return;
};
let result = pltrs_raster::draw_coverage(
&mut self.pixmap,
&bitmap.coverage,
bitmap.left,
top,
color,
&clip,
);
self.record(result);
}
pub(super) fn draw_rules(
&mut self,
gc: &GraphicsContext,
fill_gc: &GraphicsContext,
rules: impl Iterator<Item = (f64, f64, f64, f64)>,
placement: &Affine2D,
) {
let color = gc.stroke_color();
for (mut x, mut y, mut w, mut h) in rules {
if gc.snap != SnapMode::Never {
if w < 1.0 {
x -= (1.0 - w) / 2.0;
w = 1.0;
}
if h < 1.0 {
y -= (1.0 - h) / 2.0;
h = 1.0;
}
}
let corners = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)];
let path = Path::polygon(corners.map(|(cx, cy)| Point::new(cx, cy)));
self.draw_path(fill_gc, &path, placement, Some(color));
}
}
}
pub(super) fn pen_position(placement: &Affine2D, x: f64, y: f64) -> Point {
let [cos, sin, minus_sin, _, origin_x, origin_y] = placement.values();
Point::new(
quantize(origin_x + x * cos + y * minus_sin),
quantize(origin_y + x * sin + y * cos),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn paints_glyph(gc: &GraphicsContext) -> bool {
let run = TextEngine::global()
.layout_line(
"W",
&pltrs_text::FontRequest::new(pltrs_text::FontQuery {
size: 20.0,
..pltrs_text::FontQuery::families(["DejaVu Sans"])
}),
72.0,
)
.expect("bundled font");
let mut r = RasterRenderer::new(40.0, 40.0, 72.0).expect("valid canvas");
r.draw_text(gc, &run, Point::new(5.0, 10.0), 0.0);
let pixmap = r.pixmap();
(0..40).any(|x| (0..40).any(|y| pixmap.pixel(x, y).is_some_and(|p| p.a > 0)))
}
#[test]
fn glyphs_ignore_clip_paths_but_not_clip_rectangles() {
let nowhere = pltrs_core::Bbox::from_extents(100.0, 100.0, 101.0, 101.0);
let clip_path = Some(crate::gc::ClipPath::new(
Path::unit_rectangle(),
Affine2D::identity().translate(100.0, 100.0),
));
let path_clipped = GraphicsContext {
clip_path,
..GraphicsContext::default()
};
assert!(paints_glyph(&path_clipped), "Agg ignores the clip path");
let rect_clipped = GraphicsContext {
clip_rect: Some(nowhere),
..GraphicsContext::default()
};
assert!(!paints_glyph(&rect_clipped));
}
#[test]
fn glyphs_far_off_the_canvas_are_skipped() {
let run = TextEngine::global()
.layout_line(
"W",
&pltrs_text::FontRequest::new(pltrs_text::FontQuery::families(["DejaVu Sans"])),
72.0,
)
.expect("bundled font");
for origin in [1e308, 8.4e16, -3e9, f64::NAN] {
let mut r = RasterRenderer::new(10.0, 10.0, 72.0).expect("valid canvas");
r.draw_text(
&GraphicsContext::default(),
&run,
Point::new(origin, 5.0),
30.0,
);
}
}
#[test]
fn pen_positions_round_like_python() {
assert_eq!(quantize(1.0 / 128.0), 0.0);
assert_eq!(quantize(3.0 / 128.0), 2.0 / 64.0);
assert_eq!(quantize(10.3), 659.0 / 64.0);
}
#[test]
fn anchors_are_flipped_down_and_up() {
let renderer = RasterRenderer::new(800.0, 600.0, 100.0).expect("valid canvas");
let below_tie = 215.835_937_499_999_97;
assert!(below_tie < 215.835_937_5);
let placement = renderer.glyph_placement(Point::new(87.5, below_tie), 0.0);
let pen = pen_position(&placement, 0.0, 0.0);
assert_eq!(pen, Point::new(87.5, 13814.0 / 64.0));
}
}