expand primitives in minigfx library

This commit is contained in:
bunnie 2025-02-11 16:23:06 +08:00
parent 79fae48bd8
commit 2a4d91d9be
11 changed files with 1272 additions and 4 deletions

View file

@ -0,0 +1,20 @@
use crate::minigfx::*;
#[derive(Debug, Clone, Copy, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Circle {
pub center: Point,
pub radius: isize,
/// Drawing style
pub style: DrawStyle,
}
impl Circle {
pub fn new(c: Point, r: isize) -> Circle { Circle { center: c, radius: r, style: DrawStyle::default() } }
pub fn new_with_style(c: Point, r: isize, style: DrawStyle) -> Circle {
Circle { center: c, radius: r, style }
}
pub fn translate(&mut self, offset: Point) { self.center = self.center + offset; }
}

View file

@ -0,0 +1,115 @@
// Copyright (c) 2022 Sam Blenny
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
use super::*;
use crate::platform::{LINES, WIDTH};
/// ClipRect specifies a region of pixels. X and y pixel ranges are inclusive of
/// min and exclusive of max (i.e. it's min.x..max.x rather than min.x..=max.x)
/// Coordinate System Notes:
/// - (0,0) is top left
/// - Increasing Y moves downward on the screen, increasing X moves right
#[derive(Copy, Clone, Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct ClipRect {
pub min: Pt,
pub max: Pt,
}
#[allow(dead_code)]
impl ClipRect {
/// Initialize a rectangle using automatic min/max fixup for corner points
pub fn new(min_x: isize, min_y: isize, max_x: isize, max_y: isize) -> ClipRect {
// Make sure min_x <= max_x && min_y <= max_y
let mut min = Pt { x: min_x, y: min_y };
let mut max = Pt { x: max_x, y: max_y };
if min_x > max_x {
min.x = max_x;
max.x = min_x;
}
if min_y > max_y {
min.y = max_y;
max.y = min_y;
}
ClipRect { min, max }
}
pub fn to_rect(&self) -> Rectangle {
Rectangle::new_coords(
self.min.x as isize,
self.min.y as isize,
self.max.x as isize,
self.max.y as isize,
)
}
/// Make a rectangle of the full screen size (0,0)..(WIDTH,LINES)
pub fn full_screen() -> ClipRect { ClipRect::new(0, 0, WIDTH, LINES) }
/// Make a rectangle of the screen size minus padding (6,6)..(WIDTH-6,LINES-6)
pub fn padded_screen() -> ClipRect {
let pad = 6;
ClipRect::new(pad, pad, WIDTH - pad, LINES - pad)
}
pub fn intersects(&self, other: ClipRect) -> bool {
!(self.max.x < other.min.x
|| self.min.y > other.max.y
|| self.max.y < other.min.y
|| self.min.x > other.max.x)
}
pub fn intersects_point(&self, point: Pt) -> bool {
((point.x >= self.min.x) && (point.x <= self.max.x))
&& ((point.y >= self.min.y) && (point.y <= self.max.y))
}
/// takes the current Rectangle, and clips it with a clipping Rectangle; returns a new rectangle as the
/// result
pub fn clip_with(&self, clip: ClipRect) -> Option<ClipRect> {
// check to see if we even overlap; if not, don't do any computation
if !self.intersects(clip) {
return None;
}
let tl: Pt = Pt::new(
if self.min.x < clip.min.x { clip.min.x } else { self.min.x },
if self.min.y < clip.min.y { clip.min.y } else { self.min.y },
);
let br: Pt = Pt::new(
if self.max.x > clip.max.x { clip.max.x } else { self.max.x },
if self.max.y > clip.max.y { clip.max.y } else { self.max.y },
);
Some(ClipRect::new(tl.x, tl.y, br.x, br.y))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cliprect_equivalence() {
let cr1 = ClipRect { min: Pt { x: 1, y: 2 }, max: Pt { x: 8, y: 9 } };
// Called properly:
let cr2 = ClipRect::new(1, 2, 8, 9);
// Called with mixed up corners that should get auto-corrected
let cr3 = ClipRect::new(8, 2, 1, 9);
let cr4 = ClipRect::new(1, 9, 8, 2);
assert_eq!(cr1, cr2);
assert_eq!(cr2, cr3);
assert_eq!(cr3, cr4);
}
#[test]
fn test_cliprect_full_screen() {
let clip = ClipRect::full_screen();
assert_eq!(clip.min, Pt::new(0, 0));
assert_eq!(clip.max, Pt::new(WIDTH, LINES));
}
#[test]
fn test_cliprect_padded_screen() {
let c1 = ClipRect::full_screen();
let c2 = ClipRect::padded_screen();
assert!(c2.min > c1.min);
assert!(c2.max < c1.max);
}
}

View file

@ -0,0 +1,63 @@
// Copyright (c) 2022 Sam Blenny
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
use super::GlyphSprite;
use super::TypesetWord;
use super::cliprect::ClipRect;
use super::pt::Pt;
/// Cursor specifies a drawing position along a line of text. Lines of text can
/// be different heights. Line_height is for keeping track of the tallest
/// character that has been drawn so far on the current line.
#[derive(Copy, Clone, Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Cursor {
pub pt: Pt,
pub line_height: usize,
}
#[allow(dead_code)]
impl Cursor {
// Make a new Cursor. When in doubt, set line_height = 0.
pub fn new(x: isize, y: isize, line_height: usize) -> Cursor { Cursor { pt: Pt { x, y }, line_height } }
// Make a Cursor aligned at the top left corner of a ClipRect
pub fn from_top_left_of(r: ClipRect) -> Cursor { Cursor { pt: r.min, line_height: 0 } }
pub fn update_glyph(&mut self, glyph: &GlyphSprite) {
self.pt.x += glyph.wide as isize;
self.line_height = self.line_height.max(glyph.high as usize);
}
pub(crate) fn update_word(&mut self, word: &TypesetWord) {
self.pt.x += word.width;
self.line_height = self.line_height.max(word.height as usize);
}
pub fn add(&self, other: Cursor) -> Cursor {
Cursor {
pt: Pt::new(self.pt.x + other.pt.x, self.pt.y + other.pt.y),
line_height: self.line_height.max(other.line_height),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cursor_equivalence() {
let c1 = Cursor { pt: Pt { x: 1, y: 2 }, line_height: 0 };
let c2 = Cursor::new(1, 2, 0);
assert_eq!(c1, c2);
let clip = ClipRect::new(1, 2, 3, 4);
let c3 = Cursor::from_top_left_of(clip);
assert_eq!(c1, c3);
}
#[test]
fn test_cursor_from_clip_rect() {
let cr = ClipRect::new(1, 2, 8, 9);
let c = Cursor::from_top_left_of(cr);
assert_eq!(c.pt, cr.min);
}
}

View file

@ -0,0 +1,65 @@
/// Style options for Latin script fonts
#[derive(Copy, Clone, Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum GlyphStyle {
Small = 0,
Regular = 1,
Bold = 2,
Monospace = 3,
Cjk = 4,
Large = 5,
ExtraLarge = 6,
Tall = 7,
}
/// Convert number to style for use with register-based message passing sytems
// [by bunnie for Xous]
impl From<usize> for GlyphStyle {
fn from(gs: usize) -> Self {
match gs {
0 => GlyphStyle::Small,
1 => GlyphStyle::Regular,
2 => GlyphStyle::Bold,
3 => GlyphStyle::Monospace,
4 => GlyphStyle::Cjk,
5 => GlyphStyle::Large,
6 => GlyphStyle::ExtraLarge,
7 => GlyphStyle::Tall,
_ => GlyphStyle::Regular,
}
}
}
/// Convert style to number for use with register-based message passing sytems
// [by bunnie for Xous]
impl From<GlyphStyle> for usize {
fn from(g: GlyphStyle) -> usize {
match g {
GlyphStyle::Small => 0,
GlyphStyle::Regular => 1,
GlyphStyle::Bold => 2,
GlyphStyle::Monospace => 3,
GlyphStyle::Cjk => 4,
GlyphStyle::Large => 5,
GlyphStyle::ExtraLarge => 6,
GlyphStyle::Tall => 7,
}
}
}
/// Estimate line-height for Latin script text in the given style
/// These are hard-coded in because we want to keep the rest of the font data
/// structures private to this crate. Moving the font files out of their
/// current location would also require modifying a bunch of codegen infrastruture,
/// so, this is one spot where we have to manually maintain a link.
pub fn glyph_to_height_hint(g: GlyphStyle) -> usize {
match g {
GlyphStyle::Small => 12, // crate::blitstr2::fonts::small::MAX_HEIGHT as usize,
GlyphStyle::Regular => 15, // crate::blitstr2::fonts::regular::MAX_HEIGHT as usize,
GlyphStyle::Bold => 15, // crate::blitstr2::fonts::regular::MAX_HEIGHT as usize,
GlyphStyle::Monospace => 15, // crate::blitstr2::fonts::mono::MAX_HEIGHT as usize,
GlyphStyle::Cjk => 16, // crate::blistr2::fonts::emoji::MAX_HEIGHT as usize,
GlyphStyle::Large => 24, // 2x of small
GlyphStyle::ExtraLarge => 30, // 2x of regular
GlyphStyle::Tall => 19,
}
}

View file

@ -6,6 +6,19 @@ pub mod rect;
pub use rect::*;
pub mod style;
pub use style::*;
pub mod circle;
pub use circle::*;
pub mod glyphstyle;
pub use glyphstyle::*;
pub mod textview;
pub use textview::*;
pub mod cliprect;
pub use cliprect::*;
pub mod cursor;
pub use cursor::*;
pub mod pt;
pub use pt::*;
pub(crate) mod op;
/// Abstract trait for a FrameBuffer. Slower than native manipulation
/// of the [u8] contents of a frame buffer, but more portable.
@ -21,3 +34,53 @@ pub trait FrameBuffer {
/// Returns the size of the frame buffer as a Point
fn dimensions(&self) -> Point;
}
// Font data is stored as CODEPOINTS and GLYPHS arrays. CODEPOINTS holds sorted
// Unicode codepoints for characters included in the font, and GLYPHS holds
// 16*16px sprites (pixels packed in row-major order, LSB of first word is top
// left pixel of sprite). The order of codepoints and glyphs is the same, but,
// each codepoint is one u32 word long while each glyph is eight u32 words
// long. So, to find a glyph we do:
// 1. Binary search CODEPOINTS for the codepoint of interest
// 2. Multiply the codepoint index by 8, yielding an offset into GLYPHS
// 3. Slice 8 u32 words from GLYPHS starting at the offset
/// Struct to hold sprite pixel reference and associated metadata for glyphs
#[derive(Copy, Clone, Debug)]
pub struct GlyphSprite {
pub glyph: &'static [u32],
pub wide: u8,
pub high: u8,
pub kern: u8,
// the original character
pub ch: char,
// invert rendering for the character - for copy/paste selection regions
pub invert: bool,
// drawn an insertion point after this character
pub insert: bool,
// 2x flag for the back-end rendering (wide/high should be pre-computed to match this)
pub double: bool,
// flag for 32-bit wide glyph sets
pub large: bool,
}
/// A TypesetWord is a Word that has beet turned into sprites and placed at a specific location on the canvas,
/// defined by its `bb` record. The intention is that this abstract representation can be passed directly to
/// a rasterizer for rendering.
#[derive(Debug)]
pub(crate) struct TypesetWord {
/// glyph data to directly render the word
pub gs: Vec<GlyphSprite>,
/// top left origin point for rendering of the glyphs
pub origin: Pt,
/// width of the word
pub width: isize,
/// overall height for the word
pub height: isize,
/// set if this `word` is not drawable, e.g. a newline placeholder.
/// *however* the Vec<GlyphSprite> should still be checked for an insertion point, so that
/// successive newlines properly get their insertion point drawn
pub non_drawable: bool,
/// the position in the originating abstract string of the first character in the word
pub strpos: usize,
}

View file

@ -0,0 +1,643 @@
use super::*;
/// LCD Frame buffer bounds
pub const LCD_WORDS_PER_LINE: usize = crate::platform::WIDTH as usize / core::mem::size_of::<u32>();
pub const LCD_PX_PER_LINE: usize = crate::platform::WIDTH as usize;
pub const LCD_LINES: usize = crate::platform::LINES as usize;
pub const LCD_FRAME_BUF_SIZE: usize = LCD_WORDS_PER_LINE * LCD_LINES;
pub const WIDTH: isize = crate::platform::WIDTH;
pub const HEIGHT: isize = crate::platform::LINES;
/// For passing frame buffer references
pub type LcdFB = [u32; LCD_FRAME_BUF_SIZE];
/// Set the expected rectangle length for the busy animation
pub const BUSY_ANIMATION_RECT_WIDTH: isize = 32; // golden ratio off of a height of 20
fn put_pixel(fb: &mut LcdFB, x: isize, y: isize, color: ColorNative) {
let mut clip_y: usize = y as usize;
if clip_y >= LCD_LINES {
clip_y = LCD_LINES - 1;
}
let clip_x: usize = x as usize;
if clip_x >= LCD_PX_PER_LINE {
clip_y = LCD_PX_PER_LINE - 1;
}
let pc = PixelColor::from(color.0);
if pc == PixelColor::Light {
fb[(clip_x + clip_y * LCD_WORDS_PER_LINE * 32) / 32] |= 1 << (clip_x % 32)
} else {
fb[(clip_x + clip_y * LCD_WORDS_PER_LINE * 32) / 32] &= !(1 << (clip_x % 32))
}
// set the dirty bit on the line that contains the pixel
fb[clip_y * LCD_WORDS_PER_LINE + (LCD_WORDS_PER_LINE - 1)] |= 0x1_0000;
}
fn xor_pixel(fb: &mut LcdFB, x: isize, y: isize) {
let mut clip_y: usize = y as usize;
if clip_y >= LCD_LINES {
clip_y = LCD_LINES - 1;
}
let clip_x: usize = x as usize;
if clip_x >= LCD_PX_PER_LINE {
clip_y = LCD_PX_PER_LINE - 1;
}
fb[(clip_x + clip_y * LCD_WORDS_PER_LINE * 32) / 32] ^= 1 << (clip_x % 32);
// set the dirty bit on the line that contains the pixel
fb[clip_y * LCD_WORDS_PER_LINE + (LCD_WORDS_PER_LINE - 1)] |= 0x1_0000;
}
pub fn line(fb: &mut LcdFB, l: Line, clip: Option<Rectangle>, xor: bool) {
let color: ColorNative;
if l.style.stroke_color.is_some() {
color = l.style.stroke_color.unwrap();
} else {
return;
}
let mut x0 = l.start.x;
let mut y0 = l.start.y;
let x1 = l.end.x;
let y1 = l.end.y;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -((y1 - y0).abs());
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy; /* error value e_xy */
loop {
/* loop */
if x0 >= 0 && y0 >= 0 && x0 < (WIDTH as _) && y0 < (HEIGHT as _) {
if clip.is_none() || (clip.unwrap().intersects_point(Point::new(x0, y0))) {
if !xor {
put_pixel(fb, x0 as _, y0 as _, color);
} else {
xor_pixel(fb, x0 as _, y0 as _);
}
}
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
/* e_xy+e_x > 0 */
err += dy;
x0 += sx;
}
if e2 <= dx {
/* e_xy+e_y < 0 */
err += dx;
y0 += sy;
}
}
}
/// Pixel iterator for each pixel in the circle border
/// lifted from embedded-graphics crate
#[derive(Debug, Copy, Clone)]
pub struct CircleIterator {
center: Point,
radius: u16,
style: DrawStyle,
p: Point,
clip: Option<Rectangle>,
}
impl Iterator for CircleIterator {
type Item = Pixel;
// https://stackoverflow.com/questions/1201200/fast-algorithm-for-drawing-filled-circles
fn next(&mut self) -> Option<Self::Item> {
// If border or stroke colour is `None`, treat entire object as transparent and exit early
if self.style.stroke_color.is_none() && self.style.fill_color.is_none() {
return None;
}
let radius = self.radius as isize - self.style.stroke_width + 1;
let outer_radius = self.radius as isize;
let radius_sq = radius * radius;
let outer_radius_sq = outer_radius * outer_radius;
loop {
let mut item = None;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p + self.center))
{
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let is_border = len > (radius_sq - radius) && len < (outer_radius_sq + radius);
let is_fill = len <= outer_radius_sq + 1;
item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(self.center + t, self.style.stroke_color.expect("Border color not defined")))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(self.center + t, self.style.fill_color.expect("Fill color not defined")))
} else {
None
};
}
self.p.x += 1;
if self.p.x > self.radius as isize {
self.p.x = -(self.radius as isize);
self.p.y += 1;
}
if self.p.y > self.radius as isize {
break None;
}
if item.is_some() {
break item;
}
}
}
}
pub fn circle(fb: &mut LcdFB, circle: Circle, clip: Option<Rectangle>) {
let radius = circle.radius.abs() as u16;
let c = CircleIterator {
center: circle.center,
radius,
style: circle.style,
p: Point::new(-(radius as isize), -(radius as isize)),
clip,
};
for pixel in c {
put_pixel(fb, pixel.0.x, pixel.0.y, pixel.1);
}
}
/// Pixel iterator for each pixel in the rect border
/// lifted from embedded-graphics crate
#[derive(Debug, Clone, Copy)]
pub struct RectangleIterator {
top_left: Point,
bottom_right: Point,
style: DrawStyle,
p: Point,
clip: Option<Rectangle>,
}
impl Iterator for RectangleIterator {
type Item = Pixel;
fn next(&mut self) -> Option<Self::Item> {
// Don't render anything if the rectangle has no border or fill color.
if self.style.stroke_color.is_none() && self.style.fill_color.is_none() {
return None;
}
loop {
let mut out = None;
// Finished, i.e. we're below the rect
if self.p.y > self.bottom_right.y {
break None;
}
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p))
{
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(self.p, self.style.stroke_color.expect("Expected stroke")));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
}
}
self.p.x += 1;
// Reached end of row? Jump down one line
if self.p.x > self.bottom_right.x {
self.p.x = self.top_left.x;
self.p.y += 1;
}
if out.is_some() {
break out;
}
}
}
}
pub fn rectangle(fb: &mut LcdFB, rect: Rectangle, clip: Option<Rectangle>, xor: bool) {
let r =
RectangleIterator { top_left: rect.tl, bottom_right: rect.br, style: rect.style, p: rect.tl, clip };
for pixel in r {
if !xor {
put_pixel(fb, pixel.0.x, pixel.0.y, pixel.1);
} else {
if rect.width() <= BUSY_ANIMATION_RECT_WIDTH as u32 {
// only allow xor of a rectangle if it is within the expected width for the busy animation
// This is to make it annoying for someone using an XOR rectangle to synthesize inverted
// text on an otherwise untrusted dialog box (I suspect it's not impossible, but introduces
// a likelihood of drawing artifacts especially across translations and font size selections).
if pixel.0.y % 25 != 5 {
xor_pixel(fb, pixel.0.x, pixel.0.y);
} else {
// don't allow XOR on some pixels to avoid this being used as a primitive to synthesize
// secure boxes
}
} else {
log::warn!("invalid xor rect width");
put_pixel(fb, pixel.0.x, pixel.0.y, pixel.1);
}
}
}
}
/////////////////////////////////////////////////// rounded rectangle
#[derive(Debug, Clone, Copy)]
pub enum Quadrant {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
#[derive(Debug, Copy, Clone)]
pub struct QuadrantIterator {
center: Point,
radius: u16,
style: DrawStyle,
p: Point,
quad: Quadrant,
clip: Option<Rectangle>,
}
impl Iterator for QuadrantIterator {
type Item = Pixel;
// https://stackoverflow.com/questions/1201200/fast-algorithm-for-drawing-filled-circles
fn next(&mut self) -> Option<Self::Item> {
// If border and stroke colour is `None`, treat entire object as transparent and exit early
if self.style.stroke_color.is_none() && self.style.fill_color.is_none() {
return None;
}
let inner_radius = self.radius as isize - self.style.stroke_width + 1;
let outer_radius = self.radius as isize;
let inner_radius_sq = inner_radius * inner_radius;
let outer_radius_sq = outer_radius * outer_radius;
//log::info!("GFX|OP: quaditerator {}, {:?}, {:?}, {:?}, {:?}, {:?}", self.radius, self.center,
// self.p, self.quad, self.clip, self.style);
loop {
let mut item = None;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p + self.center))
{
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let is_border =
len > (inner_radius_sq - inner_radius) && len < (outer_radius_sq + inner_radius);
let is_fill = len <= outer_radius_sq + 1;
item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(self.center + t, self.style.stroke_color.expect("Border color not defined")))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(self.center + t, self.style.fill_color.expect("Fill color not defined")))
} else {
None
};
}
self.p.x += 1;
match self.quad {
Quadrant::TopLeft => {
if self.p.x > 0 as isize {
self.p.x = -(self.radius as isize);
self.p.y += 1;
}
if self.p.y > 1 as isize {
break None;
}
if item.is_some() {
break item;
}
}
Quadrant::TopRight => {
if self.p.x > self.radius as isize {
self.p.x = 0;
self.p.y += 1;
}
if self.p.y > 1 as isize {
break None;
}
if item.is_some() {
break item;
}
}
Quadrant::BottomLeft => {
if self.p.x > 0 as isize {
self.p.x = -(self.radius as isize);
self.p.y += 1;
}
if self.p.y > self.radius as isize {
break item;
}
if item.is_some() {
break item;
}
}
Quadrant::BottomRight => {
if self.p.x > self.radius as isize {
self.p.x = 0;
self.p.y += 1;
}
if self.p.y > self.radius as isize {
break item;
}
if item.is_some() {
break item;
}
}
}
}
}
}
pub fn quadrant(fb: &mut LcdFB, circle: Circle, quad: Quadrant, clip: Option<Rectangle>) {
let starting_pixel = match quad {
Quadrant::TopLeft => Point::new(-(circle.radius as isize), -(circle.radius as isize)),
Quadrant::TopRight => Point::new(0, -(circle.radius as isize)),
Quadrant::BottomLeft => Point::new(-(circle.radius as isize), 0),
Quadrant::BottomRight => Point::new(0, 0),
};
let q = QuadrantIterator {
center: circle.center,
radius: circle.radius as _,
style: circle.style,
p: starting_pixel,
quad,
clip,
};
for pixel in q {
put_pixel(fb, pixel.0.x, pixel.0.y, pixel.1);
}
}
/// Pixel iterator for each pixel in the rect border
/// lifted from embedded-graphics crate
#[derive(Debug, Clone, Copy)]
pub struct RoundedRectangleIterator {
top_left: Point,
bottom_right: Point,
style: DrawStyle,
p: Point,
clip: Option<Rectangle>,
// the four quadrants for drawing the rounded corners
tlq: Rectangle,
trq: Rectangle,
blq: Rectangle,
brq: Rectangle,
}
impl Iterator for RoundedRectangleIterator {
type Item = Pixel;
fn next(&mut self) -> Option<Self::Item> {
// Don't render anything if the rectangle has no border or fill color.
if self.style.stroke_color.is_none() && self.style.fill_color.is_none() {
return None;
}
loop {
let mut out = None;
// Finished, i.e. we're below the rect
if self.p.y > self.bottom_right.y {
break None;
}
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p))
{
// suppress the output pixel if we happen to be in the corner quadrant area
if self.tlq.intersects_point(self.p)
|| self.trq.intersects_point(self.p)
|| self.blq.intersects_point(self.p)
|| self.brq.intersects_point(self.p)
{
out = None
} else {
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(self.p, self.style.stroke_color.expect("Expected stroke")));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
}
}
}
self.p.x += 1;
// Reached end of row? Jump down one line
if self.p.x > self.bottom_right.x {
self.p.x = self.top_left.x;
self.p.y += 1;
}
if out.is_some() {
break out;
}
}
}
}
pub fn rounded_rectangle(fb: &mut LcdFB, rr: RoundedRectangle, clip: Option<Rectangle>) {
// compute the four quadrants
// call the rr iterator on the rectangle
// then call it on one each of the four circle quadrants
//log::info!("GFX|OP: rr: {:?}, clip: {:?}", rr, clip);
let rri = RoundedRectangleIterator {
top_left: rr.border.tl,
bottom_right: rr.border.br,
style: rr.border.style,
p: rr.border.tl,
clip,
tlq: Rectangle::new(rr.border.tl, Point::new(rr.border.tl.x + rr.radius, rr.border.tl.y + rr.radius)),
trq: Rectangle::new(
Point::new(rr.border.br.x - rr.radius, rr.border.tl.y),
Point::new(rr.border.br.x, rr.border.tl.y + rr.radius),
),
blq: Rectangle::new(
Point::new(rr.border.tl.x, rr.border.br.y - rr.radius),
Point::new(rr.border.tl.x + rr.radius, rr.border.br.y),
),
brq: Rectangle::new(Point::new(rr.border.br.x - rr.radius, rr.border.br.y - rr.radius), rr.border.br),
};
// draw the body
for pixel in rri {
put_pixel(fb, pixel.0.x, pixel.0.y, pixel.1);
}
//log::info!("GFX|OP: topleft {:?}, {:?}, {:?}, {:?}", rri.tlq.br, rr.radius, rr.border.style, clip);
// now draw the corners
quadrant(fb, Circle::new_with_style(rri.tlq.br, rr.radius, rr.border.style), Quadrant::TopLeft, clip);
quadrant(
fb,
Circle::new_with_style(Point::new(rri.trq.tl.x, rri.trq.br.y), rr.radius, rr.border.style),
Quadrant::TopRight,
clip,
);
quadrant(
fb,
Circle::new_with_style(Point::new(rri.blq.br.x, rri.blq.tl.y), rr.radius, rr.border.style),
Quadrant::BottomLeft,
clip,
);
quadrant(fb, Circle::new_with_style(rri.brq.tl, rr.radius, rr.border.style), Quadrant::BottomRight, clip);
}
/*
* Each line of the LCD Frame Buffer and the Tile is represented by a whole
* number of u32 words, packed with bits, from the left. The right most word
* may have unused bits on the right. The right-most bit in the frame-buffer
* is used as a dirty-line bit flag.
*
* A brute force approach would copy each pixel one-by-one from Tile to fb.
*
* We can do better by copying a word at a time, but there are a few challenges
* In general (unfortunately) a line of Words in the Tile is not aligned with
* the Words in the Frame Buffer. And, even if it were, the right side of the
* Tile will not generally align with a Word boundry.
*
* So the approach for each line is to:
* - start with the first word in the fb impacted by the tile
* - take the left-part of the fb Word and shift the tile Word into the right-part
* - replace the next fb Words with the aligned parts of adjacent parts from the tile Words
* - align the last tile Word, clip it and join with the right-most fb word beyond the clip
* - finally set the dirty-line bit flag on the right most fb Word.
*
* author: nworbnhoj
*/
#[cfg(feature = "ditherpunk")]
use crate::api::Tile;
#[cfg(feature = "ditherpunk")]
pub fn tile(fb: &mut LcdFB, tile: Tile, clip: Option<Rectangle>) {
use std::cmp::{max, min};
let fb_size: Point = Point::new((LCD_PX_PER_LINE - 1) as isize, (LCD_LINES - 1) as isize);
const FB_WORDS_PER_LINE: usize = LCD_WORDS_PER_LINE;
let clip = match clip {
// alter clip to work around an odd use (bug?) of the clip origin
// clip.tl appears to relate to the the usable screen area as origin
// clip.br appears to relate to the clip.tl as origin
Some(clip) => Rectangle::new(Point::new(0, 0), clip.br),
// default to the LcdFB dimensions
None => Rectangle::new(Point::new(0, 0), fb_size),
};
// determine the sub-region of the tile to transfer to the fb (in Tile coords)
let (tl_x, tl_y, br_x, br_y): (usize, usize, usize, usize) = (
max(tile.bound().tl.x, clip.tl.x) as usize,
max(tile.bound().tl.y, clip.tl.y) as usize,
min(tile.bound().br.x, clip.br.x) as usize,
min(tile.bound().br.y, clip.br.y) as usize,
);
// prepare to cut and mask misaligned words
let r_cut = tl_x % 32;
let l_cut = 32 - r_cut;
let mask = (1 << r_cut) - 1;
// prepare to clip a word spanning br_x
let c_clip = br_x % 32;
let c_mask = (1 << c_clip) - 1;
let first_wd = tl_x / 32;
let clip_wd = br_x / 32;
let last_wd = min(clip_wd, FB_WORDS_PER_LINE - 1);
for tile_ln in tl_y..=br_y {
let fb_ln = tile_ln * FB_WORDS_PER_LINE;
let tile_line = tile.get_line(Point::new(tl_x as isize, tile_ln as isize));
let mut fb_wd = first_wd;
let mut tile_wd = 0;
let mut fb_word = fb[fb_ln + fb_wd];
let mut left_part = fb_word & mask;
let mut right_part;
let mut tile_word: u32;
while (fb_wd <= last_wd) & (tile_wd < tile_line.len()) {
fb_word = fb[fb_ln + fb_wd];
tile_word = tile_line[tile_wd];
fb[fb_ln + fb_wd] = match r_cut {
0 => tile_word,
_ => {
// create an aligned word from parts of adjacent tile words
right_part = tile_word << r_cut;
let word = left_part | right_part;
left_part = tile_word >> l_cut;
word
}
};
fb_wd += 1;
tile_wd += 1;
}
// complete the right side of the tile
if fb_wd > last_wd {
// encountered clip before end of tile
left_part = fb[fb_ln + fb_wd - 1] & c_mask;
right_part = fb_word & !c_mask;
fb[fb_ln + fb_wd - 1] = left_part | right_part;
} else {
// encountered end of tile before clip
left_part = left_part & c_mask;
right_part = fb[fb_ln + fb_wd] & !c_mask;
fb[fb_ln + fb_wd] = left_part | right_part;
}
// set the dirty bit on the line
fb[fb_ln + (FB_WORDS_PER_LINE - 1)] |= 0x1_0000;
}
}

View file

@ -1,6 +1,6 @@
use core::ops::{Add, AddAssign, Div, DivAssign, Index, Mul, MulAssign, Neg, Sub, SubAssign};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Point {
pub x: isize,
pub y: isize,

View file

@ -0,0 +1,36 @@
// Copyright (c) 2022 Sam Blenny
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
/// Point specifies a pixel coordinate
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Pt {
pub x: isize,
pub y: isize,
}
impl Pt {
/// Make a new point
pub fn new(x: isize, y: isize) -> Pt { Pt { x, y } }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pt_equivalence() {
let p1 = Pt { x: 1, y: 2 };
let p2 = Pt::new(1, 2);
assert_eq!(p1, p2);
}
#[test]
fn test_pt_ordering() {
let p1 = Pt { x: 1, y: 2 };
let p2 = Pt::new(1, 3);
let p3 = Pt::new(0, 0);
assert!(p1 < p2);
assert!(p1 > p3);
}
}

View file

@ -2,7 +2,7 @@ use core::cmp::{max, min};
use crate::minigfx::*;
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Rectangle {
pub tl: Point,
pub br: Point,
@ -191,3 +191,25 @@ impl Rectangle {
self.br.y += margin.y;
}
}
//////////////////////// Rounded Rectangle
#[derive(Debug, Clone, Copy, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct RoundedRectangle {
pub border: Rectangle, // drawstyle is inherited from the Rectangle
pub radius: isize,
}
impl RoundedRectangle {
pub fn new(rr: Rectangle, r: isize) -> RoundedRectangle {
let mut r_adj = r;
// disallow radii that are greater than 2x the width of the rectangle
if r > (rr.br.x - rr.tl.x) {
r_adj = 0;
}
if r > (rr.br.y - rr.tl.y) {
r_adj = 0;
}
RoundedRectangle { border: rr, radius: r_adj }
}
pub fn translate(&mut self, offset: Point) { self.border.translate(offset); }
}

View file

@ -1,5 +1,7 @@
use crate::minigfx::Point;
/// Type wrapper for native colors
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct ColorNative(pub usize);
impl From<usize> for ColorNative {
fn from(value: usize) -> Self { Self { 0: value } }
@ -9,7 +11,7 @@ impl Into<usize> for ColorNative {
}
/// Style properties for an object
#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct DrawStyle {
/// Fill colour of the object
pub fill_color: Option<ColorNative>,
@ -37,3 +39,29 @@ impl Default for DrawStyle {
Self { fill_color: Some(ColorNative(0)), stroke_color: Some(ColorNative(0)), stroke_width: 1 }
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum PixelColor {
Dark,
Light,
}
impl From<bool> for PixelColor {
fn from(pc: bool) -> Self { if pc { PixelColor::Dark } else { PixelColor::Light } }
}
impl From<PixelColor> for bool {
fn from(pc: PixelColor) -> bool { if pc == PixelColor::Dark { true } else { false } }
}
impl From<usize> for PixelColor {
fn from(pc: usize) -> Self { if pc == 0 { PixelColor::Light } else { PixelColor::Dark } }
}
impl From<PixelColor> for usize {
fn from(pc: PixelColor) -> usize { if pc == PixelColor::Light { 0 } else { 1 } }
}
/// A single pixel
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Pixel(pub Point, pub ColorNative);

View file

@ -0,0 +1,213 @@
use core::ops::Add;
use String;
use super::*;
/// coordinates are local to the canvas, not absolute to the screen
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum TextBounds {
// fixed width and height in a rectangle
BoundingBox(Rectangle),
// fixed width, grows up from bottom right
GrowableFromBr(Point, u16),
// fixed width, grows down from top left
GrowableFromTl(Point, u16),
// fixed width, grows up from bottom left
GrowableFromBl(Point, u16),
// fixed width, grows down from top right
GrowableFromTr(Point, u16),
// fixed width, centered aligned top
CenteredTop(Rectangle),
// fixed width, centered aligned bottom
CenteredBot(Rectangle),
}
impl TextBounds {
pub fn translate(&self, by: Point) -> TextBounds {
match *self {
TextBounds::BoundingBox(mut r) => {
r.translate(by);
TextBounds::BoundingBox(r)
}
TextBounds::GrowableFromBr(origin, width) => TextBounds::GrowableFromBr(origin.add(by), width),
TextBounds::GrowableFromTl(origin, width) => TextBounds::GrowableFromTl(origin.add(by), width),
TextBounds::GrowableFromBl(origin, width) => TextBounds::GrowableFromBl(origin.add(by), width),
TextBounds::GrowableFromTr(origin, width) => TextBounds::GrowableFromTr(origin.add(by), width),
TextBounds::CenteredTop(mut r) => {
r.translate(by);
TextBounds::BoundingBox(r)
}
TextBounds::CenteredBot(mut r) => {
r.translate(by);
TextBounds::BoundingBox(r)
}
}
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, PartialEq)]
// operations that may be requested of a TextView when sent to GAM
pub enum TextOp {
Nop,
Render,
ComputeBounds, // maybe we don't need this
}
impl From<TextOp> for usize {
fn from(op: TextOp) -> usize {
match op {
TextOp::Nop => 0,
TextOp::Render => 1,
TextOp::ComputeBounds => 2,
}
}
}
impl From<usize> for TextOp {
fn from(code: usize) -> Self {
match code {
1 => TextOp::Render,
2 => TextOp::ComputeBounds,
_ => TextOp::Nop,
}
}
}
// roughly 168 bytes to represent the rest of the struct, and we want to fill out the 4096 byte page with text
pub const TEXTVIEW_LEN: usize = 3072;
pub const TEXTVIEW_DEFAULT_STYLE: GlyphStyle = GlyphStyle::Regular;
#[derive(Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct TextView {
// this is the operation as specified for the GAM. Note this is different from the "op" when sent to
// graphics-server only the GAM should be sending TextViews to the graphics-server, and a different
// coding scheme is used for that link.
operation: TextOp,
pub clip_rect: Option<Rectangle>, /* this is set by the GAM to the canvas' clip_rect; needed by gfx
* for drawing. Note this is in screen coordinates. */
pub untrusted: bool, // render content with random stipples to indicate the strings within are untrusted
pub token: Option<[u32; 4]>, // optional 128-bit token which is presented to prove a field's trustability
pub invert: bool, // only trusted, token-validated TextViews will have the invert bit respected
// offsets for text drawing -- exactly one of the following options should be specified
// note that the TextBounds coordinate system is local to the canvas, not the screen
pub bounds_hint: TextBounds,
pub bounds_computed: Option<Rectangle>, /* is Some(Rectangle) if bounds have been computed and text
* has not been modified. This is local to the canvas. */
pub overflow: Option<bool>, /* indicates if the text has overflowed the canvas, set by the drawing
* routine */
dry_run: bool, /* callers should not set; use TexOp to select. gam-side bookkeepping, set to true if
* no drawing is desired and we just want to compute the bounds */
pub style: GlyphStyle,
pub cursor: Cursor,
pub insertion: Option<i32>, // this is the insertion point offset, if it's to be drawn, on the string
pub ellipsis: bool,
pub draw_border: bool,
pub clear_area: bool, // you almost always want this to be true
pub border_width: u16,
pub rounded_border: Option<u16>, // radius of the rounded border, if applicable
pub margin: Point,
// this field specifies the beginning and end of a "selected" region of text
pub selected: Option<[u32; 2]>,
// this field tracks the state of a busy animation, if `Some`
pub busy_animation_state: Option<u32>,
pub text: String,
}
impl TextView {
pub fn new(bounds_hint: TextBounds) -> Self {
TextView {
operation: TextOp::Nop,
untrusted: true,
token: None,
invert: false,
clip_rect: None,
bounds_hint,
bounds_computed: None,
style: TEXTVIEW_DEFAULT_STYLE,
text: String::new(),
cursor: Cursor::new(0, 0, 0),
insertion: None,
ellipsis: false,
draw_border: true,
border_width: 1,
rounded_border: None,
margin: Point { x: 4, y: 4 },
selected: None,
clear_area: true,
overflow: None,
dry_run: false,
busy_animation_state: None,
}
}
pub fn dry_run(&self) -> bool { self.dry_run }
pub fn set_dry_run(&mut self, dry_run: bool) { self.dry_run = dry_run; }
pub fn set_op(&mut self, op: TextOp) { self.operation = op; }
pub fn get_op(&self) -> TextOp { self.operation }
pub fn to_str(&self) -> &str { self.text.as_str() }
pub fn clear_str(&mut self) { self.text.clear() }
pub fn populate_from(&mut self, t: &TextView) {
self.operation = t.operation;
self.untrusted = t.untrusted;
self.token = t.token;
self.invert = t.invert;
self.bounds_hint = t.bounds_hint;
self.bounds_computed = t.bounds_computed;
self.style = t.style;
self.text = t.text.clone();
self.cursor = t.cursor;
self.draw_border = t.draw_border;
self.clear_area = t.clear_area;
self.border_width = t.border_width;
self.rounded_border = t.rounded_border;
self.margin = t.margin;
self.selected = t.selected;
self.overflow = t.overflow;
self.clip_rect = t.clip_rect;
self.dry_run = t.dry_run;
self.insertion = t.insertion;
}
}
// Allow a `&TextView` to be used anywhere that expects a `&str`
impl AsRef<str> for TextView {
fn as_ref(&self) -> &str { self.to_str() }
}
impl core::fmt::Debug for TextView {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
// this should definitely be extended to print more relevant data, but for now just render the string
// itself
write!(
f,
"{:?}, {:?}, {:?}, dry_run: {:?}, {}",
self.get_op(),
self.bounds_hint,
self.cursor,
self.dry_run,
self.to_str()
)
}
}
// allow printing of the text
impl core::fmt::Display for TextView {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) }
}
// allow `write!()` macro on a` &TextView`
impl core::fmt::Write for TextView {
fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> {
write!(self.text, "{}", s)
}
}