use crate::{
App, AtlasTile, Bounds, ContentMask, DecorationRun, DevicePixels, FontId, GlyphId, Hsla,
IsZero, MonochromeSprite, Pixels, Point, RenderGlyphParams, SUBPIXEL_VARIANTS_X,
SUBPIXEL_VARIANTS_Y, ScaledPixels, Size, SubpixelSprite, TransformationMatrix, Window,
util::round_half_toward_zero,
};
use anyhow::Result;
use std::borrow::Cow;
pub(crate) fn quantize_origin(origin: Point<ScaledPixels>) -> (Point<ScaledPixels>, Point<u8>) {
let (x, variant_x) = quantize_axis(origin.x.0, SUBPIXEL_VARIANTS_X);
let (y, variant_y) = quantize_axis(origin.y.0, SUBPIXEL_VARIANTS_Y);
(
Point::new(ScaledPixels(x), ScaledPixels(y)),
Point::new(variant_x, variant_y),
)
}
fn quantize_axis(value: f32, variants: u8) -> (f32, u8) {
let whole = value.floor();
let steps = round_half_toward_zero((value - whole) * variants as f32) as i32;
let carry = steps / variants as i32;
(whole + carry as f32, (steps % variants as i32) as u8)
}
pub(crate) fn quantize_emoji_origin(origin: Point<ScaledPixels>) -> Point<ScaledPixels> {
origin.map(|c| {
let whole = c.0.floor();
ScaledPixels(whole + round_half_toward_zero(c.0 - whole))
})
}
#[cfg(test)]
pub(crate) fn may_reach(
line_glyph: Bounds<Pixels>,
baseline: Pixels,
mask: &Bounds<Pixels>,
) -> bool {
GlyphReach::new(line_glyph.size, mask)
.contains(line_glyph.origin.x, line_glyph.origin.y + baseline)
}
#[derive(Clone, Copy)]
struct GlyphReach {
size: Size<Pixels>,
left: Pixels,
top: Pixels,
right: Pixels,
bottom: Pixels,
}
impl GlyphReach {
const UNSET: Self = Self {
size: Size {
width: Pixels(f32::NAN),
height: Pixels(f32::NAN),
},
left: Pixels(0.),
top: Pixels(0.),
right: Pixels(0.),
bottom: Pixels(0.),
};
#[inline]
fn is_for(&self, size: Size<Pixels>) -> bool {
self.size.width.0.to_bits() == size.width.0.to_bits()
&& self.size.height.0.to_bits() == size.height.0.to_bits()
}
fn new(size: Size<Pixels>, mask: &Bounds<Pixels>) -> Self {
const MARGIN: Pixels = Pixels(2.);
if mask.is_empty() {
return Self {
size,
left: Pixels(f32::INFINITY),
top: Pixels(f32::INFINITY),
right: Pixels(f32::NEG_INFINITY),
bottom: Pixels(f32::NEG_INFINITY),
};
}
let height = size.height + MARGIN;
let width = size.width + MARGIN;
let end = mask.bottom_right();
Self {
size,
left: mask.origin.x - width,
top: mask.origin.y - height,
right: end.x + height,
bottom: end.y + height,
}
}
#[inline]
fn contains(&self, x: Pixels, y: Pixels) -> bool {
y > self.top && y < self.bottom && x > self.left && x < self.right
}
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct GlyphRunRendering {
subpixel_rendering: bool,
dilation: u8,
}
impl Window {
pub(crate) fn glyph_run_rendering(
&self,
font_id: FontId,
font_size: Pixels,
color: Hsla,
) -> GlyphRunRendering {
GlyphRunRendering {
subpixel_rendering: self.should_use_subpixel_rendering(font_id, font_size),
dilation: self.text_system().glyph_dilation_for_color(color),
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn paint_glyph_in_run(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
color: Hsla,
rendering: GlyphRunRendering,
content_mask: ContentMask<ScaledPixels>,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let (integer_origin, subpixel_variant) = quantize_origin(glyph_origin);
let GlyphRunRendering {
subpixel_rendering,
dilation,
} = rendering;
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant,
scale_factor,
is_emoji: false,
subpixel_rendering,
dilation,
};
let (raster_bounds, tile, sprite_size) = match self.fast_glyph_bounds.lookup(¶ms) {
Some(kept) => kept,
None => {
let raster_bounds = self.text_system().raster_bounds(¶ms)?;
self.fast_glyph_bounds.insert(¶ms, raster_bounds);
(raster_bounds, None, None)
}
};
let sprite_origin = integer_origin + raster_bounds.origin.map(Into::into);
if !raster_bounds.is_zero() {
let tile = match tile {
Some(tile) => tile,
None if sprite_size.is_some_and(|size| {
Bounds::new(sprite_origin, size.map(Into::into))
.intersect(&content_mask.bounds)
.is_empty()
}) =>
{
return Ok(());
}
None => {
let tile = self
.sprite_atlas
.get_or_insert_with(params.clone().into(), &mut || {
let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
self.fast_glyph_bounds.insert_tile(¶ms, tile);
tile
}
};
let bounds = Bounds {
origin: sprite_origin,
size: tile.bounds.size.map(Into::into),
};
if subpixel_rendering {
self.next_frame.scene.insert_primitive(SubpixelSprite {
order: 0,
pad: 0,
bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
});
} else {
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
animation: Default::default(),
bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
});
}
}
Ok(())
}
}
pub(crate) struct LineGlyphPainter {
snapped_content_mask: ContentMask<ScaledPixels>,
content_mask: Bounds<Pixels>,
reach: GlyphReach,
run_rendering: Option<(FontId, Hsla, GlyphRunRendering)>,
}
impl LineGlyphPainter {
pub(crate) fn new(window: &Window) -> Self {
Self {
snapped_content_mask: window.snapped_content_mask(),
content_mask: window.content_mask().bounds,
reach: GlyphReach::UNSET,
run_rendering: None,
}
}
#[inline]
pub(crate) fn may_reach(
&mut self,
line_glyph: Bounds<Pixels>,
baseline: Pixels,
mask: &Bounds<Pixels>,
) -> bool {
debug_assert_eq!(*mask, self.content_mask);
if !self.reach.is_for(line_glyph.size) {
self.reach = GlyphReach::new(line_glyph.size, &self.content_mask);
}
self.reach
.contains(line_glyph.origin.x, line_glyph.origin.y + baseline)
}
pub(crate) fn paint_glyph(
&mut self,
window: &mut Window,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
color: Hsla,
) -> Result<()> {
let rendering = match self.run_rendering {
Some((run_font_id, run_color, rendering))
if run_font_id == font_id && run_color == color =>
{
rendering
}
_ => {
let rendering = window.glyph_run_rendering(font_id, font_size, color);
self.run_rendering = Some((font_id, color, rendering));
rendering
}
};
window.paint_glyph_in_run(
origin,
font_id,
glyph_id,
font_size,
color,
rendering,
self.snapped_content_mask,
)
}
}
const GLYPH_BOUNDS_SLOT_BITS: u32 = 12;
pub(crate) struct GlyphBoundsCache {
slots: Box<[Option<GlyphSlot>]>,
frame: u64,
bounding_boxes: Vec<(FontId, Pixels, Bounds<Pixels>)>,
}
#[derive(Clone)]
struct GlyphSlot {
params: RenderGlyphParams,
raster_bounds: Bounds<DevicePixels>,
tile: Option<(u64, AtlasTile)>,
}
impl Default for GlyphBoundsCache {
fn default() -> Self {
Self {
slots: vec![None; 1 << GLYPH_BOUNDS_SLOT_BITS].into_boxed_slice(),
frame: 0,
bounding_boxes: Vec::new(),
}
}
}
impl GlyphBoundsCache {
fn slot(params: &RenderGlyphParams) -> usize {
const K: u64 = 0x9e37_79b9_7f4a_7c15;
let words = [
params.glyph_id.0 as u64 | (params.font_id.0 as u64) << 32,
params.font_size.0.to_bits() as u64
| (params.subpixel_variant.x as u64) << 32
| (params.subpixel_variant.y as u64) << 40
| (params.dilation as u64) << 48
| (params.subpixel_rendering as u64) << 56
| (params.is_emoji as u64) << 57,
params.scale_factor.to_bits() as u64,
];
let hash = words.iter().fold(0u64, |hash, word| {
(hash.rotate_left(26) ^ word).wrapping_mul(K)
});
(hash >> (64 - GLYPH_BOUNDS_SLOT_BITS)) as usize
}
#[cfg(test)]
pub(crate) fn get(&self, params: &RenderGlyphParams) -> Option<Bounds<DevicePixels>> {
self.lookup(params).map(|(bounds, _, _)| bounds)
}
pub(crate) fn lookup(
&self,
params: &RenderGlyphParams,
) -> Option<(
Bounds<DevicePixels>,
Option<AtlasTile>,
Option<Size<DevicePixels>>,
)> {
match &self.slots[Self::slot(params)] {
Some(slot) if slot.params == *params => Some((
slot.raster_bounds,
slot.tile
.and_then(|(frame, tile)| (frame == self.frame).then_some(tile)),
slot.tile.map(|(_, tile)| tile.bounds.size),
)),
_ => None,
}
}
pub(crate) fn insert(&mut self, params: &RenderGlyphParams, bounds: Bounds<DevicePixels>) {
self.slots[Self::slot(params)] = Some(GlyphSlot {
params: params.clone(),
raster_bounds: bounds,
tile: None,
});
}
pub(crate) fn insert_tile(&mut self, params: &RenderGlyphParams, tile: AtlasTile) {
if let Some(slot) = &mut self.slots[Self::slot(params)]
&& slot.params == *params
{
slot.tile = Some((self.frame, tile));
}
}
pub(crate) fn finish_frame(&mut self) {
self.frame += 1;
}
}
const BOUNDING_BOXES: usize = 16;
#[inline]
pub(crate) fn bounding_box(
window: &mut Window,
cx: &App,
font_id: FontId,
font_size: Pixels,
) -> Bounds<Pixels> {
let boxes = &mut window.fast_glyph_bounds.bounding_boxes;
if let Some((_, _, bounds)) = boxes
.iter()
.rev()
.find(|(id, size, _)| *id == font_id && *size == font_size)
{
return *bounds;
}
let bounds = cx.text_system().bounding_box(font_id, font_size);
if boxes.len() == BOUNDING_BOXES {
boxes.remove(0);
}
boxes.push((font_id, font_size, bounds));
bounds
}
#[inline]
pub(crate) fn has_no_background(decoration_runs: &[DecorationRun]) -> bool {
decoration_runs
.iter()
.all(|run| run.background_color.is_none())
}