1// Glyph outlines: from `glyf`, contours of on- and off-curve points2// (quadratic curves), composite glyphs assembled from their components;3// from CFF and CFF2 (text_fonts' cff.alloy), lines and cubic curves.45import std::vector;6import std::option;7import std::math;89import reader;10import face;1112// What a point of a contour is: on the curve, a quadratic curve's13// control point (two in a row implying an on-curve point midway), or one14// of a cubic curve's two control points.15exp type PointKind = enum {16 On,17 Quadratic,18 Cubic,19};2021exp type OutlinePoint = struct {22 exp x: f32,23 exp y: f32, // font units, y up24 exp kind: PointKind,25};2627exp type Outline = struct {28 exp points: Vector<OutlinePoint>,29 exp ends: Vector<u32>, // each contour's last point30};3132exp fn Outline::empty() -> Outline {33 return Outline { .points = Vector<OutlinePoint>::empty(), .ends = Vector<u32>::empty() };34}3536// A point being moved by a variable face's deltas, in font units.37exp type Moved = struct {38 exp x: f32,39 exp y: f32,40};4142// The point (x, y) goes to (a x + c y + e, b x + d y + f).43exp type Affine = struct {44 exp a: f32,45 exp b: f32,46 exp c: f32,47 exp d: f32,48 exp e: f32,49 exp f: f32,50};5152exp const IDENTITY: Affine = Affine { .a = 1.0, .b = 0.0, .c = 0.0, .d = 1.0, .e = 0.0, .f = 0.0 };5354fn identity(self t: &Affine) -> bool {55 return t.a == 1.0 && t.b == 0.0 && t.c == 0.0 && t.d == 1.0 && t.e == 0.0 && t.f == 0.0;56}5758// The transform undoing this one; one taking every point to the origin59// when it has no inverse.60exp fn inverse(self t: &Affine) -> Affine {61 const det = t.a * t.d - t.b * t.c;62 if (det == 0.0) {63 return Affine { .a = 0.0, .b = 0.0, .c = 0.0, .d = 0.0, .e = 0.0, .f = 0.0 };64 }65 const a = t.d / det;66 const b = -t.b / det;67 const c = -t.c / det;68 const d = t.a / det;69 return Affine {70 .a = a,71 .b = b,72 .c = c,73 .d = d,74 .e = -(a * t.e + c * t.f),75 .f = -(b * t.e + d * t.f)76 };77}7879// This transform, then the outer one.80exp fn then(self inner: &Affine, outer: &Affine) -> Affine {81 return Affine {82 .a = outer.a * inner.a + outer.c * inner.b,83 .b = outer.b * inner.a + outer.d * inner.b,84 .c = outer.a * inner.c + outer.c * inner.d,85 .d = outer.b * inner.c + outer.d * inner.d,86 .e = outer.a * inner.e + outer.c * inner.f + outer.e,87 .f = outer.b * inner.e + outer.d * inner.f + outer.f88 };89}9091// A simple glyph's point flags92const ON_CURVE: u8 = 0x01;93const X_SHORT: u8 = 0x02;94const Y_SHORT: u8 = 0x04;95const REPEAT: u8 = 0x08;96const X_SAME_OR_POSITIVE: u8 = 0x10;97const Y_SAME_OR_POSITIVE: u8 = 0x20;9899// A composite glyph's component flags100const ARGUMENTS_ARE_WORDS: u32 = 0x1;101const ARGUMENTS_ARE_OFFSETS: u32 = 0x2;102const HAS_SCALE: u32 = 0x8;103const MORE_COMPONENTS: u32 = 0x20;104const HAS_X_AND_Y_SCALE: u32 = 0x40;105const HAS_TWO_BY_TWO: u32 = 0x80;106const SCALED_COMPONENT_OFFSET: u32 = 0x800;107108// The glyph's outline: empty for a space or a glyph past the face's. A109// face's .notdef left empty, as Inter's is, is drawn as a box, so a110// character the face lacks still shows.111exp fn outline(self face: &Face, glyph: u32) -> Outline {112 var out = face.drawn_outline(glyph);113 if (glyph == 0 && out.points.length() == 0) {114 face.add_box(&var out);115 }116 if (face.embolden != 0.0) {117 out.embolden(face.embolden);118 }119 return move out;120}121122// The glyph's outline as its font draws it, at the face's position on123// its axes.124exp fn drawn_outline(self face: &Face, glyph: u32) -> Outline {125 var out = Outline::empty();126 match (face.glyphs) {127 ::TrueType |&table| {128 // moved so that its left phantom point is at x 0, as129 // HarfBuzz and fontTools draw it130 const left = face.add_glyph(&table, &var out, glyph, &IDENTITY, 0);131 if (left != 0.0) {132 for (out.points.items()) |&var p| {133 p.x -= left;134 }135 }136 }137 ::Cff |&outlines| {138 outlines.draw(&face, glyph, &var out);139 }140 ::Nothing {}141 }142 return move out;143}144145// Thickens the outline by `strength` font units as FreeType's146// FT_Outline_EmboldenXY does, each point moved along the bisector of its147// contour's turn there, then up and right by half of it so that the ink148// keeps its left side and baseline (HarfBuzz's synthetic bold).149fn embolden(self out: &var Outline, strength: f32) {150 const half = strength / 2.0;151 const negative = out.control_area() < 0.0;152 var first: i64 = 0;153 for (out.ends.view()) |end| {154 const last = end to i64;155 // j walks the points; i follows, moving those behind j once the156 // turn at j is known; k is the first point moved157 var i = last;158 var j = first;159 var k: i64 = -1;160 var before = Moved { .x = 0.0, .y = 0.0 };161 var before_length: f32 = 0.0;162 var anchor = Moved { .x = 0.0, .y = 0.0 };163 var anchor_length: f32 = 0.0;164 while (j != i && i != k) {165 var after = anchor;166 var after_length = anchor_length;167 if (j != k) {168 const p = &out.points.get(j to u64);169 const q = &out.points.get(i to u64);170 after = Moved { .x = p.x - q.x, .y = p.y - q.y };171 after_length = sqrt(after.x * after.x + after.y * after.y);172 if (after_length == 0.0) {173 j = if (j < last) j + 1 else first;174 continue;175 }176 after.x /= after_length;177 after.y /= after_length;178 }179 if (before_length != 0.0) {180 if (k < 0) {181 k = i;182 anchor = before;183 anchor_length = before_length;184 }185 var shift = Moved { .x = 0.0, .y = 0.0 };186 const d = before.x * after.x + before.y * after.y;187 // only for a turn of less than about 160 degrees188 if (d > -15.0 / 16.0) {189 const e = d + 1.0;190 shift.x = before.y + after.y;191 shift.y = before.x + after.x;192 var cross = after.x * before.y - after.y * before.x;193 if (negative) {194 shift.x = -shift.x;195 cross = -cross;196 } else {197 shift.y = -shift.y;198 }199 // at most as far as the shorter segment, for segments200 // collapsing201 const l = min(before_length, after_length);202 shift.x = if (203 half * cross <= l * e204 ) shift.x * half / e else shift.x * l / cross;205 shift.y = if (206 half * cross <= l * e207 ) shift.y * half / e else shift.y * l / cross;208 }209 while (i != j) {210 const p = &var out.points.get_var(i to u64);211 p.x += half + shift.x;212 p.y += half + shift.y;213 i = if (i < last) i + 1 else first;214 }215 } else {216 i = j;217 }218 before = after;219 before_length = after_length;220 j = if (j < last) j + 1 else first;221 }222 first = last + 1;223 }224}225226// The area the outline's points enclose, counting control points as on227// the contour: negative for contours clockwise, y up.228fn control_area(self out: &Outline) -> f32 {229 var area: f32 = 0.0;230 var first: u64 = 0;231 for (out.ends.view()) |end| {232 const last = end to u64;233 for ([first..last + 1]) |i| {234 const p = &out.points.get(i);235 const q = &out.points.get(if (i < last) i + 1 else first);236 area += p.x * q.y - p.y * q.x;237 }238 first = last + 1;239 }240 return area / 2.0;241}242243// A hollow box within .notdef's advance, from the baseline to about the244// capitals' height.245fn add_box(self face: &Face, out: &var Outline) {246 const advance = face.advance(0);247 if (advance <= 0.0) {248 return;249 }250 const x0 = advance * 0.12;251 const x1 = advance * 0.88;252 const y1 = face.ascender * 0.7;253 const stroke = face.units_per_em / 18.0;254 // the outer contour clockwise, the inner one counterclockwise255 add_rect(&var out, x0, 0.0, x1, y1, true);256 add_rect(&var out, x0 + stroke, stroke, x1 - stroke, y1 - stroke, false);257}258259fn add_rect(out: &var Outline, x0: f32, y0: f32, x1: f32, y1: f32, clockwise: bool) {260 const xs = if (clockwise) [x0, x0, x1, x1] else [x0, x1, x1, x0];261 const ys = if (clockwise) [y0, y1, y1, y0] else [y0, y0, y1, y1];262 for (xs, ys) |x, y| {263 out.points.push(OutlinePoint { .x = x, .y = y, .kind = PointKind::On });264 }265 out.ends.push((out.points.length() - 1) to u32);266}267268// Adds the glyph's contours, transformed, and gives the x of its left269// phantom point: its bounds' left less its left side bearing, moved by270// `gvar` at a variable face's position.271fn add_glyph(272 self face: &Face,273 table: &TrueTypeGlyphs,274 out: &var Outline,275 glyph: u32,276 transform: &Affine,277 depth: u32278) -> f32 {279 const g = &face.glyph_data(&table, glyph);280 const x_min = if (g.length() >= 10) i16_at(&g, 2) to f32 else 0.0;281 var phantoms: [Moved : 4] = [Moved { .x = 0.0, .y = 0.0 } : 4];282 phantoms[0].x = x_min - face.left_side_bearing(glyph);283 phantoms[1].x = phantoms[0].x + face.hmtx_advance(glyph);284 const varied = face.coords.length() > 0 && face.variations.gvar is ::Some;285 if (g.length() < 10 || depth > 8) {286 if (varied) {287 var points = Vector<Moved>::from(&phantoms[..]);288 face.vary_points(glyph, &var points, &Vector<u32>::empty().view());289 return points.get(0).x;290 }291 return phantoms[0].x;292 }293 const contours = i16_at(&g, 0);294 if (contours >= 0) {295 // decoded in place, then moved and transformed there296 const first = out.points.length();297 add_simple(&g, contours to u64, &var out);298 var left = phantoms[0].x;299 if (varied) {300 var points = Vector<Moved>::with_capacity(out.points.length() - first + 4);301 for (out.points.view()[first..]) |&p| {302 points.push(Moved { .x = p.x, .y = p.y });303 }304 points.append(&phantoms[..]);305 var ends = Vector<u32>::with_capacity(contours to u64);306 for (out.ends.view()[out.ends.length() - contours to u64..]) |end| {307 ends.push(end - first to u32);308 }309 face.vary_points(glyph, &var points, &ends.view());310 for (out.points.items()[first..], points.view()[..points.length() - 4]) |&var p, &m| {311 p.x = m.x;312 p.y = m.y;313 }314 left = points.get(points.length() - 4).x;315 }316 if (!transform.identity()) {317 for (out.points.items()[first..]) |&var p| {318 const x = p.x;319 p.x = transform.a * x + transform.c * p.y + transform.e;320 p.y = transform.b * x + transform.d * p.y + transform.f;321 }322 }323 return left;324 }325 var components = read_components(&g);326 // each component's offset a point, then the phantom points; a327 // component is a contour of its own328 var points = Vector<Moved>::with_capacity(components.length() + 4);329 var ends = Vector<u32>::with_capacity(components.length());330 for (components.view()) |&c| {331 ends.push(points.length() to u32);332 points.push(Moved { .x = c.dx, .y = c.dy });333 }334 points.append(&phantoms[..]);335 if (varied) {336 face.vary_points(glyph, &var points, &ends.view());337 }338 for (components.view(), points.view()[..components.length()]) |&c, &offset| {339 var local = c.transform;340 if (c.scaled_offset) {341 local.e = local.a * offset.x + local.c * offset.y;342 local.f = local.b * offset.x + local.d * offset.y;343 } else {344 local.e = offset.x;345 local.f = offset.y;346 }347 face.add_glyph(&table, &var out, c.glyph, &local.then(&transform), depth + 1);348 }349 return points.get(components.length()).x;350}351352// Moves the points (the outline's or a composite's offsets, then the four353// phantom ones) by the glyph's `gvar` deltas at the face's position.354fn vary_points(self face: &Face, glyph: u32, points: &var Vector<Moved>, ends: &[u32]) {355 if (face.formats is ::Some |f|) {356 (f.vary_points)(&face, glyph, &var points, &ends);357 }358}359360// A component of a composite glyph: the glyph, its offset (or none, when361// it is placed by matching points) and transform.362type Component = struct {363 glyph: u32,364 dx: f32,365 dy: f32,366 transform: Affine,367 scaled_offset: bool,368};369370fn read_components(g: &[u8]) -> Vector<Component> {371 var out = Vector<Component>::empty();372 var p: u64 = 10;373 while (p + 4 <= g.length()) {374 const flags = u16_at(&g, p);375 var c = Component {376 .glyph = u16_at(&g, p + 2),377 .dx = 0.0,378 .dy = 0.0,379 .transform = IDENTITY,380 .scaled_offset = (flags & SCALED_COMPONENT_OFFSET) != 0381 };382 p += 4;383 if ((flags & ARGUMENTS_ARE_WORDS) != 0) {384 if ((flags & ARGUMENTS_ARE_OFFSETS) != 0) {385 c.dx = i16_at(&g, p) to f32;386 c.dy = i16_at(&g, p + 2) to f32;387 }388 p += 4;389 } else {390 if ((flags & ARGUMENTS_ARE_OFFSETS) != 0) {391 c.dx = signed_byte(u8_at(&g, p)) to f32;392 c.dy = signed_byte(u8_at(&g, p + 1)) to f32;393 }394 p += 2;395 }396 if ((flags & HAS_SCALE) != 0) {397 c.transform.a = f2dot14_at(&g, p);398 c.transform.d = c.transform.a;399 p += 2;400 } else if ((flags & HAS_X_AND_Y_SCALE) != 0) {401 c.transform.a = f2dot14_at(&g, p);402 c.transform.d = f2dot14_at(&g, p + 2);403 p += 4;404 } else if ((flags & HAS_TWO_BY_TWO) != 0) {405 c.transform.a = f2dot14_at(&g, p);406 c.transform.b = f2dot14_at(&g, p + 2);407 c.transform.c = f2dot14_at(&g, p + 4);408 c.transform.d = f2dot14_at(&g, p + 6);409 p += 8;410 }411 out.push(c);412 if ((flags & MORE_COMPONENTS) == 0) {413 break;414 }415 }416 return move out;417}418419fn signed_byte(v: u32) -> i32 {420 return if (v >= 0x80) v to i32 - 0x100 else v to i32;421}422423// Adds a simple glyph's contours, in font units.424fn add_simple(g: &[u8], contours: u64, out: &var Outline) {425 if (contours == 0) {426 return;427 }428 const base = out.points.length() to u32;429 const count = u16_at(&g, 10 + (contours - 1) * 2) to u64 + 1;430 for ([..contours]) |k| {431 out.ends.push(base + u16_at(&g, 10 + k * 2));432 }433 const instructions = u16_at(&g, 10 + contours * 2) to u64;434 var p = 12 + contours * 2 + instructions;435 var flags = Vector<u8>::with_capacity(count);436 while (flags.length() < count && p < g.length()) {437 const f = u8_at(&g, p) to u8;438 p += 1;439 flags.push(f);440 if ((f & REPEAT) != 0) {441 var repeat = u8_at(&g, p);442 p += 1;443 while (repeat > 0 && flags.length() < count) {444 flags.push(f);445 repeat -= 1;446 }447 }448 }449 while (flags.length() < count) {450 flags.push(0);451 }452 const first = out.points.length();453 out.points.reserve(count);454 var x: i32 = 0;455 for (flags.view()) |f| {456 if ((f & X_SHORT) != 0) {457 const v = u8_at(&g, p) to i32;458 p += 1;459 x += if ((f & X_SAME_OR_POSITIVE) != 0) v else -v;460 } else if ((f & X_SAME_OR_POSITIVE) == 0) {461 x += i16_at(&g, p);462 p += 2;463 }464 out.points.push(OutlinePoint {465 .x = x to f32,466 .y = 0.0,467 .kind = if ((f & ON_CURVE) != 0) PointKind::On else PointKind::Quadratic468 });469 }470 var y: i32 = 0;471 for (flags.view(), out.points.items()[first..]) |f, &var point| {472 if ((f & Y_SHORT) != 0) {473 const v = u8_at(&g, p) to i32;474 p += 1;475 y += if ((f & Y_SAME_OR_POSITIVE) != 0) v else -v;476 } else if ((f & Y_SAME_OR_POSITIVE) == 0) {477 y += i16_at(&g, p);478 p += 2;479 }480 point.y = y to f32;481 }482}483484// A glyph's ink box as HarfBuzz gives it, in font units: from the left485// side bearing and the top, its width and its height (negative, down).486exp type Extents = struct {487 exp x_bearing: f32,488 exp y_bearing: f32,489 exp width: f32,490 exp height: f32,491};492493// The glyph's extents, None for a face with no outlines (HarfBuzz's494// hb_font_get_glyph_extents): a TrueType glyph's from its header with495// `hmtx`'s side bearing, others' and varied ones' from their points; a496// face made bold's taller and wider by its strength, as HarfBuzz's.497exp fn extents(self face: &Face, glyph: u32) -> Option<Extents> {498 const drawn = face.drawn_extents(glyph);499 if (face.embolden != 0.0 && drawn is ::Some |e|) {500 return ::Some(Extents {501 .x_bearing = e.x_bearing,502 .y_bearing = e.y_bearing + face.embolden,503 .width = e.width + face.embolden,504 .height = e.height - face.embolden505 });506 }507 return drawn;508}509510fn drawn_extents(self face: &Face, glyph: u32) -> Option<Extents> {511 match (face.glyphs) {512 ::Nothing {513 return ::None;514 }515 ::TrueType |&table| {516 if (face.coords.length() == 0 || face.variations.gvar is ::None) {517 const g = &face.glyph_data(&table, glyph);518 if (g.length() < 10) {519 return ::Some(Extents {520 .x_bearing = 0.0,521 .y_bearing = 0.0,522 .width = 0.0,523 .height = 0.0524 });525 }526 const x_min = i16_at(&g, 2) to f32;527 const y_min = i16_at(&g, 4) to f32;528 const x_max = i16_at(&g, 6) to f32;529 const y_max = i16_at(&g, 8) to f32;530 const left = min(x_min, x_max);531 return ::Some(Extents {532 .x_bearing = if (face.metric_count > 0) face.left_side_bearing(glyph) else left,533 .y_bearing = max(y_min, y_max),534 .width = max(x_min, x_max) - left,535 .height = min(y_min, y_max) - max(y_min, y_max)536 });537 }538 }539 else {}540 }541 const o = face.drawn_outline(glyph);542 if (o.points.length() == 0) {543 return ::Some(Extents { .x_bearing = 0.0, .y_bearing = 0.0, .width = 0.0, .height = 0.0 });544 }545 var x0 = o.points.get(0).x;546 var x1 = x0;547 var y0 = o.points.get(0).y;548 var y1 = y0;549 for (o.points.view()) |&p| {550 x0 = min(x0, p.x);551 x1 = max(x1, p.x);552 y0 = min(y0, p.y);553 y1 = max(y1, p.y);554 }555 const x_bearing = round(x0);556 const y_bearing = round(y1);557 return ::Some(Extents {558 .x_bearing = x_bearing,559 .y_bearing = y_bearing,560 .width = round(x1 - x_bearing),561 .height = round(y0 - y_bearing)562 });563}