blob: 1324ff73451ec6efd4eab88d31b4c74f127996ba [file] [edit]
// Copyright 2025 the Vello Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Basic render operations.
use crate::RenderMode;
use crate::dispatch::Dispatcher;
#[cfg(feature = "multithreading")]
use crate::dispatch::multi_threaded::MultiThreadedDispatcher;
#[cfg(feature = "text")]
use crate::text::{GlyphAtlasResources, GlyphRunBuilder};
#[cfg(feature = "text")]
use glifo::{GlyphPrepCache, HintCacheConfig};
use crate::dispatch::single_threaded::SingleThreadedDispatcher;
use crate::kurbo::{PathEl, Point};
use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use hashbrown::HashMap;
use vello_common::blurred_rounded_rect::BlurredRoundedRect;
use vello_common::clip::Clip;
use vello_common::color::{AlphaColor, Srgb};
use vello_common::encode::{EncodeExt, EncodedPaint};
use vello_common::fearless_simd::Level;
use vello_common::filter::FilterData;
use vello_common::filter_effects::Filter;
use vello_common::kurbo::{Affine, BezPath, Rect, Stroke};
use vello_common::mask::Mask;
use vello_common::paint::{Brush, ImageId, ImageResolver, Paint, PaintHandle};
use vello_common::peniko::{BlendMode, Fill};
use vello_common::pixmap::{Pixmap, PixmapMut};
use vello_common::reset::ResetOptions;
use vello_common::util::into_fast_path_rect;
#[cfg(feature = "text")]
pub(crate) const DEFAULT_GLYPH_ATLAS_SIZE: u16 = 4096;
/// Persistent resources required by Vello CPU for rendering.
///
/// You should create one such instance per renderer.
#[derive(Debug, Default)]
pub struct Resources {
pub(crate) image_registry: ImageRegistry,
#[cfg(feature = "text")]
pub(crate) glyph_prep_cache: GlyphPrepCache,
// Will be initialized lazily on first use.
#[cfg(feature = "text")]
pub(crate) glyph_resources: Option<GlyphAtlasResources>,
}
impl Resources {
/// Create a new set of renderer resources.
pub fn new() -> Self {
Self::default()
}
/// Create a new set of renderer resources whose glyph hinting cache uses `config`.
#[cfg(feature = "text")]
pub fn with_hint_cache_config(config: HintCacheConfig) -> Self {
Self {
glyph_prep_cache: GlyphPrepCache::with_hint_cache_config(config),
..Self::default()
}
}
pub(crate) fn before_render(&mut self, render_mode: RenderMode) {
#[cfg(feature = "text")]
self.prepare_glyph_cache(render_mode);
#[cfg(not(feature = "text"))]
let _ = render_mode;
}
pub(crate) fn after_render(&mut self) {
#[cfg(feature = "text")]
self.maintain_glyph_cache();
}
}
/// How the destination pixmap is initialized before rendering.
pub type TargetInit = vello_common::TargetInit<AlphaColor<Srgb>>;
/// The pixel format to assume for the destination pixmap.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum PixelFormat {
/// Premultiplied RGBA8.
#[default]
Rgba8,
}
/// Settings used when rasterizing a scene into a pixmap.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct RasterizerSettings {
/// Whether to prioritize speed or quality when rendering.
///
/// For most cases (especially for real-time rendering), it is highly recommended to set
/// this to [`RenderMode::OptimizeSpeed`]. If color accuracy is a more significant concern,
/// then you can set this to [`RenderMode::OptimizeQuality`].
///
/// Currently, the only difference this makes is that when choosing [`RenderMode::OptimizeSpeed`],
/// rasterization will happen using u8/u16,
/// while [`RenderMode::OptimizeQuality`] will use a f32-based pipeline.
pub render_mode: RenderMode,
/// How the destination is initialized before drawing.
pub target_init: TargetInit,
/// Pixel format of the destination.
pub pixel_format: PixelFormat,
/// Offset in destination pixels where the render context origin is placed.
///
/// See [`RenderContext::render_with`] for more information.
pub offset: (i32, i32),
}
impl Default for RasterizerSettings {
fn default() -> Self {
Self {
render_mode: RenderMode::OptimizeSpeed,
target_init: TargetInit::Clear(AlphaColor::TRANSPARENT),
pixel_format: PixelFormat::Rgba8,
offset: (0, 0),
}
}
}
/// A render context for CPU-based 2D graphics rendering.
///
/// This is the main entry point for drawing operations.
#[derive(Debug)]
pub struct RenderContext {
/// Width of the render target in pixels.
pub(crate) width: u16,
/// Height of the render target in pixels.
pub(crate) height: u16,
/// Temporary path buffer to avoid repeated allocations.
pub(crate) temp_path: BezPath,
pub(crate) encoded_paints: Vec<EncodedPaint>,
pub(crate) render_settings: RenderSettings,
dispatcher: Box<dyn Dispatcher>,
}
/// Settings to apply to the render context.
#[derive(Copy, Clone, Debug)]
pub struct RenderSettings {
/// The SIMD level that should be used for rendering operations.
pub level: Level,
/// The number of worker threads that should be used for rendering. Only has an effect
/// if the `multithreading` feature is active.
pub num_threads: u16,
/// Disables anti-aliasing, painting only pixels whose coverage exceeds this threshold.
pub aliasing_threshold: Option<u8>,
}
impl Default for RenderSettings {
fn default() -> Self {
Self {
level: Level::try_detect().unwrap_or(Level::baseline()),
#[cfg(feature = "multithreading")]
num_threads: (std::thread::available_parallelism()
.unwrap()
.get()
.saturating_sub(1) as u16)
.min(8),
#[cfg(not(feature = "multithreading"))]
num_threads: 0,
aliasing_threshold: None,
}
}
}
/// A layer pushed with [`RenderContext::push_layer`].
#[derive(Debug, Clone)]
pub struct Layer<'a> {
/// Clip the layer to this path.
pub clip: Option<Clip<'a>>,
/// The blend mode used to composite the layer.
pub blend_mode: BlendMode,
/// The opacity of the layer, between 0 and 1.
pub opacity: f32,
/// A mask applied to the layer.
///
/// The mask must have the same dimension as the render context.
// TODO: Lift the above restriction.
pub mask: Option<Mask>,
/// A filter applied to the layer.
pub filter: Option<Filter>,
}
impl Default for Layer<'_> {
fn default() -> Self {
Self {
clip: None,
blend_mode: BlendMode::default(),
opacity: 1.0,
mask: None,
filter: None,
}
}
}
impl<'a> Layer<'a> {
/// Clip the layer to `clip`.
#[must_use]
pub fn with_clip(mut self, clip: impl Into<Clip<'a>>) -> Self {
self.clip = Some(clip.into());
self
}
/// Set the blend mode.
#[must_use]
pub fn with_blend_mode(mut self, blend_mode: BlendMode) -> Self {
self.blend_mode = blend_mode;
self
}
/// Set the opacity.
#[must_use]
pub fn with_opacity(mut self, opacity: f32) -> Self {
self.opacity = opacity;
self
}
/// Set the mask.
#[must_use]
pub fn with_mask(mut self, mask: Mask) -> Self {
self.mask = Some(mask);
self
}
/// Set the filter.
#[must_use]
pub fn with_filter(mut self, filter: Filter) -> Self {
self.filter = Some(filter);
self
}
}
impl RenderContext {
/// Create a new render context with the given width and height in pixels.
pub fn new(width: u16, height: u16) -> Self {
Self::new_with(width, height, RenderSettings::default())
}
/// Create a new render context with specific settings.
pub fn new_with(width: u16, height: u16, settings: RenderSettings) -> Self {
#[cfg(feature = "multithreading")]
let dispatcher: Box<dyn Dispatcher> = if settings.num_threads == 0 {
Box::new(SingleThreadedDispatcher::new(
width,
height,
settings.level,
settings.aliasing_threshold,
))
} else {
Box::new(MultiThreadedDispatcher::new(
width,
height,
settings.num_threads,
settings.level,
settings.aliasing_threshold,
))
};
#[cfg(not(feature = "multithreading"))]
let dispatcher: Box<dyn Dispatcher> = {
Box::new(SingleThreadedDispatcher::new(
width,
height,
settings.level,
settings.aliasing_threshold,
))
};
Self {
width,
height,
dispatcher,
render_settings: settings,
temp_path: BezPath::new(),
encoded_paints: vec![],
}
}
fn path_transform(&self, transform: Affine) -> Affine {
self.dispatcher.root_transform() * transform
}
fn aliasing_threshold(&self) -> Option<u8> {
self.render_settings.aliasing_threshold
}
fn encode_paint(&mut self, paint: &Paint, path_transform: Affine) -> Option<PaintHandle> {
let transform = path_transform * paint.transform;
match &paint.brush {
Brush::Solid(s) => Some((*s).into()),
Brush::Gradient(g) => {
// TODO: Add caching?
g.encode_into(&mut self.encoded_paints, transform, None)
}
Brush::Image(i) => i
.image
.encode_into(&mut self.encoded_paints, transform, i.tint),
}
}
/// Fill a path.
pub fn fill_path(
&mut self,
path: &BezPath,
fill: Fill,
paint: impl Into<Paint>,
transform: Affine,
mask: Option<&Mask>,
) {
let paint = paint.into();
let transform = self.path_transform(transform);
let Some(encoded) = self.encode_paint(&paint, transform) else {
return;
};
self.dispatcher.fill_path(
path,
fill,
transform,
encoded,
paint.blend_mode,
mask.cloned(),
);
}
/// Stroke a path.
pub fn stroke_path(
&mut self,
path: &BezPath,
stroke: &Stroke,
paint: impl Into<Paint>,
transform: Affine,
mask: Option<&Mask>,
) {
let paint = paint.into();
let transform = self.path_transform(transform);
let Some(encoded) = self.encode_paint(&paint, transform) else {
return;
};
self.dispatcher.stroke_path(
path,
stroke,
transform,
encoded,
paint.blend_mode,
mask.cloned(),
);
}
/// Fill a rectangle.
pub fn fill_rect(
&mut self,
rect: &Rect,
paint: impl Into<Paint>,
transform: Affine,
mask: Option<&Mask>,
) {
let paint = paint.into();
let transform = self.path_transform(transform);
let Some(encoded) = self.encode_paint(&paint, transform) else {
return;
};
let aliasing_threshold = self.aliasing_threshold();
// Fast path: Use optimized rect filling if we have no skew in the path transform
// and anti-aliasing is enabled.
// TODO: Maybe also support no anti-aliasing in the fast path
if let Some(transformed_rect) = into_fast_path_rect(*rect, &transform, aliasing_threshold) {
self.dispatcher.fill_rect_fast(
&transformed_rect,
encoded,
paint.blend_mode,
mask.cloned(),
);
} else {
// Fall back to path-based rendering for rotated/skewed transforms.
self.rect_to_temp_path(rect);
self.dispatcher.fill_path(
&self.temp_path,
Fill::NonZero,
transform,
encoded,
paint.blend_mode,
mask.cloned(),
);
}
}
/// Stroke a rectangle.
pub fn stroke_rect(
&mut self,
rect: &Rect,
stroke: &Stroke,
paint: impl Into<Paint>,
transform: Affine,
mask: Option<&Mask>,
) {
let paint = paint.into();
let transform = self.path_transform(transform);
let Some(encoded) = self.encode_paint(&paint, transform) else {
return;
};
self.rect_to_temp_path(rect);
self.dispatcher.stroke_path(
&self.temp_path,
stroke,
transform,
encoded,
paint.blend_mode,
mask.cloned(),
);
}
fn rect_to_temp_path(&mut self, rect: &Rect) {
self.temp_path.truncate(0);
self.temp_path
.push(PathEl::MoveTo(Point::new(rect.x0, rect.y0)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x1, rect.y0)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x1, rect.y1)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x0, rect.y1)));
self.temp_path.push(PathEl::ClosePath);
}
/// Fill a blurred rounded rectangle.
pub fn fill_blurred_rounded_rect(
&mut self,
shape: &BlurredRoundedRect,
blend_mode: BlendMode,
transform: Affine,
mask: Option<&Mask>,
) {
let rect = shape.rect.abs();
let transform = self.path_transform(transform);
let Some(encoded) = shape.encode_into(&mut self.encoded_paints, transform, false) else {
return;
};
// The actual rectangle we paint needs to be larger so that the blurring effect
// is not cut off.
// The impulse response of a gaussian filter is infinite.
// For performance reason we cut off the filter at some extent where the response is close to zero.
let kernel_size = 2.5 * shape.std_dev;
let inflated_rect = rect.inflate(f64::from(kernel_size), f64::from(kernel_size));
self.rect_to_temp_path(&inflated_rect);
self.dispatcher.fill_path(
&self.temp_path,
Fill::NonZero,
transform,
encoded,
blend_mode,
mask.cloned(),
);
}
/// Fill `path` with a blurred rounded rectangle.
///
/// This effectively draws the blurred rounded rectangle clipped to `path`. If just the blurred
/// rounded rectangle is desired without clipping, use the simpler
/// [`Self::fill_blurred_rounded_rect`], which will be easier to use for many users.
///
/// When `invert` is `false`, the color is applied with the coverage (`alpha`) of the blurred
/// rounded rectangle. Points which are more than approximately 2.5 times `shape.std_dev`
/// outside of the edges of `shape.rect` will not be perceptibly painted to, but calculations
/// will still be performed for them. So for performance reasons, `path` should not extend
/// further than that.
///
/// When `invert` is `true`, the inverse (`1 - alpha`) of that coverage is applied instead. The
/// coverage then falls off towards the inside of `shape.rect`, and is effectively full at all
/// points of `path` which are more than approximately 2.5 times `shape.std_dev` outside of the
/// edges of `shape.rect`. This means that the extent of the painted area is determined only by
/// `path`, which can extend as far beyond `shape.rect` as is needed. This can be used to
/// implement inset box shadows, by using the box as `path`, the box shrunk by the spread of the
/// shadow and translated by its offset as `shape.rect`, and the corner radius of the box
/// reduced by the spread as `shape.radius`.
pub fn fill_blurred_rounded_rect_in(
&mut self,
path: &BezPath,
fill: Fill,
shape: &BlurredRoundedRect,
invert: bool,
blend_mode: BlendMode,
transform: Affine,
mask: Option<&Mask>,
) {
let transform = self.path_transform(transform);
let Some(encoded) = shape.encode_into(&mut self.encoded_paints, transform, invert) else {
return;
};
self.dispatcher
.fill_path(path, fill, transform, encoded, blend_mode, mask.cloned());
}
/// Creates a builder for drawing a run of glyphs that have the same attributes.
#[cfg(feature = "text")]
pub fn glyph_run<'a>(
&'a mut self,
resources: &'a mut Resources,
font: &crate::peniko::FontData,
paint: impl Into<Paint>,
transform: Affine,
mask: Option<&Mask>,
) -> GlyphRunBuilder<'a> {
glifo::GlyphRunBuilder::new(
font.clone(),
transform,
paint.into(),
crate::text::CpuGlyphRunBackend {
ctx: self,
resources,
atlas_cache_enabled: false,
mask: mask.cloned(),
},
)
}
/// Push a new layer with the given transform.
///
/// Note that a layer's mask is not affected by the transform.
///
/// # Panics
///
/// Panics if the layer has a filter and this context uses multi-threaded rendering.
pub fn push_layer(&mut self, layer: Layer<'_>, transform: Affine) {
let mask = layer
.mask
.filter(|m| m.width() == self.width && m.height() == self.height);
let opacity = layer.opacity.clamp(0.0, 1.0);
let layer_transform = self.path_transform(transform);
let filter_data = layer
.filter
.map(|filter| FilterData::new(filter, layer_transform));
self.dispatcher.push_layer(
layer.clip.map(|clip| clip.path),
layer.clip.map_or(Fill::NonZero, |clip| clip.fill),
layer_transform,
layer.blend_mode,
opacity,
mask,
filter_data,
);
}
/// Pop the last-pushed layer.
pub fn pop_layer(&mut self) {
self.dispatcher.pop_layer();
}
/// Reset the render context.
pub fn reset(&mut self) {
self.dispatcher.reset(self.width, self.height);
self.encoded_paints.clear();
}
/// Reset the render context according to `options`.
pub fn reset_with(&mut self, options: ResetOptions) {
let (width, height) = options.size.unwrap_or((self.width, self.height));
if options.shrink {
*self = Self::new_with(width, height, self.render_settings);
} else {
self.width = width;
self.height = height;
self.reset();
}
}
/// Push a new clip path to the clip stack.
///
/// See the explanation in the [clipping](https://github.com/linebender/vello/tree/main/vello_cpu/examples)
/// example for how this method differs from clip layers.
pub fn push_clip_path<'a>(&mut self, clip: impl Into<Clip<'a>>, transform: Affine) {
let clip = clip.into();
self.dispatcher
.push_clip_path(clip.path, clip.fill, transform);
}
/// Push a rectangular clip path.
pub fn push_clip_rect(&mut self, rect: &Rect, transform: Affine) {
if let Some(rect) = into_fast_path_rect(*rect, &transform, self.aliasing_threshold()) {
self.dispatcher.push_clip_rect(&rect);
} else {
self.rect_to_temp_path(rect);
self.dispatcher
.push_clip_path(&self.temp_path, Fill::NonZero, transform);
}
}
/// Pop the most recently pushed clip path or clip rectangle from the clip stack.
///
/// Note that unlike layers, it is permissible to have pending pushed clips before
/// finishing the rendering operation.
pub fn pop_clip(&mut self) {
self.dispatcher.pop_clip();
}
/// Flush any pending operations.
///
/// This is a no-op when using the single-threaded render mode, and can be ignored.
/// For multi-threaded rendering, you _have_ to call this before rasterizing, otherwise
/// the program will panic.
pub fn flush(&mut self) {
self.dispatcher.flush();
}
/// Render the current context into a target using default rasterizer settings.
///
/// See the documentation of [`RenderContext::render_with`] for more information.
pub fn render<'a>(&self, target: impl Into<PixmapMut<'a>>, resources: &mut Resources) {
self.render_with(target, resources, RasterizerSettings::default());
}
/// Render the current context into a target using custom rasterizer settings.
///
/// See the documentation of [`RasterizerSettings`] to understand the tunable parameters for
/// rasterization.
///
/// There is an important note to make about render sizes. [`RenderContext`] can be configured with
/// a specific width/height, but so can [`Pixmap`]. In the vast majority of cases, you will simply
/// want to configure them both to have the same size. However, it _is_ very much possible for them
/// to have different sizes, which can be useful in certain situations. In principle, the size
/// that you specify when creating a [`RenderContext`] defines the bound of the scene itself. Any
/// content that is to the top/left of (0, 0) and to the right/bottom of (width/height) will be
/// removed. However, the offset in [`RasterizerSettings`] as well as the width/height of
/// the [`PixmapMut`] define at which location the scene will be rasterized into, and allows
/// for further clipping certain parts of the scene away. The semantics are defined as follows:
///
/// 1. [`RasterizerSettings::offset`] defines the where the top-left corner will be positioned
/// on the pixmap, assuming a y-down coordinate system. In most cases (0, 0) will be the
/// appropriate choice, but other values are certainly sensible. For example, if you want to
/// implement a custom glyph-atlas, you can construct the scene assuming (0, 0) as the origin
/// and then position the glyphs at rasterization time using this feature.
///
/// 2. In case the pixmap width/height is larger than the offset plus the width/height of the
/// [`RenderContext`], any remaining rows/columns are simply treated as padding (**however**,
/// when using [`TargetInit::Clear`], then the _whole_ destination pixmap will
/// be cleared to the requested color, not just the area covered by the scene). One potential reason for doing this
/// is that certain platforms, for example macOS, require a specific byte stride for buffers.
/// For example, let's say that a byte stride of 128 is imposed by the platform, but the actual
/// size of the scene you are drawing is only 20x20. In this case, you can create a pixmap
/// of size 32x20, and the last 12 columns are essentially treated as padding.
///
/// 3. In case the width/height of the pixmap is _smaller_ than the offset + width/height of the
/// scene, then anything that exceeds the pixmap boundaries is simply cut off. This can be useful
/// if for some reason you only want to rasterize a small cut-out of the original scene.
/// Negative offsets cut off the top/left in the same way.
pub fn render_with<'a>(
&self,
target: impl Into<PixmapMut<'a>>,
resources: &mut Resources,
settings: RasterizerSettings,
) {
// TODO: Maybe we should move those checks into the dispatcher.
assert!(
!self.dispatcher.has_layers(),
"some layers haven't been popped yet"
);
resources.before_render(settings.render_mode);
let mut target = target.into();
let target_fully_covered = settings.offset == (0, 0)
&& self.width >= target.width()
&& self.height >= target.height();
// If the scene covers the whole pixmap than packing will take care
// of clearing everything anyway, so no reason to clear it explicitly
// here.
if let TargetInit::Clear(color) = settings.target_init
&& !target_fully_covered
{
let color = color.premultiply().to_rgba8().to_u32();
let data = target.data_mut();
if color == 0 {
data.fill(0);
} else {
// TODO: Optimize with SIMD? Unfortunately we can't just cast to u32 and use
// `fill` because the user-provided slice might not have the correct alignment.
let color = color.to_ne_bytes();
for pixel in data.as_chunks_mut::<4>().0 {
pixel.copy_from_slice(&color);
}
}
}
// The background is always isolated, so we don't need to worry about destructive
// blend modes.
match settings.target_init {
TargetInit::Clear(color) => {
target.set_may_have_transparency(color.components[3] != 1.0);
}
// Whatever is the current hint can be preserved.
TargetInit::SrcOver => {}
}
self.dispatcher.rasterize(
target,
self.width,
self.height,
settings,
&self.encoded_paints,
&resources.image_registry,
);
// TODO: We need to figure something out here API-wise. At the moment, the user can
// theoretically rasterize the same `RenderContext` multiple times without resetting in-between.
// However, if glyph caching is enabled, this method call could now evict that were previously
// assumed to exist in `RenderContext`, meaning that if the user rasterizes the same `RenderContext`
// again without resetting it, some of the cached glyphs might be stale and not exist anymore.
resources.after_render();
}
/// Return the width of the scene.
pub fn width(&self) -> u16 {
self.width
}
/// Return the height of the scene.
pub fn height(&self) -> u16 {
self.height
}
/// Return the render settings used by the `RenderContext`.
pub fn render_settings(&self) -> &RenderSettings {
&self.render_settings
}
/// Whether rendering is currently configured to run in multi-threaded mode.
pub fn is_multi_threaded(&self) -> bool {
self.dispatcher.is_multi_threaded()
}
}
/// Registry that maps opaque [`ImageId`]s to [`Pixmap`] data.
///
/// Used by [`RenderContext`] to resolve `ImageSource::Atlas` at rasterization time.
#[derive(Debug, Default)]
pub(crate) struct ImageRegistry {
images: HashMap<u32, Arc<Pixmap>>,
}
impl ImageRegistry {
#[cfg(feature = "text")]
pub(crate) fn register_atlas_page(&mut self, page_index: u32, pixmap: Arc<Pixmap>) {
self.images.insert(page_index, pixmap);
}
#[cfg(feature = "text")]
pub(crate) fn destroy_atlas_page(&mut self, page_index: u32) -> bool {
self.images.remove(&page_index).is_some()
}
}
impl ImageResolver for ImageRegistry {
fn resolve(&self, id: ImageId) -> Option<Arc<Pixmap>> {
self.images.get(&id.as_u32()).cloned()
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "text")]
use crate::peniko::{Blob, FontData};
use crate::{Layer, RasterizerSettings, RenderContext, ResetOptions, Resources, TargetInit};
#[cfg(feature = "text")]
use alloc::sync::Arc;
use alloc::vec;
#[cfg(feature = "text")]
use glifo::Glyph;
use vello_common::color::PremulRgba8;
use vello_common::color::palette::css::{BLACK, BLUE, RED};
use vello_common::kurbo::{Affine, Rect, Shape};
#[cfg(any(feature = "multithreading", feature = "text"))]
use vello_common::peniko::Fill;
use vello_common::peniko::ImageAlphaType;
use vello_common::pixmap::{PixelMetadata, Pixmap, PixmapMut};
use vello_common::tile::Tile;
const GRAY: PremulRgba8 = PremulRgba8 {
r: 9,
g: 10,
b: 11,
a: 255,
};
fn red_pixel() -> PremulRgba8 {
RED.premultiply().to_rgba8()
}
fn blue_pixel() -> PremulRgba8 {
BLUE.premultiply().to_rgba8()
}
fn transparent_pixel() -> PremulRgba8 {
PremulRgba8::from_u32(0)
}
fn solid_pixmap(width: u16, height: u16, color: PremulRgba8) -> Pixmap {
Pixmap::from_parts(
bytemuck::cast_vec(vec![color; usize::from(width) * usize::from(height)]),
width,
height,
PixelMetadata::new(ImageAlphaType::AlphaPremultiplied, color.a != 255),
)
}
fn red_rect_context(width: u16, height: u16, rect: Rect) -> RenderContext {
let mut ctx = RenderContext::new(width, height);
ctx.fill_rect(&rect, RED, Affine::IDENTITY, None);
ctx.flush();
ctx
}
#[test]
fn clip_overflow() {
let mut ctx = RenderContext::new(100, 100);
for _ in 0..(usize::from(u16::MAX) + 1).div_ceil(usize::from(Tile::HEIGHT * Tile::WIDTH)) {
ctx.fill_rect(
&Rect::new(0.0, 0.0, 1.0, 1.0),
BLACK,
Affine::IDENTITY,
None,
);
}
let clip = Rect::new(20.0, 20.0, 180.0, 180.0).to_path(0.1);
let layer = Layer::default().with_clip(&clip);
ctx.push_layer(layer, Affine::IDENTITY);
ctx.pop_layer();
ctx.flush();
}
#[test]
fn render_with_offset_clears_pixels_outside_scene() {
let ctx = red_rect_context(2, 2, Rect::new(0.0, 0.0, 2.0, 2.0));
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(4, 3, GRAY);
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
offset: (1, 1),
..Default::default()
},
);
for y in 0..3 {
for x in 0..4 {
let expected = if (1..=2).contains(&x) && (1..=2).contains(&y) {
red_pixel()
} else {
transparent_pixel()
};
assert_eq!(pixmap.sample(x, y), expected, "pixel at ({x}, {y})");
}
}
}
#[test]
fn render_clips_scene_to_target_bounds() {
let ctx = red_rect_context(3, 3, Rect::new(0.0, 0.0, 3.0, 3.0));
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(4, 4, GRAY);
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
offset: (2, 1),
..Default::default()
},
);
for y in 0..4 {
for x in 0..4 {
let expected = if (2..=3).contains(&x) && (1..=3).contains(&y) {
red_pixel()
} else {
transparent_pixel()
};
assert_eq!(pixmap.sample(x, y), expected, "pixel at ({x}, {y})");
}
}
}
#[test]
fn render_into_padded_pixmap() {
let ctx = red_rect_context(2, 2, Rect::new(0.0, 0.0, 2.0, 2.0));
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(4, 2, GRAY);
ctx.render(&mut pixmap, &mut resources);
for y in 0..2 {
for x in 0..4 {
let expected = if x < 2 {
red_pixel()
} else {
transparent_pixel()
};
assert_eq!(pixmap.sample(x, y), expected, "pixel at ({x}, {y})");
}
}
}
#[test]
fn reset_with_size_updates_scene_size() {
for shrink in [false, true] {
let mut ctx = RenderContext::new(8, 4);
let mut resources = Resources::new();
let mut pixmap = Pixmap::new(4, 8);
ctx.reset_with(ResetOptions {
size: Some((4, 8)),
shrink,
});
assert_eq!(ctx.width(), 4);
assert_eq!(ctx.height(), 8);
ctx.fill_rect(&Rect::new(0.0, 0.0, 4.0, 8.0), BLUE, Affine::IDENTITY, None);
ctx.flush();
ctx.render(&mut pixmap, &mut resources);
for y in 0..8 {
for x in 0..4 {
assert_eq!(pixmap.sample(x, y), blue_pixel(), "pixel at ({x}, {y})");
}
}
}
}
#[test]
fn render_into_raw_buffer() {
let ctx = red_rect_context(2, 1, Rect::new(0.0, 0.0, 2.0, 1.0));
let mut resources = Resources::new();
let mut buffer = vec![0; 3 * 2 * 4];
for pixel in buffer.as_chunks_mut::<4>().0 {
pixel.copy_from_slice(&[GRAY.r, GRAY.g, GRAY.b, GRAY.a]);
}
{
let pixmap = PixmapMut::new(3, 2, &mut buffer).unwrap();
ctx.render_with(
pixmap,
&mut resources,
RasterizerSettings {
offset: (1, 1),
..Default::default()
},
);
}
let expected = [
transparent_pixel(),
transparent_pixel(),
transparent_pixel(),
transparent_pixel(),
red_pixel(),
red_pixel(),
];
for (&pixel, expected) in buffer.as_chunks::<4>().0.iter().zip(expected) {
assert_eq!(pixel, [expected.r, expected.g, expected.b, expected.a]);
}
}
#[test]
fn pixmap_mut_validates_buffer_length() {
let mut short_buffer = vec![0; 3 * 2 * 4 - 1];
assert!(PixmapMut::new(3, 2, &mut short_buffer).is_none());
let mut exact_buffer = vec![0; 3 * 2 * 4];
assert!(PixmapMut::new(3, 2, &mut exact_buffer).is_some());
}
#[test]
fn render_preserves_target_under_opaque_draw() {
let ctx = red_rect_context(2, 1, Rect::new(0.0, 0.0, 1.0, 1.0));
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(2, 1, blue_pixel());
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
target_init: TargetInit::SrcOver,
..Default::default()
},
);
assert_eq!(pixmap.sample(0, 0), red_pixel());
assert_eq!(pixmap.sample(1, 0), blue_pixel());
}
#[test]
fn render_preserves_target_under_translucent_draw() {
let mut ctx = RenderContext::new(1, 1);
ctx.fill_rect(
&Rect::new(0.0, 0.0, 1.0, 1.0),
RED.with_alpha(0.5),
Affine::IDENTITY,
None,
);
ctx.flush();
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(1, 1, blue_pixel());
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
target_init: TargetInit::SrcOver,
..Default::default()
},
);
assert_eq!(
pixmap.sample(0, 0),
PremulRgba8 {
r: 128,
g: 0,
b: 127,
a: 255,
}
);
}
#[test]
fn opaque_clear_updates_target_transparency_hint() {
let mut ctx = RenderContext::new(1, 1);
ctx.flush();
let mut resources = Resources::new();
let mut pixmap = Pixmap::new(1, 1);
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
target_init: TargetInit::Clear(BLUE),
..Default::default()
},
);
assert!(!pixmap.may_have_transparency());
assert_eq!(pixmap.sample(0, 0), blue_pixel());
}
#[test]
fn translucent_clear_updates_target_transparency_hint() {
let mut ctx = RenderContext::new(1, 1);
ctx.flush();
let mut resources = Resources::new();
let mut pixmap = solid_pixmap(1, 1, blue_pixel());
let clear_color = RED.with_alpha(0.5);
ctx.render_with(
&mut pixmap,
&mut resources,
RasterizerSettings {
target_init: TargetInit::Clear(clear_color),
..Default::default()
},
);
assert!(pixmap.may_have_transparency());
assert_eq!(pixmap.sample(0, 0), clear_color.premultiply().to_rgba8());
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_crash_after_reset() {
use crate::{Level, RasterizerSettings, RenderMode, RenderSettings};
let mut pixmap = Pixmap::new(200, 200);
let settings = RenderSettings {
level: Level::try_detect().unwrap_or(Level::baseline()),
num_threads: 1,
..RenderSettings::default()
};
let rasterizer_settings = RasterizerSettings {
render_mode: RenderMode::OptimizeQuality,
..Default::default()
};
let mut resources = Resources::new();
let mut ctx = RenderContext::new_with(200, 200, settings);
ctx.reset();
ctx.fill_path(
&Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1),
Fill::NonZero,
BLACK,
Affine::IDENTITY,
None,
);
ctx.flush();
ctx.render_with(&mut pixmap, &mut resources, rasterizer_settings);
ctx.flush();
ctx.render_with(&mut pixmap, &mut resources, rasterizer_settings);
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_render_empty_frame_after_reset() {
use crate::RenderSettings;
let mut ctx = RenderContext::new_with(
100,
100,
RenderSettings {
num_threads: 4,
..Default::default()
},
);
let mut resources = Resources::new();
let mut pixmap = Pixmap::new(100, 100);
ctx.fill_rect(
&Rect::new(0.0, 0.0, 100.0, 100.0),
BLACK,
Affine::IDENTITY,
None,
);
ctx.flush();
ctx.render(&mut pixmap, &mut resources);
ctx.reset();
ctx.flush();
ctx.render(&mut pixmap, &mut resources);
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_push_clip_path_before_draw() {
use crate::RenderSettings;
let mut ctx = RenderContext::new_with(
100,
100,
RenderSettings {
num_threads: 1,
..Default::default()
},
);
let clip = Rect::new(0.0, 0.0, 50.0, 50.0).to_path(0.1);
// Just make sure we don't panic.
ctx.push_clip_path(&clip, Affine::IDENTITY);
ctx.flush();
ctx.pop_clip();
ctx.flush();
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_reset_with_pending_tasks() {
use crate::RenderSettings;
let mut ctx = RenderContext::new_with(
100,
100,
RenderSettings {
num_threads: 4,
..Default::default()
},
);
// Note: This test only works if we draw enough rectangles
// to trigger a batch send.
for _ in 0..300 {
ctx.fill_rect(
&Rect::new(0.0, 0.0, 100., 100.0),
BLACK,
Affine::IDENTITY,
None,
);
}
ctx.reset();
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_drop_with_pending_tasks() {
use crate::RenderSettings;
for _ in 0..10 {
let mut ctx = RenderContext::new_with(
100,
100,
RenderSettings {
num_threads: 4,
..Default::default()
},
);
// Note: This test only works if we draw enough rectangles
// to trigger a batch send.
for _ in 0..300 {
ctx.fill_rect(
&Rect::new(0.0, 0.0, 100., 100.0),
BLACK,
Affine::IDENTITY,
None,
);
}
drop(ctx);
}
}
#[cfg(feature = "text")]
#[test]
fn glyph_atlas_resources_are_lazy() {
const ROBOTO_FONT: &[u8] = include_bytes!("../../assets/roboto/Roboto-Regular.ttf");
let font = FontData::new(Blob::new(Arc::new(ROBOTO_FONT)), 0);
let glyphs = [Glyph {
id: 1,
x: 0.0,
y: 0.0,
}];
let mut resources = Resources::new();
let mut ctx = RenderContext::new(100, 100);
ctx.fill_rect(
&Rect::new(0.0, 0.0, 10.0, 10.0),
BLACK,
Affine::IDENTITY,
None,
);
ctx.fill_path(
&Rect::new(10.0, 10.0, 20.0, 20.0).to_path(0.1),
Fill::NonZero,
BLACK,
Affine::IDENTITY,
None,
);
ctx.glyph_run(&mut resources, &font, BLACK, Affine::IDENTITY, None)
.fill_glyphs(glyphs.into_iter())
.unwrap();
assert!(resources.glyph_resources.is_none());
ctx.glyph_run(&mut resources, &font, BLACK, Affine::IDENTITY, None)
.atlas_cache(true)
.fill_glyphs(glyphs.into_iter())
.unwrap();
assert!(resources.glyph_resources.is_some());
}
}