use std::{hash::Hash, ops::Range, sync::Arc};
use bytemuck::{Pod, Zeroable};
use crate::{
ArcGeometry, BlendMode, Brush, Color, CornerRadii, DrawPrimitive, GroupMarker, LineGeometry,
Point, Rect, ShapeRecordBody, ShapeRecordCurve, Stroke, StrokeCap, StrokeJoin, TAU, TileMode,
Trapezoid, arc_band,
float::{at_least, within},
vertex_gradient,
};
mod band_ring;
mod command_recording;
mod draw_groups;
mod materialize;
mod record_tables;
mod row_run;
mod shape_spans;
use band_ring::{BandRing, vertex_pixels};
use command_recording::RecordingContent;
pub use command_recording::{CommandRecorder, CommandRecording, LineRun};
use draw_groups::DrawGroups;
use materialize::{
ContentMarkers, brush_of, materialize_shape, parts_primitives_with_markers,
parts_segment_primitives,
};
pub use record_tables::RecordTables;
use row_run::{RowRun, line_body, line_curve, slice_body, slice_curve};
pub const RECORD_KIND_RECT: u32 = 0;
pub const RECORD_KIND_ROUND_RECT: u32 = 1;
pub const RECORD_KIND_ARC: u32 = 2;
pub const RECORD_KIND_LINE: u32 = 3;
pub const TRAPEZOID_CAP: u32 = 3;
const KIND_SHIFT: u32 = 0;
const STROKED_BIT: u32 = 1 << 2;
const CAP_SHIFT: u32 = 3;
const JOIN_SHIFT: u32 = 5;
const BLEND_SHIFT: u32 = 8;
const BAND_CAP_SHIFT: u32 = 16;
const ARC_DEGENERATE_BIT: u32 = 1 << 18;
const ARC_RECT_LOOSE_BIT: u32 = 1 << 19;
const ARC_BANDED_BIT: u32 = 1 << 20;
const BAND_CLASS_SHIFT: u32 = 21;
const BAND_CLASS_MASK: u32 = 0b111;
const VERTEX_GRADIENT_BIT: u32 = 1 << 24;
const OPEN_LEFT_BIT: u32 = 1 << JOIN_SHIFT;
const OPEN_RIGHT_BIT: u32 = 2 << JOIN_SHIFT;
const RECT_FILL_MASK: u32 = STROKED_BIT | (RECORD_KIND_ARC << KIND_SHIFT);
const NO_SEGMENT_KEY: u32 = u32::MAX;
pub const ARC_BUCKETS: usize = 7;
pub const ARC_BUCKET_SEGMENTS: [u32; ARC_BUCKETS] = [1, 2, 4, 8, 16, 32, 64];
pub const ARC_RING_SEGMENTS: [u32; 4] = [8, 16, 32, 64];
pub const ARC_RING_RADII: [f32; 3] = [24.0, 96.0, 384.0];
const ARC_RING_SEGMENTS_PER_RADIAN: [f32; ARC_RING_SEGMENTS.len()] = ring_segments_per_radian();
const fn ring_segments_per_radian() -> [f32; ARC_RING_SEGMENTS.len()] {
let mut out = [0.0; ARC_RING_SEGMENTS.len()];
let mut index = 0;
while index < ARC_RING_SEGMENTS.len() {
out[index] = ARC_RING_SEGMENTS[index] as f32 / TAU;
index += 1;
}
out
}
pub const ARC_BAND_MIN_RADIUS: f32 = 11.0;
pub const ARC_BAND_MIN_INNER_RADIUS: f32 = 1.0;
pub const BAND_MARGIN: f32 = 0.5 + 1.0 / 16.0;
pub const BAND_MAX_STEP: f32 = std::f32::consts::FRAC_PI_2;
pub const BAND_ANGULAR_PAD: f32 = 0.001;
pub const QUAD_VERTICES: u32 = 4;
pub const QUAD_INDICES: u32 = 6;
pub const BAND_MIN_SEGMENTS: u32 = 1;
pub const fn strip_vertices(segments: u32) -> u32 {
segments * 2 + 2
}
pub const fn strip_indices(segments: u32) -> u32 {
segments * QUAD_INDICES
}
pub fn strip_index_pattern(segments: u32) -> impl Iterator<Item = u32> {
(0..segments).flat_map(|quad| {
let base = quad * 2;
[base, base + 1, base + 2, base + 2, base + 1, base + 3]
})
}
pub const BAND_VERTEX_PIXELS: f32 = 32.0;
const BAND_STRIP_OVERSHOOT: f32 = 1.25;
const SEGMENT_WASTE_QUADS: u32 = 512;
pub fn band_padded_range(mid: f32, ring_half: f32, start: f32, sweep: f32) -> (f32, f32) {
let inner_padded = mid - ring_half;
if inner_padded <= 0.0 {
return (0.0, TAU);
}
let pad = ring_half / inner_padded + BAND_ANGULAR_PAD;
let padded = sweep + pad + pad;
if padded < TAU {
(start - pad, padded)
} else {
(0.0, TAU)
}
}
pub fn band_bucket(segments: u32) -> usize {
segments.trailing_zeros() as usize
}
pub fn band_class_segments(class: u8) -> u32 {
ARC_BUCKET_SEGMENTS[class as usize]
}
#[inline]
fn band_bucket_for(
geometry: &ArcGeometry,
degenerate: bool,
ring: &BandRing,
rect: Rect,
) -> Option<usize> {
if degenerate
|| geometry.outer_radius < ARC_BAND_MIN_RADIUS
|| geometry.inner_radius <= ARC_BAND_MIN_INNER_RADIUS
{
return None;
}
let segments = ring.segments();
(ring.strip_pixels(segments) < rect.width * rect.height + vertex_pixels(QUAD_VERTICES))
.then(|| band_bucket(segments))
}
fn paints_nothing(body: &ShapeRecordBody, blend: BlendMode) -> bool {
body.brush == 0
&& body.color[3] <= 0.0
&& !matches!(
blend,
BlendMode::Clear
| BlendMode::Src
| BlendMode::SrcIn
| BlendMode::DstIn
| BlendMode::SrcOut
| BlendMode::DstAtop
| BlendMode::Modulate
)
}
pub fn band_pays(geometry: &ArcGeometry, rect: Rect) -> bool {
band_bucket_for(
geometry,
geometry.is_degenerate(),
&BandRing::of_geometry(geometry),
rect,
)
.is_some()
}
pub const FRAGMENT_KIND_FILL: u32 = 0;
pub const FRAGMENT_KIND_STROKE: u32 = 1;
pub const FRAGMENT_KIND_ARC: u32 = 2;
pub const FRAGMENT_KIND_LINE: u32 = 3;
pub const FRAGMENT_KIND_TRAPEZOID: u32 = 4;
const TWO_BITS: u32 = 0b11;
const BLEND_MASK: u32 = 0xff;
pub const BRUSH_KIND_LINEAR: u32 = 1;
pub const BRUSH_KIND_RADIAL: u32 = 2;
pub const BRUSH_KIND_SWEEP: u32 = 3;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct ShapeRecord {
pub rect: [f32; 4],
pub radii: [f32; 4],
pub color: [f32; 4],
pub stroke_width: f32,
pub flags: u32,
pub brush: u32,
pub reserved: u32,
pub arc: [f32; 4],
pub arc_band: [f32; 4],
pub arc_normalized: [f32; 4],
}
impl ShapeRecord {
pub fn kind(&self) -> u32 {
(self.flags >> KIND_SHIFT) & TWO_BITS
}
pub fn is_stroked(&self) -> bool {
self.flags & STROKED_BIT != 0
}
pub fn fragment_kind(&self) -> u32 {
record_fragment_kind(self.flags)
}
pub fn stroke(&self) -> Option<Stroke> {
self.is_stroked().then(|| Stroke {
width: self.stroke_width,
cap: STROKE_CAPS[((self.flags >> CAP_SHIFT) & TWO_BITS) as usize],
join: STROKE_JOINS[((self.flags >> JOIN_SHIFT) & TWO_BITS) as usize],
})
}
pub fn blend_mode(&self) -> BlendMode {
BlendMode::ALL[((self.flags >> BLEND_SHIFT) & BLEND_MASK) as usize]
}
pub fn band_cap(&self) -> StrokeCap {
STROKE_CAPS[((self.flags >> BAND_CAP_SHIFT) & TWO_BITS) as usize]
}
pub fn is_degenerate_arc(&self) -> bool {
self.flags & ARC_DEGENERATE_BIT != 0
}
pub fn is_gradient(&self) -> bool {
self.brush != 0
}
pub fn is_vertex_gradient(&self) -> bool {
self.flags & VERTEX_GRADIENT_BIT != 0
}
pub fn is_banded(&self) -> bool {
self.flags & ARC_BANDED_BIT != 0
}
pub fn band_class(&self) -> usize {
((self.flags >> BAND_CLASS_SHIFT) & BAND_CLASS_MASK) as usize
}
pub fn band_segments(&self) -> u32 {
ARC_BUCKET_SEGMENTS[self.band_class()]
}
pub fn has_loose_rect(&self) -> bool {
self.flags & ARC_RECT_LOOSE_BIT != 0
}
pub fn stored_rect(&self) -> Rect {
row_rect(self.rect)
}
pub fn rect_value(&self) -> Rect {
match self.arc_geometry() {
Some(geometry) if self.has_loose_rect() => geometry.bounds(),
_ => self.stored_rect(),
}
}
pub fn coverage_rect(&self) -> Rect {
match self.line_geometry() {
Some(line) => line.bounds(),
None => expand_rect(self.rect_value(), self.half_stroke()),
}
}
fn half_stroke(&self) -> f32 {
if self.is_stroked() {
self.stroke_width * 0.5
} else {
0.0
}
}
pub fn line_geometry(&self) -> Option<LineGeometry> {
(self.kind() == RECORD_KIND_LINE && !is_trapezoid(self.flags)).then(|| LineGeometry {
start: Point::new(self.arc[0], self.arc[1]),
end: Point::new(self.arc_band[2], self.arc_band[3]),
half_width: self.stroke_width * 0.5,
cap: STROKE_CAPS[((self.flags >> CAP_SHIFT) & TWO_BITS) as usize],
})
}
pub fn trapezoid(&self) -> Option<Trapezoid> {
is_trapezoid(self.flags).then(|| Trapezoid {
left: self.arc_normalized[0],
right: self.arc_normalized[1],
top: [self.arc[0], self.arc[1]],
bottom: [self.arc_band[2], self.arc_band[3]],
open_left: self.flags & OPEN_LEFT_BIT != 0,
open_right: self.flags & OPEN_RIGHT_BIT != 0,
})
}
pub fn arc_geometry(&self) -> Option<ArcGeometry> {
(self.kind() == RECORD_KIND_ARC).then(|| ArcGeometry {
center: Point::new(self.arc[0], self.arc[1]),
inner_radius: self.arc_band[2],
outer_radius: self.arc_band[3],
start_angle: self.arc_normalized[0],
sweep_angle: self.arc_normalized[1],
cap: self.band_cap(),
})
}
}
fn band_interior_area(width: f32, height: f32, radii: [f32; 4]) -> f32 {
let [top_left, top_right, bottom_right, bottom_left] =
radii.map(|radius| at_least(radius, 0.0));
let across = inset_area(
width,
height,
top_left.max(bottom_left) + top_right.max(bottom_right),
0.0,
);
let down = inset_area(
width,
height,
0.0,
top_left.max(top_right) + bottom_left.max(bottom_right),
);
across.max(down)
}
fn fill_interior_area(width: f32, height: f32, radii: [f32; 4]) -> f32 {
let [top_left, top_right, bottom_right, bottom_left] =
radii.map(|radius| at_least(radius, 0.0) * (1.0 - std::f32::consts::FRAC_1_SQRT_2));
band_interior_area(width, height, radii).max(inset_area(
width,
height,
top_left.max(bottom_left) + top_right.max(bottom_right),
top_left.max(top_right) + bottom_left.max(bottom_right),
))
}
fn inset_area(width: f32, height: f32, less_width: f32, less_height: f32) -> f32 {
at_least(width - less_width, 0.0) * at_least(height - less_height, 0.0)
}
fn record_coverage(body: &ShapeRecordBody) -> Rect {
let half_stroke = if body.flags & STROKED_BIT != 0 {
body.stroke_width * 0.5
} else {
0.0
};
expand_rect(row_rect(body.rect), half_stroke)
}
fn interior_repays(body: &ShapeRecordBody, curve: &ShapeRecordCurve) -> bool {
if record_fragment_kind(body.flags) != FRAGMENT_KIND_FILL {
return false;
}
let [top_left, top_right, bottom_right, bottom_left] = curve.radii;
let rounded = top_left.max(top_right).max(bottom_right.max(bottom_left)) > 0.0;
let [_, _, width, height] = body.rect;
let area = width * height;
rounded && area > 0.0 && band_interior_area(width, height, curve.radii) * 2.0 >= area
}
pub const OCCLUDER_MIN_AREA: f32 = 1024.0;
pub(crate) fn interior_occludes(body: &ShapeRecordBody, curve: &ShapeRecordCurve) -> bool {
if record_fragment_kind(body.flags) != FRAGMENT_KIND_FILL
|| body.brush != 0
|| body.color[3] < 1.0
{
return false;
}
let [_, _, width, height] = body.rect;
fill_interior_area(width, height, curve.radii) >= OCCLUDER_MIN_AREA
}
pub fn record_is_degenerate_arc(flags: u32) -> bool {
flags & ARC_DEGENERATE_BIT != 0
}
pub fn record_cap_bits(flags: u32) -> u32 {
(flags >> CAP_SHIFT) & TWO_BITS
}
pub fn record_fragment_kind(flags: u32) -> u32 {
let kind = (flags >> KIND_SHIFT) & TWO_BITS;
if kind == RECORD_KIND_ARC {
FRAGMENT_KIND_ARC
} else if is_trapezoid(flags) {
FRAGMENT_KIND_TRAPEZOID
} else if kind == RECORD_KIND_LINE {
FRAGMENT_KIND_LINE
} else if flags & STROKED_BIT != 0 {
FRAGMENT_KIND_STROKE
} else {
FRAGMENT_KIND_FILL
}
}
fn is_trapezoid(flags: u32) -> bool {
(flags >> KIND_SHIFT) & TWO_BITS == RECORD_KIND_LINE
&& (flags >> CAP_SHIFT) & TWO_BITS == TRAPEZOID_CAP
}
const STROKE_CAPS: [StrokeCap; 3] = [StrokeCap::Butt, StrokeCap::Round, StrokeCap::Square];
const STROKE_JOINS: [StrokeJoin; 3] = [StrokeJoin::Miter, StrokeJoin::Round, StrokeJoin::Bevel];
const TILE_MODES: [TileMode; 4] = [
TileMode::Clamp,
TileMode::Repeated,
TileMode::Mirror,
TileMode::Decal,
];
#[inline]
fn pack_flags(kind: u32, stroke: Option<Stroke>, blend: BlendMode, band_cap: StrokeCap) -> u32 {
let mut flags = (kind << KIND_SHIFT) | ((blend as u32) << BLEND_SHIFT);
if let Some(stroke) = stroke {
flags |=
STROKED_BIT | ((stroke.cap as u32) << CAP_SHIFT) | ((stroke.join as u32) << JOIN_SHIFT);
}
flags | ((band_cap as u32) << BAND_CAP_SHIFT)
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct BrushRecord {
pub kind: u32,
pub tile_mode: u32,
pub stop_start: u32,
pub stop_count: u32,
pub params: [f32; 4],
pub explicit_start: u32,
pub explicit_len: u32,
pub reserved: [u32; 2],
}
const NO_EXPLICIT_STOPS: u32 = u32::MAX;
#[derive(Clone, Copy, PartialEq, Eq)]
enum BrushShading {
Solid,
Fragment,
Vertex,
}
impl BrushShading {
fn flag(self) -> u32 {
if self == Self::Vertex {
VERTEX_GRADIENT_BIT
} else {
0
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct GradientStopRecord {
pub color: [f32; 4],
pub position: [f32; 4],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RecordLane {
Shapes,
Others,
Content,
GroupStart,
GroupEnd,
}
impl RecordLane {
pub fn draws(self) -> bool {
matches!(self, Self::Shapes | Self::Others)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RecordSegment {
pub lane: RecordLane,
pub start: u32,
pub count: u32,
pub blend: BlendMode,
pub gradient: bool,
pub vertex_gradient: bool,
pub brushes: u8,
pub kinds: u8,
pub band_class: u8,
pub interiors: bool,
pub occluders: bool,
pub bare_interiors: bool,
}
impl RecordSegment {
pub fn range(&self) -> Range<usize> {
self.start as usize..(self.start + self.count) as usize
}
pub fn uniform_kind(&self) -> Option<u32> {
(self.kinds.count_ones() == 1).then(|| self.kinds.trailing_zeros())
}
pub fn uniform_brush(&self) -> Option<u32> {
(self.brushes.count_ones() == 1).then(|| self.brushes.trailing_zeros())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RecordingSummary {
pub has_text: bool,
pub has_shadow: bool,
pub has_non_shadow: bool,
pub has_pixel_sensitive: bool,
pub has_shapes: bool,
pub has_others: bool,
pub has_content_markers: bool,
pub has_groups: bool,
}
impl RecordingSummary {
fn note(&mut self, primitive: &DrawPrimitive) {
let primitive = unwrap_blend(primitive);
if matches!(primitive, DrawPrimitive::Shadow(_)) {
self.has_shadow = true;
return;
}
if matches!(primitive, DrawPrimitive::Content | DrawPrimitive::Group(_)) {
return;
}
self.has_non_shadow = true;
match primitive {
DrawPrimitive::Text(_) => {
self.has_text = true;
self.has_pixel_sensitive = true;
}
DrawPrimitive::Image { .. } => self.has_pixel_sensitive = true,
_ => {}
}
}
fn merge(&mut self, other: Self) {
self.has_text |= other.has_text;
self.has_shadow |= other.has_shadow;
self.has_non_shadow |= other.has_non_shadow;
self.has_pixel_sensitive |= other.has_pixel_sensitive;
self.has_shapes |= other.has_shapes;
self.has_others |= other.has_others;
self.has_content_markers |= other.has_content_markers;
self.has_groups |= other.has_groups;
}
pub fn shapes_only(&self) -> bool {
self.has_shapes && !self.has_others && !self.has_content_markers && !self.has_groups
}
}
fn unwrap_blend(mut primitive: &DrawPrimitive) -> &DrawPrimitive {
while let DrawPrimitive::Blend {
primitive: inner, ..
} = primitive
{
primitive = inner;
}
primitive
}
pub fn expand_rect(rect: Rect, margin: f32) -> Rect {
Rect {
x: rect.x - margin,
y: rect.y - margin,
width: rect.width + margin * 2.0,
height: rect.height + margin * 2.0,
}
}
pub fn primitive_coverage_rect(primitive: &DrawPrimitive) -> Option<Rect> {
match primitive {
DrawPrimitive::Blend { primitive, .. } => primitive_coverage_rect(primitive),
DrawPrimitive::Rect { rect, stroke, .. }
| DrawPrimitive::RoundRect { rect, stroke, .. }
| DrawPrimitive::Arc { rect, stroke, .. } => {
let half_stroke = stroke.as_ref().map_or(0.0, |stroke| stroke.width * 0.5);
Some(expand_rect(*rect, half_stroke))
}
DrawPrimitive::Line {
start, end, stroke, ..
} => Some(LineGeometry::new(*start, *end, *stroke).bounds()),
DrawPrimitive::Trapezoid { trapezoid, .. } => Some(trapezoid.bounds()),
DrawPrimitive::Image { rect, .. } => Some(*rect),
DrawPrimitive::Text(text) => Some(text.rect),
DrawPrimitive::Content | DrawPrimitive::Shadow(_) | DrawPrimitive::Group(_) => None,
}
}
#[derive(Clone, Debug)]
pub struct ShapeRecorder {
tables: RecordTables,
gradient_lists: crate::rare_list::RareList<GradientLists>,
last_segment_key: u32,
segment_waste: u32,
min: [f32; 2],
max: [f32; 2],
}
impl Default for ShapeRecorder {
fn default() -> Self {
Self {
tables: RecordTables::default(),
gradient_lists: crate::rare_list::RareList::default(),
last_segment_key: NO_SEGMENT_KEY,
segment_waste: 0,
min: [f32::INFINITY; 2],
max: [f32::NEG_INFINITY; 2],
}
}
}
#[derive(Clone, Debug)]
struct GradientLists {
colors: Arc<[Color]>,
stops: Option<Arc<[f32]>>,
}
impl PartialEq for ShapeRecorder {
fn eq(&self, other: &Self) -> bool {
self.tables == other.tables
}
}
pub enum Recorded {
Shape(Rect),
Other(DrawPrimitive),
}
#[inline]
fn extend_segment_in(tables: &mut RecordTables, extend: bool, opened: RecordSegment) {
if extend {
let last = tables.segments.last_mut().expect("a keyed segment exists");
last.count += 1;
last.brushes |= opened.brushes;
last.kinds |= opened.kinds;
last.band_class = last.band_class.max(opened.band_class);
last.interiors |= opened.interiors;
last.occluders |= opened.occluders;
last.bare_interiors |= opened.bare_interiors;
return;
}
tables.segments.push(opened);
}
impl ShapeRecorder {
pub fn tables(&self) -> &RecordTables {
&self.tables
}
fn tables_mut(&mut self) -> &mut RecordTables {
let tables = &mut self.tables;
tables.forget_fingerprint();
tables
}
pub fn is_empty(&self) -> bool {
self.tables.shapes.is_empty()
}
pub fn all_segments(&self) -> Range<u32> {
0..self.tables.segments.len() as u32
}
pub fn bounds(&self) -> Option<Rect> {
(self.min[0] <= self.max[0] && self.min[1] <= self.max[1]).then(|| Rect {
x: self.min[0],
y: self.min[1],
width: self.max[0] - self.min[0],
height: self.max[1] - self.min[1],
})
}
pub fn fingerprint(&self) -> u64 {
self.tables.fingerprint()
}
pub fn clear(&mut self) {
self.tables.clear();
self.gradient_lists.clear();
self.last_segment_key = NO_SEGMENT_KEY;
self.segment_waste = 0;
self.min = [f32::INFINITY; 2];
self.max = [f32::NEG_INFINITY; 2];
}
pub fn push_primitive(&mut self, primitive: DrawPrimitive) -> Recorded {
match primitive {
DrawPrimitive::Blend {
primitive,
blend_mode,
} => match self.push_shape_primitive(*primitive, blend_mode) {
Recorded::Other(inner) => Recorded::Other(DrawPrimitive::Blend {
primitive: Box::new(inner),
blend_mode,
}),
recorded => recorded,
},
other => self.push_shape_primitive(other, BlendMode::SrcOver),
}
}
pub fn push_shape_primitive(
&mut self,
primitive: DrawPrimitive,
blend_mode: BlendMode,
) -> Recorded {
Recorded::Shape(match primitive {
DrawPrimitive::Rect {
rect,
brush,
stroke,
} => self.push_rect(rect, &brush, stroke, blend_mode),
DrawPrimitive::RoundRect {
rect,
brush,
radii,
stroke,
} => self.push_round_rect(rect, &brush, radii, stroke, blend_mode),
DrawPrimitive::Arc {
rect,
brush,
center,
radius,
start_angle,
sweep_angle,
stroke,
inner_radius,
} => self.push_arc(
rect,
&ArcRecordArgs {
brush: &brush,
center,
radius,
start_angle,
sweep_angle,
stroke,
inner_radius,
blend_mode,
},
),
DrawPrimitive::Line {
brush,
start,
end,
stroke,
..
} => self.push_line(
&LineGeometry::new(start, end, stroke),
&brush,
stroke,
blend_mode,
),
DrawPrimitive::Trapezoid {
rect,
brush,
trapezoid,
} => {
self.push_trapezoids(rect, &[trapezoid], &brush, blend_mode);
trapezoid.bounds()
}
other => return Recorded::Other(other),
})
}
fn push_marker_segment(&mut self, lane: RecordLane, start: u32) {
self.last_segment_key = NO_SEGMENT_KEY;
self.tables_mut().segments.push(RecordSegment {
lane,
start,
count: 1,
blend: BlendMode::SrcOver,
gradient: false,
vertex_gradient: false,
brushes: 0,
kinds: 0,
band_class: 0,
interiors: false,
occluders: false,
bare_interiors: false,
});
}
pub fn push_line(
&mut self,
line: &LineGeometry,
brush: &Brush,
stroke: Stroke,
blend: BlendMode,
) -> Rect {
let brush = self.intern_brush(brush);
let mut flags = pack_flags(RECORD_KIND_LINE, Some(stroke), blend, StrokeCap::Butt);
if line.is_degenerate() {
flags |= ARC_DEGENERATE_BIT;
}
let frame = line.frame();
let ends = line.end_bounds();
let body = line_body(line, ends, brush, stroke.width, flags);
let curve = line_curve(&frame);
let bounds = line.bounds_around(ends, &frame);
self.include_bounds(bounds);
let shading = self.brush_shading(&body, &curve);
self.push_shaded(body, curve, [0.0; 4], (blend, shading), None);
bounds
}
pub fn push_trapezoids(
&mut self,
brush_rect: Rect,
trapezoids: &[Trapezoid],
brush: &Brush,
blend: BlendMode,
) {
let (handle, color) = self.intern_brush(brush);
let flags = pack_flags(RECORD_KIND_LINE, None, blend, StrokeCap::Butt)
| (TRAPEZOID_CAP << CAP_SHIFT);
let radii = rect_row(brush_rect);
let shading = self.brush_shading(
&ShapeRecordBody {
brush: handle,
flags,
..ShapeRecordBody::zeroed()
},
&ShapeRecordCurve {
radii,
arc_normalized: [0.0; 4],
},
);
let brush = (handle, color);
let mut run = RowRun::new(blend, shading);
for trapezoid in trapezoids {
let bounds = trapezoid.bounds();
self.include_bounds(bounds);
run.push(
self,
|| slice_body(trapezoid, bounds, brush, flags),
|| slice_curve(trapezoid, radii),
);
}
run.close(self);
}
#[inline]
pub fn push_rect(
&mut self,
rect: Rect,
brush: &Brush,
stroke: Option<Stroke>,
blend: BlendMode,
) -> Rect {
let (handle, color) = self.intern_brush(brush);
self.push_shape(
ShapeRecordBody {
rect: rect_row(rect),
color,
stroke_width: stroke.map_or(0.0, |stroke| stroke.width),
flags: pack_flags(RECORD_KIND_RECT, stroke, blend, StrokeCap::Butt),
brush: handle,
placement: 0,
arc_geometry: [0.0; 4],
},
ShapeRecordCurve {
radii: [0.0; 4],
arc_normalized: [0.0; 4],
},
[0.0; 4],
blend,
None,
)
}
pub fn push_round_rect(
&mut self,
rect: Rect,
brush: &Brush,
radii: CornerRadii,
stroke: Option<Stroke>,
blend: BlendMode,
) -> Rect {
let (handle, color) = self.intern_brush(brush);
let mut flags = pack_flags(RECORD_KIND_ROUND_RECT, stroke, blend, StrokeCap::Butt);
let mut arc_geometry = [0.0; 4];
let mut source = [0.0; 4];
let mut arc_normalized = [0.0; 4];
let mut bucket = None;
if let Some(ring) = stroked_circle_ring(rect, radii, stroke)
&& let band = BandRing::of_geometry(&ring)
&& let Some(ring_bucket) = band_bucket_for(
&ring,
ring.is_degenerate(),
&band,
expand_rect(rect, ring.half_thickness()),
)
{
flags |= ARC_BANDED_BIT;
arc_geometry = [
ring.center.x,
ring.center.y,
ring.inner_radius,
ring.outer_radius,
];
source = [ring.mid_radius(), ring.inner_radius, 0.0, TAU];
arc_normalized = [0.0, TAU, 0.0, 0.0];
bucket = Some(ring_bucket);
}
self.push_shape(
ShapeRecordBody {
rect: rect_row(rect),
color,
stroke_width: stroke.map_or(0.0, |stroke| stroke.width),
flags,
brush: handle,
placement: 0,
arc_geometry,
},
ShapeRecordCurve {
radii: [
radii.top_left,
radii.top_right,
radii.bottom_right,
radii.bottom_left,
],
arc_normalized,
},
source,
blend,
bucket,
)
}
pub fn push_arc(&mut self, rect: Rect, args: &ArcRecordArgs<'_>) -> Rect {
let geometry = normalized_band(args);
self.push_arc_band(args, &geometry, Some(rect), geometry.is_degenerate())
}
#[inline]
pub fn push_scope_arc(&mut self, args: &ArcRecordArgs<'_>, geometry: &ArcGeometry) -> Rect {
debug_assert!(
!geometry.is_degenerate(),
"the scope skips degenerate bands"
);
self.push_arc_band(args, geometry, None, false)
}
#[inline]
fn push_arc_band(
&mut self,
args: &ArcRecordArgs<'_>,
geometry: &ArcGeometry,
rect: Option<Rect>,
degenerate: bool,
) -> Rect {
let (handle, color) = self.intern_brush(args.brush);
let mut flags = pack_flags(RECORD_KIND_ARC, args.stroke, args.blend_mode, geometry.cap);
if degenerate {
flags |= ARC_DEGENERATE_BIT;
}
let rect = rect.unwrap_or_else(|| {
flags |= ARC_RECT_LOOSE_BIT;
band_disc(geometry)
});
let ring = BandRing::of_geometry(geometry);
let bucket = band_bucket_for(geometry, degenerate, &ring, rect);
if bucket.is_some() {
flags |= ARC_BANDED_BIT;
}
self.push_shape(
ShapeRecordBody {
rect: rect_row(rect),
color,
stroke_width: args.stroke.map_or(0.0, |stroke| stroke.width),
flags,
brush: handle,
placement: 0,
arc_geometry: [
args.center.x,
args.center.y,
geometry.inner_radius,
geometry.outer_radius,
],
},
ShapeRecordCurve {
radii: [0.0; 4],
arc_normalized: [geometry.start_angle, geometry.sweep_angle, 0.0, 0.0],
},
[
args.radius,
args.inner_radius,
args.start_angle,
args.sweep_angle,
],
args.blend_mode,
bucket,
)
}
#[inline(always)]
fn push_shape(
&mut self,
body: ShapeRecordBody,
curve: ShapeRecordCurve,
source: [f32; 4],
blend: BlendMode,
band_bucket: Option<usize>,
) -> Rect {
let coverage = record_coverage(&body);
self.include_bounds(coverage);
let shading = self.brush_shading(&body, &curve);
self.push_shaded(body, curve, source, (blend, shading), band_bucket);
coverage
}
fn push_shaded(
&mut self,
mut body: ShapeRecordBody,
curve: ShapeRecordCurve,
source: [f32; 4],
(blend, shading): (BlendMode, BrushShading),
band_bucket: Option<usize>,
) {
if paints_nothing(&body, blend) {
return;
}
let index = self.tables.shapes.len() as u32;
body.flags |= shading.flag();
let brush_bit = 1u8
<< match body.brush {
0 => 0,
index => self.tables.brushes()[index as usize - 1].kind,
};
let kind_bit = 1u8 << record_fragment_kind(body.flags);
let band_class = band_bucket.unwrap_or(0) as u8;
body.flags |= u32::from(band_class) << BAND_CLASS_SHIFT;
let extend =
self.note_segment_key(RecordLane::Shapes, blend, shading, is_trapezoid(body.flags))
&& self.segment_takes_class(band_class);
if !extend {
self.segment_waste = 0;
}
let joined = extend.then(|| self.tables.segments.last()).flatten();
let translucent = body.brush != 0 || body.color[3] < 1.0;
let interiors = !joined
.is_some_and(|segment| segment.interiors && (segment.bare_interiors || !translucent))
&& interior_repays(&body, &curve);
let occluders =
!joined.is_some_and(|segment| segment.occluders) && interior_occludes(&body, &curve);
let bare_interiors = interiors && translucent;
let tables = self.tables_mut();
tables.shapes.push(body, curve, source);
extend_segment_in(
tables,
extend,
RecordSegment {
lane: RecordLane::Shapes,
start: index,
count: 1,
blend,
gradient: shading == BrushShading::Fragment,
vertex_gradient: shading == BrushShading::Vertex,
brushes: brush_bit,
kinds: kind_bit,
band_class,
interiors,
occluders,
bare_interiors,
},
);
}
fn extend_segment(&mut self, lane: RecordLane, index: u32, blend: BlendMode, kind_bit: u8) {
let extend = self.note_segment_key(lane, blend, BrushShading::Solid, false);
if !extend {
self.segment_waste = 0;
}
extend_segment_in(
self.tables_mut(),
extend,
RecordSegment {
lane,
start: index,
count: 1,
blend,
gradient: false,
vertex_gradient: false,
brushes: 0,
kinds: kind_bit,
band_class: 0,
interiors: false,
occluders: false,
bare_interiors: false,
},
);
}
fn extends_plainly(&self) -> bool {
self.tables
.segments
.last()
.is_some_and(|segment| segment.band_class == 0)
}
fn segment_takes_class(&mut self, band_class: u8) -> bool {
let last = self.tables.segments.last().expect("a keyed segment exists");
let held = ARC_BUCKET_SEGMENTS[last.band_class as usize];
let wanted = ARC_BUCKET_SEGMENTS[band_class as usize];
let waste = if wanted > held {
last.count * (wanted - held)
} else {
held - wanted
};
if self.segment_waste + waste > SEGMENT_WASTE_QUADS {
return false;
}
self.segment_waste += waste;
true
}
#[inline]
fn note_segment_key(
&mut self,
lane: RecordLane,
blend: BlendMode,
shading: BrushShading,
slice: bool,
) -> bool {
let key = ((lane as u32) << 16)
| (u32::from(slice) << 15)
| ((blend as u32) << 2)
| shading as u32;
let extend = key == self.last_segment_key;
self.last_segment_key = key;
extend
}
#[inline]
fn include_bounds(&mut self, rect: Rect) {
let right = rect.x + rect.width;
let bottom = rect.y + rect.height;
if rect.x < self.min[0] {
self.min[0] = rect.x;
}
if rect.y < self.min[1] {
self.min[1] = rect.y;
}
if right > self.max[0] {
self.max[0] = right;
}
if bottom > self.max[1] {
self.max[1] = bottom;
}
}
#[inline]
fn brush_shading(&self, body: &ShapeRecordBody, curve: &ShapeRecordCurve) -> BrushShading {
if body.brush == 0 {
return BrushShading::Solid;
}
let tables = &self.tables;
let Some(brush) = tables.brushes().get(body.brush as usize - 1) else {
return BrushShading::Fragment;
};
let vertex = if is_trapezoid(body.flags) {
vertex_gradient::clamps_between_two_stops(brush, tables.stops(), curve.radii)
} else {
body.flags & RECT_FILL_MASK == 0
&& vertex_gradient::spans_quad(brush, tables.stops(), body.rect)
};
if vertex {
BrushShading::Vertex
} else {
BrushShading::Fragment
}
}
#[inline]
fn intern_brush(&mut self, brush: &Brush) -> (u32, [f32; 4]) {
match brush {
Brush::Solid(color) => (0, [color.0, color.1, color.2, color.3]),
gradient => self.intern_gradient(gradient),
}
}
#[cold]
#[inline(never)]
fn intern_gradient(&mut self, brush: &Brush) -> (u32, [f32; 4]) {
let (kind, tile_mode, params, colors, stops) = match brush {
Brush::Solid(color) => return (0, [color.0, color.1, color.2, color.3]),
Brush::LinearGradient {
colors,
stops,
start,
end,
tile_mode,
} => (
BRUSH_KIND_LINEAR,
*tile_mode,
[start.x, start.y, end.x, end.y],
colors,
stops,
),
Brush::RadialGradient {
colors,
stops,
center,
radius,
tile_mode,
} => (
BRUSH_KIND_RADIAL,
*tile_mode,
[center.x, center.y, *radius, 0.0],
colors,
stops,
),
Brush::SweepGradient {
colors,
stops,
center,
} => (
BRUSH_KIND_SWEEP,
TileMode::Clamp,
[center.x, center.y, 0.0, 0.0],
colors,
stops,
),
};
let tables = self.tables_mut().gradients_mut();
let stop_start = tables.stops.len() as u32;
let count = colors.len();
let positions = stops.as_deref().filter(|values| values.len() == count);
for (index, color) in colors.iter().enumerate() {
let position = positions.map_or_else(
|| {
if count <= 1 {
0.0
} else {
index as f32 / (count - 1) as f32
}
},
|values| values[index],
);
tables.stops.push(GradientStopRecord {
color: [color.0, color.1, color.2, color.3],
position: [position, 0.0, 0.0, 0.0],
});
}
let (explicit_start, explicit_len) = match stops {
Some(values) => {
let start = tables.explicit_stops.len() as u32;
tables.explicit_stops.extend_from_slice(values);
(start, values.len() as u32)
}
None => (0, NO_EXPLICIT_STOPS),
};
let record = BrushRecord {
kind,
tile_mode: tile_mode as u32,
stop_start,
stop_count: count as u32,
params,
explicit_start,
explicit_len,
reserved: [0; 2],
};
tables.brushes.push(record);
let handle = tables.brushes.len() as u32;
self.gradient_lists.push(GradientLists {
colors: Arc::clone(colors),
stops: stops.clone(),
});
let first = colors.first().copied().unwrap_or(Color(0.0, 0.0, 0.0, 0.0));
(handle, [first.0, first.1, first.2, first.3])
}
}
pub struct ArcRecordArgs<'a> {
pub brush: &'a Brush,
pub center: Point,
pub radius: f32,
pub start_angle: f32,
pub sweep_angle: f32,
pub stroke: Option<Stroke>,
pub inner_radius: f32,
pub blend_mode: BlendMode,
}
fn stroked_circle_ring(
rect: Rect,
radii: CornerRadii,
stroke: Option<Stroke>,
) -> Option<ArcGeometry> {
const CIRCLE_TOLERANCE: f32 = 0.01;
let stroke = stroke?;
if rect.width.to_bits() != rect.height.to_bits() || !stroke.is_visible() {
return None;
}
let half = rect.width * 0.5;
let radius = radii.top_left;
if !radius.is_finite()
|| radius <= 0.0
|| (radius - half).abs() > CIRCLE_TOLERANCE
|| radii.top_right.to_bits() != radius.to_bits()
|| radii.bottom_right.to_bits() != radius.to_bits()
|| radii.bottom_left.to_bits() != radius.to_bits()
{
return None;
}
let half_width = stroke.half_width();
Some(ArcGeometry::new(
Point::new(rect.x + half, rect.y + half),
(half - half_width).max(0.0),
half + half_width,
0.0,
TAU,
StrokeCap::Round,
))
}
fn union_rect(a: Rect, b: Rect) -> Rect {
let x = a.x.min(b.x);
let y = a.y.min(b.y);
Rect {
x,
y,
width: (a.x + a.width).max(b.x + b.width) - x,
height: (a.y + a.height).max(b.y + b.height) - y,
}
}
fn rect_row(rect: Rect) -> [f32; 4] {
[rect.x, rect.y, rect.width, rect.height]
}
fn row_rect(row: [f32; 4]) -> Rect {
Rect {
x: row[0],
y: row[1],
width: row[2],
height: row[3],
}
}
#[inline(always)]
pub fn normalized_band(args: &ArcRecordArgs<'_>) -> ArcGeometry {
ArcGeometry::of_band(
args.center,
arc_band(args.radius, args.inner_radius, args.stroke),
args.start_angle,
args.sweep_angle,
)
}
fn band_disc(geometry: &ArcGeometry) -> Rect {
let reach = geometry.outer_radius + geometry.half_thickness();
Rect {
x: geometry.center.x - reach,
y: geometry.center.y - reach,
width: reach + reach,
height: reach + reach,
}
}
pub fn arc_trig(start_angle: f32, sweep_angle: f32) -> [f32; 4] {
if sweep_angle >= TAU && start_angle == 0.0 {
return [0.0, -1.0, 0.0, -1.0];
}
let half_sweep = within(sweep_angle, 0.0, TAU) * 0.5;
let (mid_sin, mid_cos) = (start_angle + half_sweep).sin_cos();
let (half_sin, half_cos) = half_sweep.sin_cos();
[mid_sin, mid_cos, at_least(half_sin, 0.0), half_cos]
}
#[cfg(test)]
#[path = "tests/record_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/record_band_tests.rs"]
mod band_tests;