Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/ab_glyph/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "rsdf_ab_glyph"
version = "0.0.0"
edition = "2021"
license = "Apache-2.0"

[dependencies]
ab_glyph = "0.2.23"
rsdf_builder = { path = "../builder" }
rsdf_core = { path = "../core" }
Binary file added crates/ab_glyph/ab_glyph_example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added crates/ab_glyph/ab_glyph_example_reference.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added crates/ab_glyph/ab_glyph_example_render.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
174 changes: 174 additions & 0 deletions crates/ab_glyph/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
//! Provides an extension trait for `ab_glyph`'s `Font` types.

use ::ab_glyph::{
point, Font, Glyph, Outline, OutlineCurve, Point, PxScaleFactor, Rect,
ScaleFont,
};

pub struct RsdfGlyph {
glyph: Glyph,
px_bounds: Rect,
scale_factor: PxScaleFactor,
outline: Outline,
}

impl RsdfGlyph {
/// Construct an `RsdfGlyph` from the source `Glyph`, pixel bounds &
/// relatively positioned outline curves.
pub fn new(
glyph: Glyph,
outline: Outline,
scale_factor: PxScaleFactor,
) -> Self {
let px_bounds = outline.px_bounds(scale_factor, glyph.position);

RsdfGlyph {
glyph,
px_bounds,
scale_factor,
outline,
}
}

/// Glyph info.
pub fn glyph(&self) -> &Glyph {
&self.glyph
}

/// Conservative whole number pixel boundeing box for this glyph.
pub fn px_bounds(&self) -> Rect {
self.px_bounds
}

/// Draw this glyph outline using a pixel & field handling function.
///
/// The callback will be called for each `(x, y)` pixel coordinate inside the
/// bounds with a field value indicating the colour channel values
/// corresponding to that pixel.
///
// TODO: Each channel value ranges between `-1.0` and `1.0`.
pub fn draw<O: FnMut(u32, u32, [u8; 3])>(&self, mut output: O) {
let h_factor = self.scale_factor.horizontal;
let v_factor = -self.scale_factor.vertical;
let offset = self.glyph.position - self.px_bounds.min;
let (w, h) = (
self.px_bounds.width() as usize,
self.px_bounds.height() as usize,
);
let scale_up = |Point { x, y }| point(x * h_factor, y * v_factor);
let get_first = |curve: &OutlineCurve| match curve {
OutlineCurve::Line(p, _) => *p,
OutlineCurve::Quad(p, _, _) => *p,
OutlineCurve::Cubic(p, _, _, _) => *p,
};
let get_last = |curve: &OutlineCurve| match curve {
OutlineCurve::Line(_, p) => *p,
OutlineCurve::Quad(_, _, p) => *p,
OutlineCurve::Cubic(_, _, _, p) => *p,
};

let mut rasterizer = Some(rsdf_builder::ShapeBuilder::new());
let mut curves = self.outline.curves.iter().cloned().peekable();

if curves.len() > 0 {
let c = curves.peek().unwrap();
let mut first = get_first(c);
let mut contour_builder = None;

for curve in curves {
if contour_builder.is_none() {
first = get_first(&curve);
contour_builder = Some(
rasterizer
.take()
.unwrap()
.contour(point_from_point(scale_up(first) + offset)),
);
}
match curve {
OutlineCurve::Line(_, p1) => {
contour_builder = Some(
contour_builder
.unwrap()
.line(point_from_point(scale_up(p1) + offset)),
);
},
OutlineCurve::Quad(_, p1, p2) => {
contour_builder = Some(contour_builder.unwrap().quadratic_bezier(
point_from_point(scale_up(p1) + offset),
point_from_point(scale_up(p2) + offset),
));
},
OutlineCurve::Cubic(_, p1, p2, p3) => {
contour_builder = Some(contour_builder.unwrap().cubic_bezier(
point_from_point(scale_up(p1) + offset),
point_from_point(scale_up(p2) + offset),
point_from_point(scale_up(p3) + offset),
));
},
}
if first == get_last(&curve) {
rasterizer = Some(contour_builder.take().unwrap().end_contour());
}
}
}

const MARGIN: usize = 5;

let rasterizer = rasterizer
.expect("contour must not have terminated")
.build();
for x in 0..(w + MARGIN * 2) {
for y in 0..(h + MARGIN * 2) {
let sample = rasterizer
.sample((x as f32 - MARGIN as f32, y as f32 - MARGIN as f32).into());
let mut color @ [r, g, b] = sample.map(|sp| {
let sp = -sp; // depends on chirality of font :(
rsdf_core::distance_color(sp)
});
// clip remaining values when bulk is 0
let sum = r as u16 + g as u16 + b as u16;
if r as u16 == sum || g as u16 == sum || b as u16 == sum {
color = [0; 3];
}
// clip when bulk is saturated
if r == 255 && b == 255 || r == 255 && g == 255 || b == 255 && g == 255
{
color = [255; 3];
}

output(x as _, y as _, color)
}
}
}
}

// TODO:
// - add max_dist to sample function
// - clip to bulk in sample function
// - return normalised values, between [0, 1] or [-1, 1]
// probably the second, as it emphasizes the "signed"-ness of sdfs
// - output of ab_glyph draw function should be those normalised values

pub trait FontExtRsdf {
fn outline_glyph_rsdf(&self, glyph: Glyph) -> Option<RsdfGlyph>;
}

impl<F> FontExtRsdf for F
where
F: Font,
{
fn outline_glyph_rsdf(&self, glyph: Glyph) -> Option<RsdfGlyph> {
let outline = self.outline(glyph.id)?;
let scale_factor = self.as_scaled(glyph.scale).scale_factor();
Some(RsdfGlyph::new(glyph, outline, scale_factor))
}
}

#[inline]
fn point_from_point(value: Point) -> rsdf_core::Point {
rsdf_core::Point {
x: value.x,
y: value.y,
}
}
64 changes: 64 additions & 0 deletions crates/ab_glyph/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use ::ab_glyph::{Font, FontRef, Glyph};
use ::rsdf_ab_glyph::FontExtRsdf;
use ::rsdf_core::Image;

fn main() {
let font =
FontRef::try_from_slice(include_bytes!("../../../fonts/Noto/NotoSerifJP-Regular.otf"))
.unwrap();

let glyph: Glyph = font.glyph_id('及').with_scale(96.0);

if let Some(q) = font.outline_glyph(glyph.clone()) {
let bounds = q.px_bounds();

let mut image = Image::new(
"ab_glyph_example_reference.png",
[bounds.width() as usize + 10, bounds.height() as usize + 10],
);

q.draw(|x, y, coverage| {
image.set_pixel(
[x as usize + 5, y as usize + 5],
[(coverage * 255.0) as _; 3],
)
});

image.flush()
}

if let Some(q) = font.outline_glyph_rsdf(glyph) {
let bounds = q.px_bounds();

let mut image = Image::new(
"ab_glyph_example.png",
[bounds.width() as usize + 10, bounds.height() as usize + 10],
);
let mut image_render = Image::new(
"ab_glyph_example_render.png",
[bounds.width() as usize + 10, bounds.height() as usize + 10],
);

q.draw(|x, y, field| {
image.set_pixel([x as usize, y as usize], field);

// find the median value
let median = |a, b, c| {
if (a <= b && b <= c) || (c <= b && b <= a) {
b
} else if (a <= c && c <= b) || (b <= c && c <= a) {
c
} else {
a
}
};
let value = median(field[0], field[1], field[2]);
if value > 127 {
image_render.set_pixel([x as usize, y as usize], [255; 3]);
}
});

image.flush();
image_render.flush();
}
}
2 changes: 2 additions & 0 deletions crates/builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use rsdf_core::*;

#[derive(Debug)]
pub struct ShapeBuilder {
shape: Shape,
}
Expand All @@ -27,6 +28,7 @@ impl ShapeBuilder {
}
}

#[derive(Debug)]
pub struct ContourBuilder {
shape: Shape,
current_spline: Spline,
Expand Down
1 change: 0 additions & 1 deletion crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ mod math;
mod shape;

use math::*;
use shape::*;

pub use image::Image;
pub use math::{Point, Vector};
Expand Down
1 change: 1 addition & 0 deletions crates/core/src/shape/sample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ impl Shape {
}

/// Comparison function for pairs of distances
#[inline]
fn closer(
(distance_a, orthogonality_a): Dist,
(distance_b, orthogonality_b): Dist,
Expand Down
Binary file added fonts/Noto/NotoSerifJP-Regular.otf
Binary file not shown.
93 changes: 93 additions & 0 deletions fonts/Noto/OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2012 Google Inc. All Rights Reserved.

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.