dymokomi/luce-fonts
Source of release 0.7.2
0.7.2 / src / opentype / glyf.lucb
#==============================================================================================
#
# glyf - glyph outlines: TrueType glyf/loca loading and the path Skia builds from them
#
# DESCRIPTION:
# Written for the Luce port of Ladybird, which draws glyphs through Skia: Skia asks
# FreeType for the outline (FT_Load_Glyph, unhinted for paths) and turns it into an
# SkPath (SkFTGeometrySink in SkFontHost_FreeType_common.cpp). This fragment does the
# same in Luce, so glyphs fill exactly where the browser's do:
#
# - FreeType's fixed-point arithmetic (FT_MulFix, FT_DivFix, FT_MulDiv), exactly;
# - the TrueType glyph loader for unhinted outlines (freetype ttgload.c: simple glyphs,
# composite glyphs with their transforms and offsets, the phantom-point origin shift);
# - FT_Outline_Decompose and Skia's geometry sink, which turn on/off-curve points into
# move/line/quad/cubic/close verbs in 26.6 fixed point;
# - SkFont::getPath's canonical size: Skia always extracts paths at 64 px
# (kCanonicalTextSizeForPaths) and scales them to the requested size.
#
# There is no TrueType bytecode interpreter: outlines are unhinted, which is what Skia
# asks for paths anyway.
#
#==============================================================================================
# mark: FreeType's fixed-point arithmetic =====================================================
## FT_MulFix: (a * b) / 0x10000 rounded (freetype ftcalc.c).
pub func ft_mul_fix(a: i64, b: i64) -> i64:
let ab = a *% b
let bias: i64 = 1 if ab < 0 else 0
return (ab +% 0x8000 -% bias) >> 16
## FT_DivFix: (a * 0x10000) / b rounded, 0x7FFFFFFF for a zero divisor.
pub func ft_div_fix(a: i64, b: i64) -> i64:
var sign: i64 = 1
var ua = a
var ub = b
if ua < 0:
ua = -ua
sign = -sign
if ub < 0:
ub = -ub
sign = -sign
let q: i64 = ((ua << 16) + (ub >> 1)) // ub if ub > 0 else 0x7FFFFFFF
return -q if sign < 0 else q
## FT_MulDiv: (a * b) / c rounded, 0x7FFFFFFF for a zero divisor.
pub func ft_mul_div(a: i64, b: i64, divisor: i64) -> i64:
var sign: i64 = 1
var ua = a
var ub = b
var uc = divisor
if ua < 0:
ua = -ua
sign = -sign
if ub < 0:
ub = -ub
sign = -sign
if uc < 0:
uc = -uc
sign = -sign
let d: i64 = (ua * ub + (uc >> 1)) // uc if uc > 0 else 0x7FFFFFFF
return -d if sign < 0 else d
## FT_PIX_ROUND: a 26.6 value rounded to whole pixels.
pub func ft_pix_round(x: i64) -> i64:
return (x + 32) & ~(i64)63
## The 16.16 scale FreeType uses for a face at `pixel_size` pixels per em (FT_Set_Char_Size at
## 72 dpi, which does not go below 1 px, then tt_size_reset's integer ppem when the head
## table's flag bit 3 asks for it).
pub func sfnt_face_ft_scale(face: const SfntFace*, pixel_size: f32) -> i64:
# SkScalarToFDot6: a truncating conversion to 26.6.
var char_size = (i64)(pixel_size * 64.0)
if char_size < 1 * 64:
char_size = 1 * 64
if (face.head_flags & 8) != 0 and face.outline_format == SfntOutlineFormat.true_type:
let ppem = (char_size + 32) >> 6
return ft_div_fix(ppem << 6, (i64)face.units_per_em)
return ft_div_fix(char_size, (i64)face.units_per_em)
# mark: Outlines ================================================================================
## The curve tags of an FT_Outline point.
let ft_curve_tag_conic: u8 = 0
let ft_curve_tag_on: u8 = 1
let ft_curve_tag_cubic: u8 = 2
## An FT_Outline: points in 26.6 fixed point with their curve tags, and the index of each
## contour's last point.
pub struct SfntOutline:
pub var xs: List[i64]
pub var ys: List[i64]
pub var tags: List[u8]
pub var contour_ends: List[usize]
## Free the points, tags and contour ends.
pub func release():
self.xs.release()
self.ys.release()
self.tags.release()
self.contour_ends.release()
## The verbs of a glyph path, as SkPath's.
pub enum GlyphPathVerb as u8:
move = 0
line = 1
quad = 2
cubic = 3
close = 4
## A point of a glyph path, in pixels.
pub struct GlyphPoint:
pub var x: f32
pub var y: f32
## A glyph's outline as Skia's SkPath holds it: verbs and their points, in pixels, with y
## growing downward and the origin on the baseline at the glyph's pen position. A move takes
## one point, a line one, a quad two, a cubic three and a close none.
pub struct GlyphPath:
pub var verbs: List[GlyphPathVerb]
pub var points: List[GlyphPoint]
## Free the verbs and points; the path is empty afterwards.
pub func release():
self.verbs.release()
self.points.release()
func glyph_path_add(path: GlyphPath*, verb: GlyphPathVerb, x: f32, y: f32):
path.verbs.push(verb)
path.points.push(GlyphPoint(x = x, y = y))
func glyph_path_add_point(path: GlyphPath*, x: f32, y: f32):
path.points.push(GlyphPoint(x = x, y = y))
## SkPathBuilder::close: a close verb after anything but another close.
func glyph_path_close(path: GlyphPath*):
let count = path.verbs.length()
if count == 0:
return
if *path.verbs.at(count - 1) != GlyphPathVerb.close:
path.verbs.push(GlyphPathVerb.close)
# mark: The TrueType glyph loader ==============================================================
## The composite glyph flags (ttgload.c).
let tt_args_are_words: u16 = 0x0001
let tt_args_are_xy_values: u16 = 0x0002
let tt_we_have_a_scale: u16 = 0x0008
let tt_more_components: u16 = 0x0020
let tt_we_have_an_xy_scale: u16 = 0x0040
let tt_we_have_a_2x2: u16 = 0x0080
let tt_use_my_metrics: u16 = 0x0200
let tt_scaled_component_offset: u16 = 0x0800
let tt_unscaled_component_offset: u16 = 0x1000
## Where `glyph`'s data lies in the glyf table (loca), or none for an out-of-range glyph.
pub func sfnt_glyf_range(face: const SfntFace*, glyph: u32) -> (usize, usize)?:
if glyph >= (u32)face.num_glyphs:
return none
var start: usize
var end: usize
if face.index_to_loc_format == 0:
if ((usize)glyph + 2) * 2 > face.loca.length:
return none
start = (usize)sfnt_u16(face.loca, (usize)glyph * 2) * 2
end = (usize)sfnt_u16(face.loca, (usize)glyph * 2 + 2) * 2
else:
if ((usize)glyph + 2) * 4 > face.loca.length:
return none
start = (usize)sfnt_u32(face.loca, (usize)glyph * 4)
end = (usize)sfnt_u32(face.loca, (usize)glyph * 4 + 4)
# FreeType treats a glyph that ends before it starts, or past the table, as broken.
if end < start or end > face.glyf.length:
return none
return (start, end)
## Loads `glyph` into `outline`, scaled by the 16.16 `scale`, and answers its scaled pp1.x (the
## phantom point that becomes the origin). FreeType's load_truetype_glyph without hinting.
func sfnt_tt_load_glyph(face: const SfntFace*, glyph: u32, scale: i64, outline: SfntOutline*, depth: u32) -> i64!:
if depth > 15:
error(invalid_font, "Composite glyph nesting too deep")
let range = sfnt_glyf_range(face, glyph) else error(invalid_font, "Invalid glyph index")
let start = range.0
let end = range.1
let left_side_bearing = (i64)sfnt_face_left_side_bearing(face, glyph)
if end == start:
# An empty glyph: its phantom point uses a zero bounding box.
return ft_mul_fix(-left_side_bearing, scale)
let data = face.glyf[start..<end]
if data.length < 10:
error(invalid_font, "Truncated glyph header")
let number_of_contours = (i64)sfnt_i16(data, 0)
let x_min = (i64)sfnt_i16(data, 2)
let pp1_x = ft_mul_fix(x_min - left_side_bearing, scale)
if number_of_contours >= 0:
try sfnt_tt_load_simple_glyph(data, number_of_contours, scale, outline)
return pp1_x
return try sfnt_tt_load_composite_glyph(face, data, scale, outline, depth, pp1_x)
## TT_Load_Simple_Glyph and the scaling of TT_Process_Simple_Glyph.
func sfnt_tt_load_simple_glyph(data: const u8[], number_of_contours: i64, scale: i64, outline: SfntOutline*) -> !:
let base = outline.xs.length()
let contours = (usize)number_of_contours
var cursor: usize = 10
if cursor + contours * 2 + 2 > data.length:
error(invalid_font, "Truncated glyph contours")
var previous_end: i64 = -1
for index in 0..<contours:
let end_point = (i64)sfnt_u16(data, cursor)
cursor += 2
if end_point <= previous_end and index > 0:
error(invalid_font, "Invalid contour end points")
previous_end = end_point
let point_count: usize = (usize)(previous_end + 1) if contours > 0 else 0
let instruction_length = (usize)sfnt_u16(data, cursor)
cursor += 2 + instruction_length
if cursor > data.length:
error(invalid_font, "Truncated glyph instructions")
# The flags, with their repeat counts.
var flags: List[u8] = List[u8]()
defer flags.release()
flags.reserve(point_count)
while flags.length() < point_count:
if cursor >= data.length:
error(invalid_font, "Truncated glyph flags")
let flag = data[cursor]
cursor += 1
flags.push(flag)
if (flag & 8) != 0:
if cursor >= data.length:
error(invalid_font, "Truncated glyph flags")
var repeat = (usize)data[cursor]
cursor += 1
while repeat > 0 and flags.length() < point_count:
flags.push(flag)
repeat -= 1
# The x and then the y coordinates, as deltas.
var x: i64 = 0
for index in 0..<point_count:
let flag = *flags.at(index)
if (flag & 2) != 0:
if cursor >= data.length:
error(invalid_font, "Truncated glyph coordinates")
let delta = (i64)data[cursor]
cursor += 1
x += delta if (flag & 16) != 0 else -delta
elif (flag & 16) == 0:
if cursor + 2 > data.length:
error(invalid_font, "Truncated glyph coordinates")
x += (i64)sfnt_i16(data, cursor)
cursor += 2
outline.xs.push(x)
var y: i64 = 0
for index in 0..<point_count:
let flag = *flags.at(index)
if (flag & 4) != 0:
if cursor >= data.length:
error(invalid_font, "Truncated glyph coordinates")
let delta = (i64)data[cursor]
cursor += 1
y += delta if (flag & 32) != 0 else -delta
elif (flag & 32) == 0:
if cursor + 2 > data.length:
error(invalid_font, "Truncated glyph coordinates")
y += (i64)sfnt_i16(data, cursor)
cursor += 2
outline.ys.push(y)
outline.tags.push(ft_curve_tag_on if (flag & 1) != 0 else ft_curve_tag_conic)
# Scale the points (the unhinted branch of TT_Process_Simple_Glyph).
for index in base..<base + point_count:
let px = outline.xs.at(index)
*px = ft_mul_fix(*px, scale)
let py = outline.ys.at(index)
*py = ft_mul_fix(*py, scale)
var contour_cursor: usize = 10
for _index in 0..<contours:
outline.contour_ends.push(base + (usize)sfnt_u16(data, contour_cursor))
contour_cursor += 2
## TT_Load_Composite_Glyph and TT_Process_Composite_Component: every component loaded, then
## transformed and offset. Answers the composite's pp1.x (a component's with USE_MY_METRICS).
func sfnt_tt_load_composite_glyph(face: const SfntFace*, data: const u8[], scale: i64, outline: SfntOutline*, depth: u32, own_pp1_x: i64) -> i64!:
var pp1_x = own_pp1_x
let composite_base = outline.xs.length()
var cursor: usize = 10
while true:
if cursor + 4 > data.length:
error(invalid_font, "Truncated composite glyph")
let flags = sfnt_u16(data, cursor)
let component = (u32)sfnt_u16(data, cursor + 2)
cursor += 4
var arg1: i64
var arg2: i64
let are_xy = (flags & tt_args_are_xy_values) != 0
if (flags & tt_args_are_words) != 0:
if cursor + 4 > data.length:
error(invalid_font, "Truncated composite glyph")
if are_xy:
arg1 = (i64)sfnt_i16(data, cursor)
arg2 = (i64)sfnt_i16(data, cursor + 2)
else:
arg1 = (i64)sfnt_u16(data, cursor)
arg2 = (i64)sfnt_u16(data, cursor + 2)
cursor += 4
else:
if cursor + 2 > data.length:
error(invalid_font, "Truncated composite glyph")
if are_xy:
arg1 = (i64)(i8)data[cursor]
arg2 = (i64)(i8)data[cursor + 1]
else:
arg1 = (i64)data[cursor]
arg2 = (i64)data[cursor + 1]
cursor += 2
# The transform in 16.16 (F2Dot14 * 4): xx, yx, xy, yy as FreeType names them.
var xx: i64 = 0x10000
var yx: i64 = 0
var xy: i64 = 0
var yy: i64 = 0x10000
let has_scale = (flags & (tt_we_have_a_scale | tt_we_have_an_xy_scale | tt_we_have_a_2x2)) != 0
if (flags & tt_we_have_a_scale) != 0:
xx = (i64)sfnt_i16(data, cursor) * 4
yy = xx
cursor += 2
elif (flags & tt_we_have_an_xy_scale) != 0:
xx = (i64)sfnt_i16(data, cursor) * 4
yy = (i64)sfnt_i16(data, cursor + 2) * 4
cursor += 4
elif (flags & tt_we_have_a_2x2) != 0:
xx = (i64)sfnt_i16(data, cursor) * 4
yx = (i64)sfnt_i16(data, cursor + 2) * 4
xy = (i64)sfnt_i16(data, cursor + 4) * 4
yy = (i64)sfnt_i16(data, cursor + 6) * 4
cursor += 8
let component_base = outline.xs.length()
let component_pp1_x = try sfnt_tt_load_glyph(face, component, scale, outline, depth + 1)
if (flags & tt_use_my_metrics) != 0:
pp1_x = component_pp1_x
let component_end = outline.xs.length()
if has_scale:
for index in component_base..<component_end:
let px = outline.xs.at(index)
let py = outline.ys.at(index)
let tx = ft_mul_fix(*px, xx) + ft_mul_fix(*py, xy)
let ty = ft_mul_fix(*px, yx) + ft_mul_fix(*py, yy)
*px = tx
*py = ty
var offset_x: i64 = 0
var offset_y: i64 = 0
if not are_xy:
# Point matching: the parent's point arg1 meets the component's point arg2.
let parent_point = composite_base + (usize)arg1
let child_point = component_base + (usize)arg2
if parent_point >= component_base or child_point >= component_end:
error(invalid_font, "Invalid composite point indices")
offset_x = *outline.xs.at(parent_point) - *outline.xs.at(child_point)
offset_y = *outline.ys.at(parent_point) - *outline.ys.at(child_point)
elif arg1 != 0 or arg2 != 0:
offset_x = arg1
offset_y = arg2
# Apple's convention: the offset is in the component's transformed space.
if has_scale and (flags & tt_scaled_component_offset) != 0 and (flags & tt_unscaled_component_offset) == 0:
let mac_x_scale = ft_hypot_fixed(xx, xy)
let mac_y_scale = ft_hypot_fixed(yy, yx)
offset_x = ft_mul_fix(offset_x, mac_x_scale)
offset_y = ft_mul_fix(offset_y, mac_y_scale)
offset_x = ft_mul_fix(offset_x, scale)
offset_y = ft_mul_fix(offset_y, scale)
if offset_x != 0 or offset_y != 0:
for index in component_base..<component_end:
let px = outline.xs.at(index)
*px = *px + offset_x
let py = outline.ys.at(index)
*py = *py + offset_y
if (flags & tt_more_components) == 0:
break
return pp1_x
## FT_Hypot of two 16.16 values (the length of a transform column).
func ft_hypot_fixed(a: i64, b: i64) -> i64:
let fa = (f64)a / 65536.0
let fb = (f64)b / 65536.0
return (i64)(math.sqrt(fa * fa + fb * fb) * 65536.0 + 0.5)
## The unhinted outline of `glyph` at the 16.16 `scale`, translated so that the origin is the
## glyph's pen position (FT_Load_Glyph with FT_LOAD_NO_HINTING), or none when FreeType fails.
pub func sfnt_face_load_outline(face: const SfntFace*, glyph: u32, scale: i64) -> SfntOutline?:
var outline: SfntOutline
var loaded = true
match face.outline_format:
.true_type:
let pp1: i64? = sfnt_tt_load_glyph(face, glyph, scale, &outline, 0) catch:
recover none
if let pp1_x = pp1:
if pp1_x != 0:
for index in 0..<outline.xs.length():
let px = outline.xs.at(index)
*px = *px - pp1_x
else:
loaded = false
.cff:
sfnt_cff_load_glyph(face, glyph, scale, &outline) catch:
loaded = false
recover ()
_:
loaded = false
if not loaded:
outline.release()
return none
return outline
# mark: From outline to path ===================================================================
## Skia's SkFTGeometrySink state: the contour has been started, and the current point.
struct SkiaGeometrySink:
var path: GlyphPath*
var started: bool
var current_x: i64
var current_y: i64
var scale: f32
## SkFDot6ToScalar and the canonical-size scale of SkFont::getPaths.
func sink_x(sink: const SkiaGeometrySink*, x: i64) -> f32:
# SkMatrix::mapPoints adds the (zero) translation, so -0.0 becomes 0.0.
return ((f32)x * 0.015625) * sink.scale + 0.0
func sink_y(sink: const SkiaGeometrySink*, y: i64) -> f32:
return (-((f32)y * 0.015625)) * sink.scale + 0.0
func sink_going_to(sink: SkiaGeometrySink*, x: i64, y: i64):
if not sink.started:
sink.started = true
glyph_path_add(sink.path, GlyphPathVerb.move, sink_x(sink, sink.current_x), sink_y(sink, sink.current_y))
sink.current_x = x
sink.current_y = y
func sink_current_is_not(sink: const SkiaGeometrySink*, x: i64, y: i64) -> bool:
return sink.current_x != x or sink.current_y != y
func sink_move(sink: SkiaGeometrySink*, x: i64, y: i64):
if sink.started:
glyph_path_close(sink.path)
sink.started = false
sink.current_x = x
sink.current_y = y
func sink_line(sink: SkiaGeometrySink*, x: i64, y: i64):
if sink_current_is_not(sink, x, y):
sink_going_to(sink, x, y)
glyph_path_add(sink.path, GlyphPathVerb.line, sink_x(sink, x), sink_y(sink, y))
func sink_quad(sink: SkiaGeometrySink*, x0: i64, y0: i64, x1: i64, y1: i64):
if sink_current_is_not(sink, x0, y0) or sink_current_is_not(sink, x1, y1):
sink_going_to(sink, x1, y1)
glyph_path_add(sink.path, GlyphPathVerb.quad, sink_x(sink, x0), sink_y(sink, y0))
glyph_path_add_point(sink.path, sink_x(sink, x1), sink_y(sink, y1))
func sink_cubic(sink: SkiaGeometrySink*, x0: i64, y0: i64, x1: i64, y1: i64, x2: i64, y2: i64):
if sink_current_is_not(sink, x0, y0) or sink_current_is_not(sink, x1, y1) or sink_current_is_not(sink, x2, y2):
sink_going_to(sink, x2, y2)
glyph_path_add(sink.path, GlyphPathVerb.cubic, sink_x(sink, x0), sink_y(sink, y0))
glyph_path_add_point(sink.path, sink_x(sink, x1), sink_y(sink, y1))
glyph_path_add_point(sink.path, sink_x(sink, x2), sink_y(sink, y2))
## FT_Outline_Decompose (ftoutln.c) into Skia's sink, then the final close of
## generateGlyphPathStatic. Answers false for an invalid outline, as FreeType does.
func sfnt_outline_decompose(outline: const SfntOutline*, sink: SkiaGeometrySink*) -> bool:
let xs = outline.xs.view()
let ys = outline.ys.view()
let tags = outline.tags.view()
var last: isize = -1
for contour_end in outline.contour_ends.view():
let first = last + 1
last = (isize)contour_end
if last < first or (usize)last >= xs.length:
return false
var limit = (usize)last
var v_start_x = xs[(usize)first]
var v_start_y = ys[(usize)first]
let v_last_x = xs[(usize)last]
let v_last_y = ys[(usize)last]
var v_control_x = v_start_x
var v_control_y = v_start_y
# `point` is one past the index FreeType's pointer is at, so that "one before the
# first point" is representable.
var point = (usize)first + 1
var tag = tags[(usize)first]
# A contour cannot start with a cubic control point!
if tag == ft_curve_tag_cubic:
return false
# check first point to determine origin
if tag == ft_curve_tag_conic:
# first point is conic control. Yes, this happens.
if tags[(usize)last] == ft_curve_tag_on:
# start at last point if it is on the curve
v_start_x = v_last_x
v_start_y = v_last_y
limit -= 1
else:
# if both first and last points are conic, start at their middle and record
# its position for closure
v_start_x = (v_start_x + v_last_x) // 2
v_start_y = (v_start_y + v_last_y) // 2
point -= 1
sink_move(sink, v_start_x, v_start_y)
var closed = false
while point < limit + 1:
point += 1
tag = tags[point - 1]
if tag == ft_curve_tag_on:
# emit a single line_to
sink_line(sink, xs[point - 1], ys[point - 1])
continue
if tag == ft_curve_tag_conic:
# consume conic arcs
v_control_x = xs[point - 1]
v_control_y = ys[point - 1]
var done_conic = false
while point < limit + 1:
point += 1
let conic_tag = tags[point - 1]
let vec_x = xs[point - 1]
let vec_y = ys[point - 1]
if conic_tag == ft_curve_tag_on:
sink_quad(sink, v_control_x, v_control_y, vec_x, vec_y)
done_conic = true
break
if conic_tag != ft_curve_tag_conic:
return false
let v_middle_x = (v_control_x + vec_x) // 2
let v_middle_y = (v_control_y + vec_y) // 2
sink_quad(sink, v_control_x, v_control_y, v_middle_x, v_middle_y)
v_control_x = vec_x
v_control_y = vec_y
if done_conic:
continue
sink_quad(sink, v_control_x, v_control_y, v_start_x, v_start_y)
closed = true
break
# FT_CURVE_TAG_CUBIC
if point > limit or tags[point] != ft_curve_tag_cubic:
return false
point += 2
let vec1_x = xs[point - 3]
let vec1_y = ys[point - 3]
let vec2_x = xs[point - 2]
let vec2_y = ys[point - 2]
if point <= limit + 1:
sink_cubic(sink, vec1_x, vec1_y, vec2_x, vec2_y, xs[point - 1], ys[point - 1])
continue
sink_cubic(sink, vec1_x, vec1_y, vec2_x, vec2_y, v_start_x, v_start_y)
closed = true
break
if not closed:
# close the contour with a line segment
sink_line(sink, v_start_x, v_start_y)
glyph_path_close(sink.path)
return true
## The path of `glyph` at `pixel_size`: SkFont::getPath (the outline at the canonical 64 px,
## unhinted, scaled by pixel_size / 64). An empty path when the glyph has no outline.
pub func sfnt_face_glyph_path(face: const SfntFace*, glyph: u32, pixel_size: f32) -> GlyphPath:
var path: GlyphPath
path.points = List[GlyphPoint]()
path.verbs = List[GlyphPathVerb]()
let canonical_size: f32 = 64.0
let outline = sfnt_face_load_outline(face, glyph, sfnt_face_ft_scale(face, canonical_size)) else return path
var sink = SkiaGeometrySink(path = &path, scale = pixel_size / canonical_size)
if not sfnt_outline_decompose(&outline, &sink):
path.verbs.clear()
path.points.clear()
var used = outline
used.release()
return path