mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 06:24:39 +00:00
The checkerboard is one textured shape from a repeating 2x2 texture, for every checkerboard (FW-151)
This commit is contained in:
@@ -18,7 +18,9 @@ pub use detail::{DetailPlan, snap_to_texels};
|
||||
use super::{PixelRect, RasterSource, canvas_space};
|
||||
use crate::contract::{Access, Common, Component, Cx, NoValue, Outcome, PaintUi, Props as _, Role};
|
||||
use crate::primitives::textures::UNTINTED;
|
||||
use crate::primitives::{CachedTexture, Checker, Revision, TextureState, TextureStore, TextureStoreOptions, texture_factor, texture_side};
|
||||
use crate::primitives::{
|
||||
CachedTexture, Checker, CheckerArea, Revision, TextureState, TextureStore, TextureStoreOptions, texture_factor, texture_side,
|
||||
};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::memory::Remember as _;
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
@@ -27,7 +29,7 @@ use craft_behavior::kurbo::{Point as Point64, Rect as Rect64};
|
||||
use craft_behavior::{CanvasView, Metrics, PixelSize};
|
||||
use detail::{texel_extent, texel_origin};
|
||||
use egui::epaint::{Mesh, Vertex};
|
||||
use egui::{Color32, ColorImage, Context, Id, Pos2, Rect, Response, Shape, Stroke, TextureFilter, TextureOptions, pos2};
|
||||
use egui::{Color32, ColorImage, Context, Id, Response, Shape, TextureFilter, TextureOptions, pos2};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The style of a raster display: it has no look of its own.
|
||||
@@ -271,14 +273,7 @@ impl Component for RasterDisplay<'_> {
|
||||
let painter = ui.content_painter(cx);
|
||||
let corners = shown.view.quad(Rect64::new(0.0, 0.0, f64::from(shown.size.width), f64::from(shown.size.height)));
|
||||
if let Some(checker) = &self.checkerboard {
|
||||
let around = Rect::from_points(&corners);
|
||||
for shape in checker.shapes(&ui.env.tokens, shown.view.rect, around) {
|
||||
if shown.view.axis_aligned() {
|
||||
painter.painter.add(shape);
|
||||
} else if let Some(cell) = clipped_cell(&shape, &corners) {
|
||||
painter.painter.add(cell);
|
||||
}
|
||||
}
|
||||
painter.painter.add(checker.shape(painter.painter.ctx(), &ui.env.tokens, CheckerArea::Quad(corners), shown.view.rect.min));
|
||||
}
|
||||
let (texture, factor) = shown.base;
|
||||
if let Some(mapping) = &self.mapping {
|
||||
@@ -345,39 +340,3 @@ fn mapped_mesh(view: &CanvasView, texture: CachedTexture, factor: u32, size: Pix
|
||||
}
|
||||
Shape::mesh(mesh)
|
||||
}
|
||||
|
||||
/// The filled rect `shape` (a transparency grid cell) cut to the convex quad `corners`, or `None` when it is not a
|
||||
/// filled rect or lies outside the quad.
|
||||
fn clipped_cell(shape: &Shape, corners: &[Pos2; 4]) -> Option<Shape> {
|
||||
let Shape::Rect(cell) = shape else { return None };
|
||||
let rect = cell.rect;
|
||||
let polygon = clip_to_convex(&[rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()], corners);
|
||||
(polygon.len() >= 3).then(|| Shape::convex_polygon(polygon, cell.fill, Stroke::NONE))
|
||||
}
|
||||
|
||||
/// `subject` cut to the convex polygon `clip` (Sutherland-Hodgman), either winding.
|
||||
fn clip_to_convex(subject: &[Pos2], clip: &[Pos2; 4]) -> Vec<Pos2> {
|
||||
let cross = |a: Pos2, b: Pos2, p: Pos2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
||||
let winding = cross(clip[0], clip[1], clip[2]).signum();
|
||||
let mut polygon = subject.to_vec();
|
||||
for edge in 0..clip.len() {
|
||||
let (a, b) = (clip[edge], clip[(edge + 1) % clip.len()]);
|
||||
let inside = |p: Pos2| cross(a, b, p) * winding >= 0.0;
|
||||
let input = std::mem::take(&mut polygon);
|
||||
for (at, current) in input.iter().enumerate() {
|
||||
let previous = input[(at + input.len() - 1) % input.len()];
|
||||
if inside(*current) != inside(previous) {
|
||||
let (from, to) = (cross(a, b, previous), cross(a, b, *current));
|
||||
let t = from / (from - to);
|
||||
polygon.push(previous + (*current - previous) * t);
|
||||
}
|
||||
if inside(*current) {
|
||||
polygon.push(*current);
|
||||
}
|
||||
}
|
||||
if polygon.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
polygon
|
||||
}
|
||||
|
||||
@@ -112,3 +112,15 @@ fn a_pass_the_display_skipped_loses_no_damage() {
|
||||
let both = first.union(&second);
|
||||
assert!(!reads.is_empty() && reads.iter().all(|read| *read == (both, 1)), "the display reads both changes: {reads:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_checkerboard_paints_the_same_shapes_at_any_area() {
|
||||
let shapes = |document: Rc<Document>, zoom: f64| {
|
||||
let mut rig = rig(document, zoom);
|
||||
rig.frame();
|
||||
rig.fixture.shape_bounds().len()
|
||||
};
|
||||
let small = shapes(Document::new(40, 30), 1.0);
|
||||
let large = shapes(Document::new(400, 300), 4.0);
|
||||
assert_eq!(small, large, "a checkerboard over the whole canvas paints as many shapes as one over a corner of it");
|
||||
}
|
||||
|
||||
@@ -349,6 +349,16 @@ impl<'a> Draw<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left. A `Draw` for an
|
||||
/// inactive part fills the rect with the theme's disabled fill instead, as `data_fill` does.
|
||||
pub fn checker(&self, checker: &super::Checker, rect: Rect, radius: CornerRadius) {
|
||||
if self.inactive {
|
||||
self.data_fill(&PaintShape::Rect(rect, radius), DataColor::new(Color32::TRANSPARENT));
|
||||
} else {
|
||||
self.painter.add(checker.shape(self.painter.ctx(), self.env.tokens, super::CheckerArea::Rect(rect, radius), rect.min));
|
||||
}
|
||||
}
|
||||
|
||||
fn data_color(&self, color: DataColor) -> Color32 {
|
||||
if self.inactive { crate::style::rgba_color(self.env.tokens.color.state.disabled_fill) } else { color.0 }
|
||||
}
|
||||
|
||||
@@ -6,9 +6,14 @@ use super::content::ContentPainterCx;
|
||||
use super::draw::{Dashes, PaintShape, StrokeWidth};
|
||||
use super::rule::{Rule, RuleKind};
|
||||
use super::surface::Surface;
|
||||
use super::textures::{TextureCache, UNTINTED};
|
||||
use crate::style::{Corners, DataColor, RuleLook, SurfaceKind, UiTokens, ink_color, rgba_color, rule_look, surface_style};
|
||||
use craft_behavior::{Axis, CanvasView, kurbo};
|
||||
use egui::{Color32, Mesh, Pos2, Rect, Shape, Stroke, Vec2, pos2, vec2};
|
||||
use egui::epaint::{RectShape, Vertex};
|
||||
use egui::{
|
||||
Color32, ColorImage, Context, CornerRadius, Mesh, Pos2, Rect, Shape, Stroke, TextureFilter, TextureId, TextureOptions, TextureWrapMode, Vec2,
|
||||
pos2, vec2,
|
||||
};
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
/// Which edge of a rect a tick row sits on, and so which way its marks point.
|
||||
@@ -89,35 +94,48 @@ impl Checker {
|
||||
self
|
||||
}
|
||||
|
||||
/// The checkerboard over `rect`, drawn where `clip` shows it: the light colour fills it and the dark cells sit
|
||||
/// on top, from the rect's top-left corner.
|
||||
pub fn shapes(&self, tokens: &UiTokens, rect: Rect, clip: Rect) -> Vec<Shape> {
|
||||
let visible = rect.intersect(clip);
|
||||
if visible.width() <= 0.0 || visible.height() <= 0.0 {
|
||||
return Vec::new();
|
||||
}
|
||||
/// The checkerboard over `area` as one textured shape: square cells of the light and dark colours, a light cell
|
||||
/// with its top-left corner at `origin`. A painter's clip cuts it.
|
||||
pub fn shape(&self, ctx: &Context, tokens: &UiTokens, area: CheckerArea, origin: Pos2) -> Shape {
|
||||
let side = self.size.unwrap_or(tokens.size.checker).max(f32::EPSILON);
|
||||
let light = self.light.map_or_else(|| rgba_color(tokens.color.overlay.checker_light), |color| color.0);
|
||||
let dark = self.dark.map_or_else(|| rgba_color(tokens.color.overlay.checker_dark), |color| color.0);
|
||||
let mut shapes = vec![Shape::rect_filled(visible, 0.0, light)];
|
||||
let cells = |from: f32, to: f32, origin: f32| {
|
||||
let at = |edge: f32, round: fn(f32) -> f32| round((edge - origin) / side).max(0.0) as usize;
|
||||
at(from, f32::floor)..at(to, f32::ceil)
|
||||
};
|
||||
for row in cells(visible.top(), visible.bottom(), rect.top()) {
|
||||
for column in cells(visible.left(), visible.right(), rect.left()).filter(|column| (column + row) % 2 == 0) {
|
||||
let min = rect.min + vec2(column as f32 * side, row as f32 * side);
|
||||
let cell = Rect::from_min_size(min, Vec2::splat(side)).intersect(visible);
|
||||
shapes.push(Shape::rect_filled(cell, 0.0, dark));
|
||||
let texture = checker_texture(ctx, light, dark);
|
||||
// One texel per cell; the texture repeats every two cells.
|
||||
let uv = |p: Pos2| ((p - origin) / (2.0 * side)).to_pos2();
|
||||
match area {
|
||||
CheckerArea::Rect(rect, radius) => {
|
||||
Shape::Rect(RectShape::filled(rect, radius, UNTINTED).with_texture(texture, Rect::from_min_max(uv(rect.min), uv(rect.max))))
|
||||
}
|
||||
CheckerArea::Quad(corners) => {
|
||||
let mut mesh = Mesh::with_texture(texture);
|
||||
mesh.vertices.extend(corners.iter().map(|&pos| Vertex { pos, uv: uv(pos), color: UNTINTED }));
|
||||
mesh.indices.extend([0, 1, 2, 0, 2, 3]);
|
||||
Shape::mesh(mesh)
|
||||
}
|
||||
}
|
||||
shapes
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme's transparency checkerboard over `rect`, drawn where `clip` shows it, with cells of `size.checker`.
|
||||
pub fn checker(tokens: &UiTokens, rect: Rect, clip: Rect) -> Vec<Shape> {
|
||||
Checker::new().shapes(tokens, rect, clip)
|
||||
/// Where a [`Checker`] paints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum CheckerArea {
|
||||
/// A rect with these corners.
|
||||
Rect(Rect, CornerRadius),
|
||||
/// A convex quad, its corners in order around it (a turned document).
|
||||
Quad([Pos2; 4]),
|
||||
}
|
||||
|
||||
/// The 2 x 2 texture of the checkerboard's two colours (light at the top left and bottom right), repeating, sampled
|
||||
/// without blending so each texel stays one sharp cell.
|
||||
fn checker_texture(ctx: &Context, light: Color32, dark: Color32) -> TextureId {
|
||||
let options = TextureOptions {
|
||||
magnification: TextureFilter::Nearest,
|
||||
minification: TextureFilter::Nearest,
|
||||
wrap_mode: TextureWrapMode::Repeat,
|
||||
mipmap_mode: None,
|
||||
};
|
||||
TextureCache::texture_with(ctx, ("craft-ui-checker", light, dark), options, || ColorImage::new([2, 2], vec![light, dark, dark, light]))
|
||||
}
|
||||
|
||||
/// A colour ramp over `rect`: the strip shades from stop to stop along `axis` (`Axis::X` runs left to right, `Axis::Y`
|
||||
@@ -601,9 +619,9 @@ impl ContentPainterCx<'_> {
|
||||
crate::runtime::egui::textures::paint(&self.painter, texture, rect, uv, super::textures::UNTINTED, UiTokens::corner(radius));
|
||||
}
|
||||
|
||||
/// Paints the transparency checkerboard over `rect`.
|
||||
/// Paints the theme's transparency checkerboard over `rect`.
|
||||
pub fn checker(&self, rect: Rect) {
|
||||
self.painter.extend(checker(self.tokens, rect, self.painter.clip_rect()));
|
||||
self.checker_with(&Checker::new(), rect);
|
||||
}
|
||||
|
||||
/// Paints a colour ramp over `rect` along `axis`; see [`ramp`].
|
||||
@@ -636,7 +654,7 @@ impl ContentPainterCx<'_> {
|
||||
|
||||
/// Paints the checkerboard `checker` over `rect`.
|
||||
pub fn checker_with(&self, checker: &Checker, rect: Rect) {
|
||||
self.painter.extend(checker.shapes(self.tokens, rect, self.painter.clip_rect()));
|
||||
self.painter.add(checker.shape(self.painter.ctx(), self.tokens, CheckerArea::Rect(rect, CornerRadius::ZERO), rect.min));
|
||||
}
|
||||
|
||||
/// Paints tick marks on one edge of `rect`.
|
||||
|
||||
@@ -34,7 +34,7 @@ pub use handle::{Handle, HandleShape};
|
||||
pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names};
|
||||
pub use ime_surface::ImeSurface;
|
||||
pub use kit::{
|
||||
Checker, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, checker, dashed, drop_mark, ellipse,
|
||||
Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse,
|
||||
grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks,
|
||||
};
|
||||
pub use reset_mark::ResetMark;
|
||||
|
||||
@@ -69,9 +69,16 @@ impl TextureCache {
|
||||
/// different key. Keys of different types never meet. A component asks again in every frame it paints the
|
||||
/// texture; a texture nobody asks for while the cache is over `CAPACITY` is freed.
|
||||
pub fn texture<K: Hash + 'static>(ctx: &Context, key: K, image: impl FnOnce() -> ColorImage) -> TextureId {
|
||||
Self::texture_with(ctx, key, TextureOptions::LINEAR, image)
|
||||
}
|
||||
|
||||
/// The texture for `key` sampled with `options` (a repeating pattern, nearest filtering); see [`Self::texture`].
|
||||
/// The options are part of the key.
|
||||
pub fn texture_with<K: Hash + 'static>(ctx: &Context, key: K, options: TextureOptions, image: impl FnOnce() -> ColorImage) -> TextureId {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
TypeId::of::<K>().hash(&mut hasher);
|
||||
key.hash(&mut hasher);
|
||||
options.hash(&mut hasher);
|
||||
let hash = hasher.finish();
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let known = memory::with(ctx, |loaded: &mut Loaded| {
|
||||
@@ -84,7 +91,7 @@ impl TextureCache {
|
||||
return id;
|
||||
}
|
||||
// The image is built and uploaded outside the service lock: neither calls back into the cache.
|
||||
let handle = textures::load(ctx, format!("craft_ui/{hash:016x}"), image(), TextureOptions::LINEAR);
|
||||
let handle = textures::load(ctx, format!("craft_ui/{hash:016x}"), image(), options);
|
||||
memory::with(ctx, |loaded: &mut Loaded| {
|
||||
let id = loaded.handles.entry(hash).or_insert(Entry { handle, used: frame }).handle.id();
|
||||
loaded.evict(frame);
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::runtime::requests::ColorRequest;
|
||||
use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style};
|
||||
use craft_behavior::{CursorIcon, CursorPriority, Metrics, Mixed, Sense, Value};
|
||||
use craft_theme::{Rgba, Srgba, Stateful, States, over};
|
||||
use egui::{Color32, CornerRadius, Rect, Response, Shape, Vec2, pos2};
|
||||
use egui::{Color32, CornerRadius, Rect, Response, Vec2, pos2};
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
@@ -247,7 +247,7 @@ impl<T: Value + 'static> Component for Swatch<T> {
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
paint_face(&ui.draw(), &ui.env.tokens, cx.rect, cx.style, cx.state(), self.color);
|
||||
paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), self.color);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> SwatchOutput {
|
||||
@@ -259,7 +259,7 @@ impl<T: Value + 'static> Component for Swatch<T> {
|
||||
|
||||
/// The one swatch face painter: the well of `color` in `well` (a checkerboard behind a translucent colour, the dash
|
||||
/// of a mixed one), then the outline ring and the selection ring, in `state`.
|
||||
fn paint_face(draw: &Draw<'_>, tokens: &UiTokens, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Srgba>) {
|
||||
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Srgba>) {
|
||||
let shape = PaintShape::Rect(well, style.radius);
|
||||
match color.same() {
|
||||
None => {
|
||||
@@ -273,11 +273,7 @@ fn paint_face(draw: &Draw<'_>, tokens: &UiTokens, well: Rect, style: &SwatchStyl
|
||||
}
|
||||
Some(color) => {
|
||||
if color.a < 1.0 {
|
||||
for cell in rounded(Checker::new().shapes(tokens, well, well), well, style.radius) {
|
||||
if let Shape::Rect(cell) = cell {
|
||||
draw.data_fill(&PaintShape::Rect(cell.rect, cell.corner_radius), DataColor::new(cell.fill));
|
||||
}
|
||||
}
|
||||
draw.checker(&Checker::new(), well, style.radius);
|
||||
}
|
||||
draw.data_fill(&shape, DataColor::new(Color32::from(*color)));
|
||||
}
|
||||
@@ -315,22 +311,6 @@ impl SwatchFace {
|
||||
let style = resolve_style(&scope, key, cx.painter.ctx(), Swatch::<()>::style);
|
||||
let (flags, on) = if self.selected { (Flags::SELECTED, 1.0) } else { (Flags::empty(), 0.0) };
|
||||
let state = StateSet::new(State::Rest, flags, StateMix::new(0.0, 0.0, on));
|
||||
cx.with_draw(|draw| paint_face(draw, scope.tokens, rect, &style, &state, self.color));
|
||||
cx.with_draw(|draw| paint_face(draw, rect, &style, &state, self.color));
|
||||
}
|
||||
}
|
||||
|
||||
/// `shapes` of a checkerboard over `well` with the corners of `radius` where a cell meets a corner of the well.
|
||||
fn rounded(mut shapes: Vec<Shape>, well: Rect, radius: CornerRadius) -> Vec<Shape> {
|
||||
for shape in &mut shapes {
|
||||
if let Shape::Rect(cell) = shape {
|
||||
let round = |touches: bool, r: u8| if touches { r } else { 0 };
|
||||
cell.corner_radius = CornerRadius {
|
||||
nw: round(cell.rect.min == well.min, radius.nw),
|
||||
ne: round(cell.rect.right_top() == well.right_top(), radius.ne),
|
||||
sw: round(cell.rect.left_bottom() == well.left_bottom(), radius.sw),
|
||||
se: round(cell.rect.max == well.max, radius.se),
|
||||
};
|
||||
}
|
||||
}
|
||||
shapes
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user