Skip to content

Code-first video & image, rendered natively on WebGPU.

feat(text): shape and lay out Arabic, Hebrew and other RTL scripts

okanasl24a4176faddb
diff --git a/.changeset/rtl-text-shaping.md b/.changeset/rtl-text-shaping.md
new file mode 100644
index 00000000..f72c0cd6
--- /dev/null
+++ b/.changeset/rtl-text-shaping.md
@@ -0,0 +1,7 @@
+---
+"framefields": minor
+---
+
+Text layers now render Arabic, Hebrew, Persian and other complex scripts. Each run is shaped with the font's OpenType tables (joining forms, lam-alef and other ligatures, kerning, mark placement), paragraphs go through the Unicode Bidirectional Algorithm, and lines wrap and read right to left with embedded Latin words and numbers kept left to right. Glyphs outside the default Latin set are generated on first use instead of rendering as boxes.
+
+New `direction: "auto" | "ltr" | "rtl"` option on text and caption layers (default `"auto"`, taken from the first strong character); `align: "start" | "end"` now follow it instead of always meaning left and right. `FontManager.measure` accepts `direction` and reports right-to-left glyphs and carets. The Slug binary format moves to v2 (`SLUGGIS2`, with glyph ids); v1 files still load.
diff --git a/nodes/node-compositor/SKILL.md b/nodes/node-compositor/SKILL.md
index 41d9c863..ce6c08c8 100644
--- a/nodes/node-compositor/SKILL.md
+++ b/nodes/node-compositor/SKILL.md
@@ -109,7 +109,7 @@ Container styles (flex/block/box with children):
Per-kind fields:
- **`box`**: `background` (CSS color, also accepts gradients), `borderRadius` (number), `padding`. A `box` with children behaves like a column container.
-- **`text`**: `text` (string), `fontSize`, `fontFamily`, `fontWeight`, `fontStyle`, `fill` (text color), `align`, `verticalAlign` (`top` default | `middle` | `bottom`: places the text block in a `height` taller than it; ignored for path text), `lineHeight`, `letterSpacing`, `textShadow`, `shadows`, `background` (rounded text box fill), `borderRadius`, `padding`.
+- **`text`**: `text` (string), `fontSize`, `fontFamily`, `fontWeight`, `fontStyle`, `fill` (text color), `align` (`start`/`end` follow the text direction), `direction` (`auto` default | `ltr` | `rtl`: paragraph base direction; `auto` takes it from the first strong character, so Arabic/Hebrew/Persian read right to left, with mixed Latin and numbers kept in order), `verticalAlign` (`top` default | `middle` | `bottom`: places the text block in a `height` taller than it; ignored for path text), `lineHeight`, `letterSpacing`, `textShadow`, `shadows`, `background` (rounded text box fill), `borderRadius`, `padding`.
- **Kinetic Typography Animators (`animators`)**: Array of text animators applied sequentially at the Slug GPU glyph instancing stage:
- `id` (string): Unique animator identifier.
- `unit` (`"character"` | `"word"` | `"line"`, default `"character"`): Granularity of text breakdown.
@@ -141,6 +141,7 @@ Per-kind fields:
- `fontStyle` (`"normal"` | `"italic"`).
- `fill` (string, default `"#ffffff"`): Text color.
- `align` (`"start"` | `"center"` | `"end"`, default `"center"`): Horizontal text alignment.
+ - `direction` (`"auto"` | `"ltr"` | `"rtl"`, default `"auto"`): Caption text direction; `start`/`end` follow it.
- `verticalAlign` (`"top"` | `"middle"` | `"bottom"`, default `"bottom"`): Vertical alignment. When `"bottom"`, the bottom edge is anchored, and multi-line subtitle cues expand **upwards**.
- `lineHeight` (number, default `1.2` or `fontSize * 1.2`).
- `letterSpacing` (number, default `0`).
diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
index 11a71316..695ac05f 100644
--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
@@ -743,6 +743,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
letterSpacing: node.letterSpacing,
lineHeight: node.lineHeight,
padding: node.padding,
+ direction: node.direction,
};
if (constraintWidth !== undefined) {
@@ -3219,12 +3220,8 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
fontStyle: lop.fontStyle,
fontWeight: lop.fontWeight,
fill: target?.fill ?? target?.color ?? lop.fill,
- align:
- lop.align === "start"
- ? "left"
- : lop.align === "end"
- ? "right"
- : lop.align,
+ align: lop.align,
+ direction: lop.direction,
verticalAlign: lop.verticalAlign,
letterSpacing: target?.letterSpacing ?? lop.letterSpacing,
lineHeight: lop.lineHeight,
@@ -3309,12 +3306,8 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
fontStyle: lop.fontStyle,
fill: lop.fill,
color: lop.fill,
- align:
- lop.align === "start"
- ? "left"
- : lop.align === "end"
- ? "right"
- : (lop.align ?? "center"),
+ align: lop.align ?? "center",
+ direction: lop.direction,
verticalAlign: lop.verticalAlign ?? lop.textAlignVertical,
lineHeight: lop.lineHeight,
letterSpacing: lop.letterSpacing,
diff --git a/packages/compositions/src/compositions/canvas-composition.ts b/packages/compositions/src/compositions/canvas-composition.ts
index 5355119d..91ba876b 100644
--- a/packages/compositions/src/compositions/canvas-composition.ts
+++ b/packages/compositions/src/compositions/canvas-composition.ts
@@ -114,6 +114,7 @@ function paragraphPropsFromTextOp(
height: opText.height ? Number(opText.height) : undefined,
lineHeight: Number(opText.lineHeight ?? 1.2),
align: opText.align,
+ direction: opText.direction,
verticalAlign: opText.verticalAlign,
fontWeight: opText.fontWeight,
fontStyle: opText.fontStyle,
@@ -594,12 +595,8 @@ export async function drawCompositionTree(
fontSize: Number(opCap.fontSize ?? 48),
color: opCap.fill ?? opCap.color ?? "white",
lineHeight: Number(opCap.lineHeight ?? 1.2),
- align:
- opCap.align === "start"
- ? "left"
- : opCap.align === "end"
- ? "right"
- : (opCap.align ?? "center"),
+ align: opCap.align ?? "center",
+ direction: opCap.direction,
textAlignVertical: opCap.verticalAlign ?? opCap.textAlignVertical,
fontWeight: opCap.fontWeight,
fontStyle: opCap.fontStyle,
diff --git a/packages/compositions/src/program/schema.ts b/packages/compositions/src/program/schema.ts
index 5882975d..9da76a13 100644
--- a/packages/compositions/src/program/schema.ts
+++ b/packages/compositions/src/program/schema.ts
@@ -903,6 +903,12 @@ export interface TextNode extends CompositionNodeBase {
fontStyle?: string;
fill?: string;
align?: "start" | "center" | "end";
+ /**
+ * Base direction of each paragraph. "auto" (default) takes it from the
+ * first strong character, so Arabic, Hebrew or Persian reads right to
+ * left; "start"/"end" alignment follows it.
+ */
+ direction?: "ltr" | "rtl" | "auto";
verticalAlign?: "top" | "middle" | "bottom";
lineHeight?: number;
letterSpacing?: number;
@@ -941,6 +947,8 @@ export interface MediaNode extends CompositionNodeBase {
fontStyle?: string;
fill?: string;
align?: "start" | "center" | "end";
+ /** Caption text direction; see {@link TextNode.direction}. */
+ direction?: "ltr" | "rtl" | "auto";
verticalAlign?: "top" | "middle" | "bottom";
lineHeight?: number;
letterSpacing?: number;
@@ -1397,6 +1405,7 @@ const TextFields = {
/** Text color (v1 name kept). */
fill: ColorSchema,
align: z.enum(["start", "center", "end"]).optional(),
+ direction: z.enum(["ltr", "rtl", "auto"]).optional(),
verticalAlign: z.enum(["top", "middle", "bottom"]).optional(),
lineHeight: z.number().positive().optional(),
letterSpacing: z.number().optional(),
@@ -1453,6 +1462,7 @@ export const MediaNodeSchema: z.ZodType<MediaNode> = z
fontStyle: z.string().optional(),
fill: ColorSchema,
align: z.enum(["start", "center", "end"]).optional(),
+ direction: z.enum(["ltr", "rtl", "auto"]).optional(),
verticalAlign: z.enum(["top", "middle", "bottom"]).optional(),
lineHeight: z.number().positive().optional(),
letterSpacing: z.number().optional(),
diff --git a/packages/core/src/types/video/base-layer-schema.ts b/packages/core/src/types/video/base-layer-schema.ts
index be9f449c..619db06a 100644
--- a/packages/core/src/types/video/base-layer-schema.ts
+++ b/packages/core/src/types/video/base-layer-schema.ts
@@ -54,6 +54,8 @@ export const VideoTextPropsSchema = z.object({
fontWeight: z.union([z.number(), z.string()]).optional(),
fill: z.string().optional(),
align: z.string().optional(),
+ /** Paragraph base direction: "ltr", "rtl" or "auto" (from the text). */
+ direction: z.enum(["ltr", "rtl", "auto"]).optional(),
verticalAlign: z.string().optional(),
letterSpacing: z.number().optional(),
lineHeight: z.number().optional(),
diff --git a/packages/framefields/src/fonts/manager.ts b/packages/framefields/src/fonts/manager.ts
index 44605a92..30667877 100644
--- a/packages/framefields/src/fonts/manager.ts
+++ b/packages/framefields/src/fonts/manager.ts
@@ -172,6 +172,8 @@ export interface MeasureTextOptions {
/** Wrap width in px; omit for one line per `\n`. */
width?: number;
align?: "left" | "center" | "right";
+ /** Paragraph base direction, as on `Layer.text`. Default "auto". */
+ direction?: "ltr" | "rtl" | "auto";
}
export interface MeasuredGlyph {
@@ -185,6 +187,8 @@ export interface MeasuredGlyph {
/** Advance width in px. */
width: number;
line: number;
+ /** Part of a right-to-left run: reading continues to the left. */
+ rtl?: boolean;
}
export interface TextMetrics {
@@ -196,7 +200,8 @@ export interface TextMetrics {
glyphs: MeasuredGlyph[];
/**
* X of a caret placed after `count` characters (0 = before the first),
- * relative to the text box. Pair with a `.keys("text", …)` reveal to make
+ * relative to the text box. In right-to-left text the caret sits on the
+ * left of the last character. Pair with a `.keys("text", …)` reveal to make
* a cursor follow typing exactly.
*/
caretX(count: number): number;
@@ -285,29 +290,46 @@ export class FontManager {
letterSpacing,
lineHeight,
options.width,
+ undefined,
+ options.direction,
);
const scale = fontSize / font.unitsPerEm;
- // Map glyphs back to string indices (layout counts graphemes).
+ // One entry per cluster (a letter with its marks, or a ligature), in
+ // reading order; textIndex maps it back to the string.
const glyphs: MeasuredGlyph[] = [];
+ const seen = new Set<number>();
let cursor = 0;
for (const g of layout.glyphs) {
- const at = text.indexOf(g.char, cursor);
- const index = at >= 0 ? at : cursor;
+ let index = g.textIndex;
+ if (index === undefined) {
+ const at = text.indexOf(g.char, cursor);
+ index = at >= 0 ? at : cursor;
+ }
+ if (seen.has(index)) continue;
+ seen.add(index);
cursor = index + g.char.length;
+ const advance =
+ g.clusterAdvance ?? g.cp.advanceWidth * (g.fontScale ?? scale);
glyphs.push({
char: g.char,
index,
- x: g.x,
+ x: g.clusterX ?? g.x,
y: g.y,
- width: g.cp.advanceWidth * (g.fontScale ?? scale) + letterSpacing,
+ width: advance + letterSpacing,
line: g.lineIndex,
+ ...(g.rtl && { rtl: true }),
});
}
const caretX = (count: number): number => {
- if (count <= 0 || glyphs.length === 0) return glyphs[0]?.x ?? 0;
+ if (count <= 0 || glyphs.length === 0) {
+ const first = glyphs[0];
+ if (!first) return 0;
+ return first.rtl ? first.x + first.width - letterSpacing : first.x;
+ }
const before = glyphs.filter((g) => g.index < count);
const last = before[before.length - 1];
- return last ? last.x + last.width - letterSpacing : 0;
+ if (!last) return 0;
+ return last.rtl ? last.x : last.x + last.width - letterSpacing;
};
return {
width,
diff --git a/packages/renderers/src/text-measurer.ts b/packages/renderers/src/text-measurer.ts
index 99ab85cb..cf3b2e02 100644
--- a/packages/renderers/src/text-measurer.ts
+++ b/packages/renderers/src/text-measurer.ts
@@ -11,6 +11,7 @@ export interface TextMeasureStyle {
lineHeight?: number;
padding?: number;
align?: "left" | "center" | "right";
+ direction?: "ltr" | "rtl" | "auto";
width?: number;
height?: number;
autoDimensions?: boolean;
@@ -109,6 +110,7 @@ export function measureText(
? Math.max(0, style.width - padding * 2)
: undefined,
style.spans,
+ style.direction,
);
const result = {
diff --git a/packages/webgpu-renderers/package.json b/packages/webgpu-renderers/package.json
index e745e929..3abff91c 100644
--- a/packages/webgpu-renderers/package.json
+++ b/packages/webgpu-renderers/package.json
@@ -45,6 +45,7 @@
"@framefields/core": "workspace:*",
"@lottiefiles/dotlottie-web": "^0.74.0",
"@resvg/resvg-js": "^2.6.2",
+ "bidi-js": "^1.0.3",
"earcut": "^3.2.4",
"fontkit": "^2.0.4",
"gifuct-js": "^2.1.2",
diff --git a/packages/webgpu-renderers/src/nodes/caption.ts b/packages/webgpu-renderers/src/nodes/caption.ts
index 3d611cb9..10eb695c 100644
--- a/packages/webgpu-renderers/src/nodes/caption.ts
+++ b/packages/webgpu-renderers/src/nodes/caption.ts
@@ -318,6 +318,8 @@ export async function drawCaptionNode(
letterSpacing,
calculatedLineHeight,
maxWidth,
+ undefined,
+ props.direction,
);
const finalWidth = measured.width;
@@ -327,10 +329,22 @@ export async function drawCaptionNode(
const rectHeight = finalHeight + padding * 2;
const align = props.align ?? "center";
+ // "start"/"end" follow the caption's direction (right/left for RTL text).
+ const rtl = measured.layout?.glyphs[0]?.baseRtl ?? props.direction === "rtl";
+ const boxAlign =
+ align === "start"
+ ? rtl
+ ? "right"
+ : "left"
+ : align === "end"
+ ? rtl
+ ? "left"
+ : "right"
+ : align;
let rectX = 0;
- if (align === "center") {
+ if (boxAlign === "center") {
rectX = Math.max(0, (containerWidth - rectWidth) / 2);
- } else if (align === "right") {
+ } else if (boxAlign === "right") {
rectX = Math.max(0, containerWidth - rectWidth);
}
diff --git a/packages/webgpu-renderers/src/nodes/paragraph.ts b/packages/webgpu-renderers/src/nodes/paragraph.ts
index 88130522..178227dd 100644
--- a/packages/webgpu-renderers/src/nodes/paragraph.ts
+++ b/packages/webgpu-renderers/src/nodes/paragraph.ts
@@ -4,12 +4,13 @@ import type { RenderContextValue } from "../render-context.js";
import type { Color } from "../renderer2d/index.js";
import { signalRegistry } from "../signals/signal-registry.js";
import { parseFontWeight, SlugFontCache } from "../slug/slug-font-cache.js";
+import { SlugGenerator } from "../slug/slug-generator.js";
import {
SlugGeometry,
type SlugGlyphLayout,
type SlugLayoutResult,
} from "../slug/slug-geometry.js";
-import type { SlugFont } from "../slug/slug-loader.js";
+import type { SlugCodePoint, SlugFont } from "../slug/slug-loader.js";
import {
type AdvancedTextAnimator,
type AETextAnimator,
@@ -936,7 +937,8 @@ export function drawParagraphNode(
props.lineHeight !== undefined && props.lineHeight < 10
? props.lineHeight * fontSize
: (props.lineHeight ?? fontSize * 1.2);
- const align = props.align ?? "left";
+ const align = props.align ?? "start";
+ const direction = props.direction ?? "auto";
const padding = props.isCaption
? 0
@@ -999,6 +1001,7 @@ export function drawParagraphNode(
lineHeight,
maxWidth,
props.spans,
+ direction,
);
} else {
measured = SlugGeometry.measure(
@@ -1009,14 +1012,16 @@ export function drawParagraphNode(
lineHeight,
undefined,
props.spans,
+ direction,
);
maxWidth = measured.width;
}
const alignWidth = props.isCaption ? props.dstRect.width : maxWidth;
const animApplyBy = props.animation?.applyBy ?? "word";
+ // measure() lays out left-aligned; "start" is the same for LTR text.
const canReuseMeasured =
- align === "left" &&
+ (align === "left" || (align === "start" && !measured.layout?.hasRtl)) &&
(alignWidth === undefined || alignWidth === maxWidth) &&
!pathOptions &&
animApplyBy === "word" &&
@@ -1037,6 +1042,7 @@ export function drawParagraphNode(
alignWidth,
pathOptions,
props.spans,
+ direction,
);
// verticalAlign places the text block inside a box taller than it (CSS
// line-box centring). Path text follows its path; captions place themselves.
@@ -1297,10 +1303,26 @@ export function drawParagraphNode(
list.push(gIdx);
}
- for (const indices of lineGlyphIndices.values()) {
+ for (const lineIndices of lineGlyphIndices.values()) {
+ // Track whole clusters (a letter and its marks) in display order,
+ // which differs from reading order on right-to-left lines.
+ const clusterMap = new Map<number, number[]>();
+ for (const gIdx of lineIndices) {
+ const key = layout.glyphs[gIdx].charIndex;
+ const members = clusterMap.get(key);
+ if (members) members.push(gIdx);
+ else clusterMap.set(key, [gIdx]);
+ }
+ const clusters = Array.from(clusterMap.values());
+ const clusterX = (c: number[]) => {
+ const g = layout.glyphs[c[0]];
+ return g.clusterX ?? g.x;
+ };
+ clusters.sort((a, b) => clusterX(a) - clusterX(b));
+
const weights: number[] = [];
- for (const gIdx of indices) {
- const g = layout.glyphs[gIdx];
+ for (const members of clusters) {
+ const g = layout.glyphs[members[0]];
const w = evaluateAEAnimatorWeight(
aeAnim,
g,
@@ -1313,21 +1335,31 @@ export function drawParagraphNode(
}
let totalLineShift = 0;
- for (let k = 0; k < indices.length - 1; k++) {
+ for (let k = 0; k < clusters.length - 1; k++) {
totalLineShift += trackingAmount * weights[k];
}
+ const baseRtl = layout.glyphs[lineIndices[0]]?.baseRtl ?? false;
+ const lineAlign =
+ align === "start"
+ ? baseRtl
+ ? "right"
+ : "left"
+ : align === "end"
+ ? baseRtl
+ ? "left"
+ : "right"
+ : align;
let cumShift = 0;
- for (let k = 0; k < indices.length; k++) {
- const gIdx = indices[k];
+ for (let k = 0; k < clusters.length; k++) {
let shift = cumShift;
- if (align === "center") {
+ if (lineAlign === "center") {
shift -= totalLineShift * 0.5;
- } else if (align === "right" || align === "end") {
+ } else if (lineAlign === "right") {
shift -= totalLineShift;
}
- trackingShifts[gIdx] += shift;
- if (k < indices.length - 1) {
+ for (const gIdx of clusters[k]) trackingShifts[gIdx] += shift;
+ if (k < clusters.length - 1) {
cumShift += trackingAmount * weights[k];
}
}
@@ -1339,6 +1371,43 @@ export function drawParagraphNode(
let scratchData = new Float32Array(Math.max(1024, instanceCount * 24));
+ // Stroke and synthetic-bold variants are separate fonts of the same family:
+ // they share glyph ids, so shaped glyphs carry over by id. Glyphs from
+ // another family (a span's font) fall back to their code point.
+ const sharesGlyphIds = (target: SlugFont, glyph: SlugGlyphLayout) =>
+ glyph.cp.glyphId !== undefined &&
+ (glyph.font ?? slugFont).fontFamily === target.fontFamily;
+ const preparedFonts = new Set<SlugFont>();
+ const prepareGlyphs = (target: SlugFont) => {
+ if (preparedFonts.has(target)) return;
+ preparedFonts.add(target);
+ const missing: number[] = [];
+ for (const g of layout.glyphs) {
+ const id = g.cp.glyphId;
+ if (
+ id !== undefined &&
+ (g.font ?? slugFont) !== target &&
+ sharesGlyphIds(target, g) &&
+ !target.glyphs?.has(id)
+ ) {
+ missing.push(id);
+ }
+ }
+ // One batch, so the variant's textures are re-uploaded at most once.
+ if (missing.length > 0) SlugGenerator.ensureGlyphs(target, missing);
+ };
+ const glyphInFont = (
+ target: SlugFont,
+ glyph: SlugGlyphLayout,
+ ): SlugCodePoint => {
+ if ((glyph.font ?? slugFont) === target) return glyph.cp;
+ if (sharesGlyphIds(target, glyph)) {
+ const byId = target.glyphs?.get(glyph.cp.glyphId as number);
+ if (byId) return byId;
+ }
+ return target.codePoints.get(glyph.cp.codePoint) || glyph.cp;
+ };
+
const buildInstanceData = (
targetFont: SlugFont,
colorOverride?: Color,
@@ -1353,6 +1422,7 @@ export function drawParagraphNode(
}
const data = scratchData;
let visibleCount = 0;
+ prepareGlyphs(targetFont);
for (let i = 0; i < layout.glyphs.length; i++) {
const glyph = layout.glyphs[i];
@@ -1364,7 +1434,7 @@ export function drawParagraphNode(
continue;
}
- const cp = targetFont.codePoints.get(glyph.cp.codePoint) || glyph.cp;
+ const cp = glyphInFont(targetFont, glyph);
if (!cp || cp.width === 0 || cp.height === 0) {
continue;
}
@@ -1973,10 +2043,23 @@ export function drawParagraphNode(
let cursorY = textRect.y + padding;
if (layout.glyphs.length > 0) {
+ // Glyphs are in reading order: the cursor follows the last one, on
+ // its left when that text runs right to left.
const lastG = layout.glyphs[layout.glyphs.length - 1];
const fontScale = fontSize / slugFont.unitsPerEm;
- const adv = (lastG.cp?.advanceWidth || 0) * fontScale;
- cursorX = lastG.x + props.dstRect.x + padding + adv + cursorSpacing;
+ const adv =
+ lastG.clusterAdvance ?? (lastG.cp?.advanceWidth || 0) * fontScale;
+ const left = lastG.clusterX ?? lastG.x;
+ const barWidth =
+ cursorCfg.style === "underscore" || cursorCfg.style === "block"
+ ? fontSize * 0.5
+ : cursorWidth;
+ cursorX =
+ props.dstRect.x +
+ padding +
+ (lastG.rtl
+ ? left - cursorSpacing - barWidth
+ : left + adv + cursorSpacing);
cursorY = lastG.y + textRect.y + padding;
}
diff --git a/packages/webgpu-renderers/src/nodes/types.ts b/packages/webgpu-renderers/src/nodes/types.ts
index 411438c8..bd97a0e0 100644
--- a/packages/webgpu-renderers/src/nodes/types.ts
+++ b/packages/webgpu-renderers/src/nodes/types.ts
@@ -116,8 +116,13 @@ export interface ParagraphNodeProps {
opacity?: number;
matrix?: DOMMatrix;
lineHeight?: number;
- /** "start"/"end" follow the line direction (left/right for LTR text) */
+ /** "start"/"end" follow the paragraph direction (left/right for LTR text) */
align?: TextAlign | "start" | "end";
+ /**
+ * Base direction of each paragraph. "auto" (default) takes it from the
+ * first strong character, so Arabic or Hebrew text reads right to left.
+ */
+ direction?: "ltr" | "rtl" | "auto";
fontWeight?: number | string;
fontStyle?: "normal" | "italic";
letterSpacing?: number;
diff --git a/packages/webgpu-renderers/src/slug/bidi-js.d.ts b/packages/webgpu-renderers/src/slug/bidi-js.d.ts
new file mode 100644
index 00000000..0773805a
--- /dev/null
+++ b/packages/webgpu-renderers/src/slug/bidi-js.d.ts
@@ -0,0 +1,21 @@
+declare module "bidi-js" {
+ interface EmbeddingLevels {
+ levels: Uint8Array;
+ paragraphs: Array<{ start: number; end: number; level: number }>;
+ }
+ interface Bidi {
+ getEmbeddingLevels(
+ text: string,
+ explicitDirection?: "ltr" | "rtl",
+ ): EmbeddingLevels;
+ getReorderSegments(
+ text: string,
+ embeddingLevels: EmbeddingLevels,
+ start?: number,
+ end?: number,
+ ): Array<[number, number]>;
+ getMirroredCharacter(char: string): string | null;
+ getBidiCharTypeName(char: string): string;
+ }
+ export default function bidiFactory(): Bidi;
+}
diff --git a/packages/webgpu-renderers/src/slug/index.ts b/packages/webgpu-renderers/src/slug/index.ts
index 0b02af04..d5fb453c 100644
--- a/packages/webgpu-renderers/src/slug/index.ts
+++ b/packages/webgpu-renderers/src/slug/index.ts
@@ -10,3 +10,4 @@ export { SlugGeometry } from "./slug-geometry.js";
export type { SlugCodePoint, SlugFont } from "./slug-loader.js";
export { SlugLoader } from "./slug-loader.js";
export { type SlugGlyphBatch, SlugPipeline } from "./slug-pipeline.js";
+export type { TextDirection } from "./text-shaping.js";
diff --git a/packages/webgpu-renderers/src/slug/slug-font-cache.ts b/packages/webgpu-renderers/src/slug/slug-font-cache.ts
index ae5c677d..57c29079 100644
--- a/packages/webgpu-renderers/src/slug/slug-font-cache.ts
+++ b/packages/webgpu-renderers/src/slug/slug-font-cache.ts
@@ -1,7 +1,7 @@
import * as fontkit from "fontkit";
import { debugLog } from "../debug-log.js";
import type { FontkitFont } from "./slug-generator.js";
-import { SlugGenerator } from "./slug-generator.js";
+import { SlugGenerator, uploadSlugTextures } from "./slug-generator.js";
import type { SlugFont } from "./slug-loader.js";
export type FontLoadListener = (fontFamily: string) => void;
@@ -69,53 +69,7 @@ function parseFontBuffer(bytes: Uint8Array): FontkitFont {
function recreateTextures(device: GPUDevice, slugFont: SlugFont): void {
if (slugFont.curvesTex) return;
- const raw = (slugFont as any)._raw;
- if (!raw) return;
-
- const TEXTURE_WIDTH = 4096;
- const curvesTexels = Math.ceil(raw.curvesList.length / 4);
- const curvesTexHeight = Math.max(1, Math.ceil(curvesTexels / TEXTURE_WIDTH));
-
- const curvesFloatArray = new Float32Array(
- TEXTURE_WIDTH * curvesTexHeight * 4,
- );
- curvesFloatArray.fill(-1.0);
- curvesFloatArray.set(raw.curvesList);
-
- slugFont.curvesTex = device.createTexture({
- label: "SlugGeneratedCurvesTexture",
- size: [TEXTURE_WIDTH, curvesTexHeight],
- format: "rgba32float",
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
- });
- device.queue.writeTexture(
- { texture: slugFont.curvesTex },
- curvesFloatArray,
- { bytesPerRow: TEXTURE_WIDTH * 16 },
- [TEXTURE_WIDTH, curvesTexHeight],
- );
-
- const bandsTexels =
- Math.floor(raw.bandOffsets.length / 2) +
- Math.floor(raw.curveOffsets.length / 2);
- const bandsTexHeight = Math.max(1, Math.ceil(bandsTexels / TEXTURE_WIDTH));
-
- const bandsUintArray = new Uint32Array(TEXTURE_WIDTH * bandsTexHeight * 2);
- bandsUintArray.set(raw.bandOffsets, 0);
- bandsUintArray.set(raw.curveOffsets, raw.bandOffsets.length);
-
- slugFont.bandsTex = device.createTexture({
- label: "SlugGeneratedBandsTexture",
- size: [TEXTURE_WIDTH, bandsTexHeight],
- format: "rg32uint",
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
- });
- device.queue.writeTexture(
- { texture: slugFont.bandsTex },
- bandsUintArray,
- { bytesPerRow: TEXTURE_WIDTH * 8 },
- [TEXTURE_WIDTH, bandsTexHeight],
- );
+ uploadSlugTextures(device, slugFont);
}
const GLOBAL_CACHE_KEY = Symbol.for("gatewai.slugFontCache.cache");
diff --git a/packages/webgpu-renderers/src/slug/slug-generator.ts b/packages/webgpu-renderers/src/slug/slug-generator.ts
index 53d7ce93..e1bf46ab 100644
--- a/packages/webgpu-renderers/src/slug/slug-generator.ts
+++ b/packages/webgpu-renderers/src/slug/slug-generator.ts
@@ -1,7 +1,13 @@
-import type { SlugCodePoint, SlugFont } from "./slug-loader.js";
+import {
+ type SlugCodePoint,
+ type SlugFont,
+ UNMAPPED_CODE_POINT,
+} from "./slug-loader.js";
export interface FontkitGlyph {
+ id: number;
codePoints: number[];
+ isMark?: boolean;
advanceWidth: number;
bbox: {
minX: number;
@@ -34,14 +40,25 @@ export interface FontkitFont {
variationAxes?: Record<string, unknown>;
getVariation?(settings: Record<string, number>): FontkitFont;
/** Shapes a string (kerning, ligatures); fontkit fonts always have it. */
- layout?(text: string): {
- glyphs: unknown[];
- positions: Array<{ xAdvance: number }>;
+ layout?(
+ text: string,
+ features?: string[] | Record<string, boolean>,
+ script?: string,
+ language?: string,
+ direction?: "ltr" | "rtl",
+ ): {
+ glyphs: FontkitGlyph[];
+ positions: Array<{
+ xAdvance: number;
+ yAdvance: number;
+ xOffset: number;
+ yOffset: number;
+ }>;
};
}
const TEXTURE_WIDTH = 4096;
-const SLUGGISH_HEADER_DATA = "SLUGGISH";
+const SLUGGISH_HEADER_DATA_V2 = "SLUGGIS2";
export interface SlugGeneratorOptions {
bandCount?: number;
@@ -400,6 +417,112 @@ function offsetGlyphPath(
return { commands };
}
+/**
+ * The growing curve/band data of one generated font. Band offsets are kept
+ * relative to the curve-offset region; they are rebased onto the band header
+ * each time the raw arrays are rebuilt, so glyphs can be appended later.
+ */
+interface GlyphAtlas {
+ source: FontkitFont;
+ strokeWidth?: number;
+ bandCount: number;
+ curves: number[];
+ bandOffsets: number[];
+ curveOffsets: number[];
+ /** GPU device the textures were last uploaded with. */
+ device: GPUDevice | null;
+}
+
+const atlases = new WeakMap<SlugFont, GlyphAtlas>();
+
+/** The fontkit font a generated Slug font was built from (null for loaded binaries). */
+export function getSlugFontSource(font: SlugFont): FontkitFont | null {
+ return atlases.get(font)?.source ?? null;
+}
+
+function rebuildRaw(font: SlugGeneratorOutput, atlas: GlyphAtlas): void {
+ const headerTexels = Math.floor(atlas.bandOffsets.length / 2);
+ const bandOffsets = atlas.bandOffsets.slice();
+ for (let k = 1; k < bandOffsets.length; k += 2) {
+ bandOffsets[k] += headerTexels;
+ }
+ font._raw.bandOffsets = bandOffsets;
+ font._raw.curvesList = atlas.curves;
+ font._raw.curveOffsets = atlas.curveOffsets;
+}
+
+/**
+ * Uploads a generated font's curve and band data to fresh textures. The old
+ * textures are left to the garbage collector: draws already encoded this
+ * frame may still reference them.
+ */
+export function uploadSlugTextures(device: GPUDevice, font: SlugFont): void {
+ const raw = (font as Partial<SlugGeneratorOutput>)._raw;
+ if (!raw) return;
+
+ const curvesTexels = Math.ceil(raw.curvesList.length / 4);
+ const curvesTexHeight = Math.max(1, Math.ceil(curvesTexels / TEXTURE_WIDTH));
+ const curvesFloatArray = new Float32Array(
+ TEXTURE_WIDTH * curvesTexHeight * 4,
+ );
+ curvesFloatArray.fill(-1.0);
+ curvesFloatArray.set(raw.curvesList);
+
+ const curvesTex = device.createTexture({
+ label: "SlugGeneratedCurvesTexture",
+ size: [TEXTURE_WIDTH, curvesTexHeight],
+ format: "rgba32float",
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
+ });
+ device.queue.writeTexture(
+ { texture: curvesTex },
+ curvesFloatArray,
+ { bytesPerRow: TEXTURE_WIDTH * 16 },
+ [TEXTURE_WIDTH, curvesTexHeight],
+ );
+
+ const bandsTexels =
+ Math.floor(raw.bandOffsets.length / 2) +
+ Math.floor(raw.curveOffsets.length / 2);
+ const bandsTexHeight = Math.max(1, Math.ceil(bandsTexels / TEXTURE_WIDTH));
+ const bandsUintArray = new Uint32Array(TEXTURE_WIDTH * bandsTexHeight * 2);
+ bandsUintArray.set(raw.bandOffsets, 0);
+ bandsUintArray.set(raw.curveOffsets, raw.bandOffsets.length);
+
+ const bandsTex = device.createTexture({
+ label: "SlugGeneratedBandsTexture",
+ size: [TEXTURE_WIDTH, bandsTexHeight],
+ format: "rg32uint",
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
+ });
+ device.queue.writeTexture(
+ { texture: bandsTex },
+ bandsUintArray,
+ { bytesPerRow: TEXTURE_WIDTH * 8 },
+ [TEXTURE_WIDTH, bandsTexHeight],
+ );
+
+ font.curvesTex = curvesTex;
+ font.bandsTex = bandsTex;
+ const atlas = atlases.get(font);
+ if (atlas) atlas.device = device;
+}
+
+/** Default code points generated up front; anything else is generated on first use. */
+function isDefaultCodePoint(cp: number): boolean {
+ return (
+ (cp >= 32 && cp <= 126) || // ASCII Printable
+ (cp >= 160 && cp <= 255) || // Latin-1 Supplement (é, ü, ©, ®, etc.)
+ (cp >= 0x0100 && cp <= 0x024f) || // Latin Extended-A & B
+ (cp >= 0x2000 && cp <= 0x206f) || // General Punctuation (• bullet U+2022, —, –, ‘, ’, “, ”, …, etc.)
+ (cp >= 0x20a0 && cp <= 0x20cf) || // Currency Symbols (€, £, etc.)
+ (cp >= 0x2100 && cp <= 0x214f) || // Letterlike Symbols (™, etc.)
+ (cp >= 0x2190 && cp <= 0x21ff) || // Arrows (←, ↑, →, ↓, etc.)
+ (cp >= 0x2200 && cp <= 0x22ff) || // Mathematical Operators (≠, ≤, ≥, etc.)
+ (cp >= 0x2600 && cp <= 0x27bf) // Misc Symbols & Dingbats (✦, ★, ⚡, etc.)
+ );
+}
+
export class SlugGenerator {
private bandCount = 16;
private fullRange = false;
@@ -420,29 +543,21 @@ export class SlugGenerator {
"[SlugGenerator] Cannot generate slug font: font is null or undefined",
);
}
- const curvesTexData: number[] = [];
- const bandsTexBandOffsets: number[] = [];
- const bandsTexCurveOffsets: number[] = [];
- const codePointsData: SlugCodePoint[] = [];
+ const atlas: GlyphAtlas = {
+ source: font,
+ strokeWidth: this.strokeWidth,
+ bandCount: this.bandCount,
+ curves: [],
+ bandOffsets: [],
+ curveOffsets: [],
+ device: null,
+ };
const charSet = Array.isArray(font.characterSet)
? font.characterSet
: Array.from(font.characterSet || []);
const charSetSet = new Set(charSet);
- const getGlyphFn =
- typeof font.getGlyph === "function"
- ? font.getGlyph.bind(font)
- : typeof font.glyphForCodePoint === "function"
- ? font.glyphForCodePoint.bind(font)
- : null;
- const glyphForCodePointFn =
- typeof font.glyphForCodePoint === "function"
- ? font.glyphForCodePoint.bind(font)
- : typeof font.getGlyph === "function"
- ? font.getGlyph.bind(font)
- : null;
-
const codePointsToProcess: number[] = [-1]; // Start with .notdef fallback
if (this.fullRange) {
for (const cp of charSet) {
@@ -450,482 +565,501 @@ export class SlugGenerator {
codePointsToProcess.push(cp);
}
}
- } else {
- if (this.whitelist) {
- for (const cp of this.whitelist) {
- if (charSetSet.has(cp)) {
- codePointsToProcess.push(cp);
- }
+ } else if (this.whitelist) {
+ for (const cp of this.whitelist) {
+ if (charSetSet.has(cp)) {
+ codePointsToProcess.push(cp);
}
- } else {
- for (const cp of charSet) {
- if (cp === -1) continue;
- if (
- (cp >= 32 && cp <= 126) || // ASCII Printable
- (cp >= 160 && cp <= 255) || // Latin-1 Supplement (é, ü, ©, ®, etc.)
- (cp >= 0x0100 && cp <= 0x024f) || // Latin Extended-A & B
- (cp >= 0x2000 && cp <= 0x206f) || // General Punctuation (• bullet U+2022, —, –, ‘, ’, “, ”, …, etc.)
- (cp >= 0x20a0 && cp <= 0x20cf) || // Currency Symbols (€, £, etc.)
- (cp >= 0x2100 && cp <= 0x214f) || // Letterlike Symbols (™, etc.)
- (cp >= 0x2190 && cp <= 0x21ff) || // Arrows (←, ↑, →, ↓, etc.)
- (cp >= 0x2200 && cp <= 0x22ff) || // Mathematical Operators (≠, ≤, ≥, etc.)
- (cp >= 0x2600 && cp <= 0x27bf) // Misc Symbols & Dingbats (✦, ★, ⚡, etc.)
- ) {
- codePointsToProcess.push(cp);
- }
+ }
+ } else {
+ for (const cp of charSet) {
+ if (cp !== -1 && isDefaultCodePoint(cp)) {
+ codePointsToProcess.push(cp);
}
}
}
+ const output = this.buildOutput(font);
+ atlases.set(output, atlas);
for (const cp of codePointsToProcess) {
+ SlugGenerator.addCodePoint(output, atlas, cp);
+ }
+ rebuildRaw(output, atlas);
+ if (device) uploadSlugTextures(device, output);
+ return output;
+ }
+
+ /**
+ * Generates any of `glyphIds` the font does not have yet, and re-uploads
+ * its textures if it already had some. Returns whether anything was added.
+ * Fonts not built by this generator (e.g. loaded binaries) are left as is.
+ */
+ static ensureGlyphs(font: SlugFont, glyphIds: Iterable<number>): boolean {
+ const atlas = atlases.get(font);
+ if (!atlas || typeof atlas.source.getGlyph !== "function") return false;
+ const out = font as SlugGeneratorOutput;
+ out.glyphs ??= new Map();
+ let added = false;
+ for (const id of glyphIds) {
+ if (out.glyphs.has(id)) continue;
let glyph: FontkitGlyph | null = null;
try {
- glyph =
- cp === -1
- ? getGlyphFn
- ? getGlyphFn(0)
- : null
- : glyphForCodePointFn
- ? glyphForCodePointFn(cp)
- : null;
+ glyph = atlas.source.getGlyph(id);
} catch {
- continue;
+ glyph = null;
}
- if (!glyph) {
- continue;
+ const record = glyph
+ ? SlugGenerator.buildGlyph(atlas, glyph, UNMAPPED_CODE_POINT, id)
+ : null;
+ // Remember failures too, so a broken glyph is not retried every frame.
+ const entry =
+ record ?? SlugGenerator.emptyRecord(UNMAPPED_CODE_POINT, id, 0);
+ out.glyphs.set(id, entry);
+ out._raw.codePoints.push(entry);
+ added = true;
+ }
+ if (added) SlugGenerator.commit(out, atlas);
+ return added;
+ }
+
+ /** Like {@link ensureGlyphs}, for code points looked up through the cmap. */
+ static ensureCodePoints(
+ font: SlugFont,
+ codePoints: Iterable<number>,
+ ): boolean {
+ const atlas = atlases.get(font);
+ if (!atlas) return false;
+ const out = font as SlugGeneratorOutput;
+ let added = false;
+ for (const cp of codePoints) {
+ if (out.codePoints.has(cp)) continue;
+ if (SlugGenerator.addCodePoint(out, atlas, cp)) added = true;
+ }
+ if (added) SlugGenerator.commit(out, atlas);
+ return added;
+ }
+
+ private static commit(font: SlugGeneratorOutput, atlas: GlyphAtlas): void {
+ rebuildRaw(font, atlas);
+ if (font.curvesTex && atlas.device) {
+ uploadSlugTextures(atlas.device, font);
+ }
+ }
+
+ /** Maps a code point (or -1 for .notdef) to a glyph record, generating it once per glyph id. */
+ private static addCodePoint(
+ font: SlugGeneratorOutput,
+ atlas: GlyphAtlas,
+ cp: number,
+ ): boolean {
+ const src = atlas.source;
+ let glyph: FontkitGlyph | null = null;
+ try {
+ if (cp === -1) {
+ glyph =
+ typeof src.getGlyph === "function"
+ ? src.getGlyph(0)
+ : (src.glyphForCodePoint?.(0) ?? null);
+ } else {
+ glyph = src.glyphForCodePoint?.(cp) ?? null;
}
+ } catch {
+ return false;
+ }
+ if (!glyph) return false;
+ // A code point the font lacks maps to glyph 0; let .notdef stand in.
+ if (cp !== -1 && glyph.id === 0) return false;
+
+ font.glyphs ??= new Map();
+ const glyphId = typeof glyph.id === "number" ? glyph.id : undefined;
+ const shared = glyphId !== undefined ? font.glyphs.get(glyphId) : undefined;
+ if (shared) {
+ // Another code point already produced this glyph: alias it.
+ const alias = { ...shared, codePoint: cp };
+ font.codePoints.set(cp, alias);
+ font._raw.codePoints.push(alias);
+ return true;
+ }
+ const record = SlugGenerator.buildGlyph(atlas, glyph, cp, glyphId);
+ if (!record) return false;
+ font.codePoints.set(cp, record);
+ if (glyphId !== undefined) font.glyphs.set(glyphId, record);
+ font._raw.codePoints.push(record);
+ return true;
+ }
- let path: any;
- let bbox: any;
- let advanceWidth = 0;
+ private static emptyRecord(
+ codePoint: number,
+ glyphId: number | undefined,
+ advanceWidth: number,
+ ): SlugCodePoint {
+ return {
+ codePoint,
+ glyphId,
+ width: 0,
+ height: 0,
+ advanceWidth,
+ bearingX: 0,
+ bearingY: 0,
+ bandCount: 0,
+ bandDimX: 0,
+ bandDimY: 0,
+ bandsTexCoordX: 0,
+ bandsTexCoordY: 0,
+ };
+ }
+
+ /** Writes one glyph's curves and bands into the atlas and returns its record. */
+ private static buildGlyph(
+ a: GlyphAtlas,
+ glyph: FontkitGlyph,
+ codePoint: number,
+ glyphId: number | undefined,
+ ): SlugCodePoint | null {
+ let path: any;
+ let bbox: any;
+ let advanceWidth = 0;
+ try {
+ path = glyph.path;
+ bbox = glyph.bbox;
try {
- path = glyph.path;
- bbox = glyph.bbox;
- try {
- advanceWidth = Math.floor(glyph.advanceWidth || 0);
- } catch {
- advanceWidth = 0;
- }
+ advanceWidth = Math.floor(glyph.advanceWidth || 0);
} catch {
- continue;
+ advanceWidth = 0;
}
+ } catch {
+ return null;
+ }
- if (
- !bbox ||
- bbox.minX === bbox.maxX ||
- bbox.minY === bbox.maxY ||
- bbox.minX === Infinity ||
- bbox.minY === Infinity ||
- !path ||
- !path.commands ||
- path.commands.length === 0
- ) {
- // Empty glyph (e.g. space) or missing
- codePointsData.push({
- codePoint: cp,
- width: 0,
- height: 0,
- advanceWidth,
- bearingX: 0,
- bearingY: 0,
- bandCount: 0,
- bandDimX: 0,
- bandDimY: 0,
- bandsTexCoordX: 0,
- bandsTexCoordY: 0,
- });
- continue;
- }
+ if (
+ !bbox ||
+ bbox.minX === bbox.maxX ||
+ bbox.minY === bbox.maxY ||
+ bbox.minX === Infinity ||
+ bbox.minY === Infinity ||
+ !path ||
+ !path.commands ||
+ path.commands.length === 0
+ ) {
+ // Empty glyph (e.g. space) or missing
+ return {
+ codePoint,
+ glyphId,
+ width: 0,
+ height: 0,
+ advanceWidth,
+ bearingX: 0,
+ bearingY: 0,
+ bandCount: 0,
+ bandDimX: 0,
+ bandDimY: 0,
+ bandsTexCoordX: 0,
+ bandsTexCoordY: 0,
+ };
+ }
+
+ const strokeOffset = a.strokeWidth ? a.strokeWidth / 2 : 0;
+ const pathCommands =
+ a.strokeWidth && a.strokeWidth > 0
+ ? offsetGlyphPath(path, strokeOffset)
+ : path;
+
+ const gx1 = bbox.minX - strokeOffset;
+ const gy1 = bbox.minY - strokeOffset;
+ const gx2 = bbox.maxX + strokeOffset;
+ const gy2 = bbox.maxY + strokeOffset;
+
+ // 1. Build Temporary Curve List
+ const curves: TempCurve[] | null = [];
+ let currentX = 0;
+ let currentY = 0;
+ let firstCurve = false;
+ let startOfShapeX = 0;
+ let startOfShapeY = 0;
+
+ for (let j = 0; j < pathCommands.commands.length; j++) {
+ const cmd = pathCommands.commands[j];
+ const commandType = cmd.command || (cmd as any).type;
+ const args = cmd.args || [];
+
+ if (commandType === "moveTo") {
+ firstCurve = true;
+ const x = args.length >= 2 ? args[0] : (cmd as any).x;
+ const y = args.length >= 2 ? args[1] : (cmd as any).y;
+ currentX = x - gx1;
+ currentY = y - gy1;
+ startOfShapeX = currentX;
+ startOfShapeY = currentY;
+ } else if (commandType === "lineTo") {
+ const x = args.length >= 2 ? args[0] : (cmd as any).x;
+ const y = args.length >= 2 ? args[1] : (cmd as any).y;
+ const nextX = x - gx1;
+ const nextY = y - gy1;
+ const c: TempCurve = {
+ first: firstCurve,
+ x1: currentX,
+ y1: currentY,
+ x3: nextX,
+ y3: nextY,
+ x2: (currentX + nextX) / 2.0,
+ y2: (currentY + nextY) / 2.0,
+ };
+ curves.push(c);
+ firstCurve = false;
+ currentX = nextX;
+ currentY = nextY;
+ } else if (commandType === "quadraticCurveTo") {
+ const cpx =
+ args.length >= 4 ? args[0] : ((cmd as any).cpx ?? (cmd as any).x1);
+ const cpy =
+ args.length >= 4 ? args[1] : ((cmd as any).cpy ?? (cmd as any).y1);
+ const x = args.length >= 4 ? args[2] : (cmd as any).x;
+ const y = args.length >= 4 ? args[3] : (cmd as any).y;
+ const nextX = x - gx1;
+ const nextY = y - gy1;
+ const c: TempCurve = {
+ first: firstCurve,
+ x1: currentX,
+ y1: currentY,
+ x2: cpx - gx1,
+ y2: cpy - gy1,
+ x3: nextX,
+ y3: nextY,
+ };
+ curves.push(c);
+ firstCurve = false;
+ currentX = nextX;
+ currentY = nextY;
+ } else if (commandType === "bezierCurveTo") {
+ const cp1x = args.length >= 6 ? args[0] : (cmd as any).cp1x;
+ const cp1y = args.length >= 6 ? args[1] : (cmd as any).cp1y;
+ const cp2x = args.length >= 6 ? args[2] : (cmd as any).cp2x;
+ const cp2y = args.length >= 6 ? args[3] : (cmd as any).cp2y;
+ const x = args.length >= 6 ? args[4] : (cmd as any).x;
+ const y = args.length >= 6 ? args[5] : (cmd as any).y;
+ const nextX = x - gx1;
+ const nextY = y - gy1;
+
+ // Approximate cubic Bezier with 4 quadratic Bezier segments
+ const segments = 4;
+ let prevX = currentX;
+ let prevY = currentY;
+
+ for (let k = 1; k <= segments; k++) {
+ const t = k / segments;
+ const mt = 1.0 - t;
+ const mt2 = mt * mt;
+ const mt3 = mt2 * mt;
+ const t2 = t * t;
+ const t3 = t2 * t;
+
+ const posX =
+ mt3 * currentX +
+ 3.0 * mt2 * t * (cp1x - gx1) +
+ 3.0 * mt * t2 * (cp2x - gx1) +
+ t3 * nextX;
+ const posY =
+ mt3 * currentY +
+ 3.0 * mt2 * t * (cp1y - gy1) +
+ 3.0 * mt * t2 * (cp2y - gy1) +
+ t3 * nextY;
- const strokeOffset = this.strokeWidth ? this.strokeWidth / 2 : 0;
- const pathCommands =
- this.strokeWidth && this.strokeWidth > 0
- ? offsetGlyphPath(path, strokeOffset)
- : path;
-
- const gx1 = bbox.minX - strokeOffset;
- const gy1 = bbox.minY - strokeOffset;
- const gx2 = bbox.maxX + strokeOffset;
- const gy2 = bbox.maxY + strokeOffset;
-
- // 1. Build Temporary Curve List
- const curves: TempCurve[] | null = [];
- let currentX = 0;
- let currentY = 0;
- let firstCurve = false;
- let startOfShapeX = 0;
- let startOfShapeY = 0;
-
- for (let j = 0; j < pathCommands.commands.length; j++) {
- const cmd = pathCommands.commands[j];
- const commandType = cmd.command || (cmd as any).type;
- const args = cmd.args || [];
-
- if (commandType === "moveTo") {
- firstCurve = true;
- const x = args.length >= 2 ? args[0] : (cmd as any).x;
- const y = args.length >= 2 ? args[1] : (cmd as any).y;
- currentX = x - gx1;
- currentY = y - gy1;
- startOfShapeX = currentX;
- startOfShapeY = currentY;
- } else if (commandType === "lineTo") {
- const x = args.length >= 2 ? args[0] : (cmd as any).x;
- const y = args.length >= 2 ? args[1] : (cmd as any).y;
- const nextX = x - gx1;
- const nextY = y - gy1;
const c: TempCurve = {
- first: firstCurve,
- x1: currentX,
- y1: currentY,
- x3: nextX,
- y3: nextY,
- x2: (currentX + nextX) / 2.0,
- y2: (currentY + nextY) / 2.0,
+ first: firstCurve && k === 1,
+ x1: prevX,
+ y1: prevY,
+ x2: (prevX + posX) / 2.0,
+ y2: (prevY + posY) / 2.0,
+ x3: posX,
+ y3: posY,
};
curves.push(c);
- firstCurve = false;
- currentX = nextX;
- currentY = nextY;
- } else if (commandType === "quadraticCurveTo") {
- const cpx =
- args.length >= 4 ? args[0] : ((cmd as any).cpx ?? (cmd as any).x1);
- const cpy =
- args.length >= 4 ? args[1] : ((cmd as any).cpy ?? (cmd as any).y1);
- const x = args.length >= 4 ? args[2] : (cmd as any).x;
- const y = args.length >= 4 ? args[3] : (cmd as any).y;
- const nextX = x - gx1;
- const nextY = y - gy1;
+ prevX = posX;
+ prevY = posY;
+ }
+
+ firstCurve = false;
+ currentX = nextX;
+ currentY = nextY;
+ } else if (commandType === "closePath") {
+ if (currentX !== startOfShapeX || currentY !== startOfShapeY) {
const c: TempCurve = {
first: firstCurve,
x1: currentX,
y1: currentY,
- x2: cpx - gx1,
- y2: cpy - gy1,
- x3: nextX,
- y3: nextY,
+ x3: startOfShapeX,
+ y3: startOfShapeY,
+ x2: (currentX + startOfShapeX) / 2.0,
+ y2: (currentY + startOfShapeY) / 2.0,
};
curves.push(c);
firstCurve = false;
- currentX = nextX;
- currentY = nextY;
- } else if (commandType === "bezierCurveTo") {
- const cp1x = args.length >= 6 ? args[0] : (cmd as any).cp1x;
- const cp1y = args.length >= 6 ? args[1] : (cmd as any).cp1y;
- const cp2x = args.length >= 6 ? args[2] : (cmd as any).cp2x;
- const cp2y = args.length >= 6 ? args[3] : (cmd as any).cp2y;
- const x = args.length >= 6 ? args[4] : (cmd as any).x;
- const y = args.length >= 6 ? args[5] : (cmd as any).y;
- const nextX = x - gx1;
- const nextY = y - gy1;
-
- // Approximate cubic Bezier with 4 quadratic Bezier segments
- const segments = 4;
- let prevX = currentX;
- let prevY = currentY;
-
- for (let k = 1; k <= segments; k++) {
- const t = k / segments;
- const mt = 1.0 - t;
- const mt2 = mt * mt;
- const mt3 = mt2 * mt;
- const t2 = t * t;
- const t3 = t2 * t;
-
- const posX =
- mt3 * currentX +
- 3.0 * mt2 * t * (cp1x - gx1) +
- 3.0 * mt * t2 * (cp2x - gx1) +
- t3 * nextX;
- const posY =
- mt3 * currentY +
- 3.0 * mt2 * t * (cp1y - gy1) +
- 3.0 * mt * t2 * (cp2y - gy1) +
- t3 * nextY;
-
- const c: TempCurve = {
- first: firstCurve && k === 1,
- x1: prevX,
- y1: prevY,
- x2: (prevX + posX) / 2.0,
- y2: (prevY + posY) / 2.0,
- x3: posX,
- y3: posY,
- };
- curves.push(c);
- prevX = posX;
- prevY = posY;
- }
-
- firstCurve = false;
- currentX = nextX;
- currentY = nextY;
- } else if (commandType === "closePath") {
- if (currentX !== startOfShapeX || currentY !== startOfShapeY) {
- const c: TempCurve = {
- first: firstCurve,
- x1: currentX,
- y1: currentY,
- x3: startOfShapeX,
- y3: startOfShapeY,
- x2: (currentX + startOfShapeX) / 2.0,
- y2: (currentY + startOfShapeY) / 2.0,
- };
- curves.push(c);
- firstCurve = false;
- }
- currentX = startOfShapeX;
- currentY = startOfShapeY;
}
+ currentX = startOfShapeX;
+ currentY = startOfShapeY;
}
+ }
- if (!curves || curves.length === 0) {
- continue;
- }
+ if (!curves || curves.length === 0) {
+ return null;
+ }
- // Fix up curves where the control point is one of the endpoints
- for (const c of curves) {
- if (
- (c.x2 === c.x1 && c.y2 === c.y1) ||
- (c.x2 === c.x3 && c.y2 === c.y3)
- ) {
- c.x2 = (c.x1 + c.x3) / 2.0;
- c.y2 = (c.y1 + c.y3) / 2.0;
- }
+ // Fix up curves where the control point is one of the endpoints
+ for (const c of curves) {
+ if (
+ (c.x2 === c.x1 && c.y2 === c.y1) ||
+ (c.x2 === c.x3 && c.y2 === c.y3)
+ ) {
+ c.x2 = (c.x1 + c.x3) / 2.0;
+ c.y2 = (c.y1 + c.y3) / 2.0;
}
+ }
- const bandsTexelIndex = Math.floor(bandsTexBandOffsets.length / 2);
+ const bandsTexelIndex = Math.floor(a.bandOffsets.length / 2);
- // 2. Write Curves Texture
- for (const c of curves) {
- if (c.first && curvesTexData.length % 4 !== 0) {
- const toAdd = 4 - (curvesTexData.length % 4);
- for (let k = 0; k < toAdd; k++) {
- curvesTexData.push(-1.0);
- }
+ // 2. Write Curves Texture
+ for (const c of curves) {
+ if (c.first && a.curves.length % 4 !== 0) {
+ const toAdd = 4 - (a.curves.length % 4);
+ for (let k = 0; k < toAdd; k++) {
+ a.curves.push(-1.0);
}
-
- const texelCount = Math.floor(curvesTexData.length / 4);
- const col = texelCount % TEXTURE_WIDTH;
- const newRow = col === TEXTURE_WIDTH - 1;
- if (newRow) {
- const toAdd = 8 - (curvesTexData.length % 4);
- for (let k = 0; k < toAdd; k++) {
- curvesTexData.push(-1.0);
- }
- }
-
- if (c.first || newRow) {
- c.texelIndex = Math.floor(curvesTexData.length / 4);
- curvesTexData.push(c.x1, c.y1);
- } else {
- c.texelIndex = Math.floor(
- (Math.floor(curvesTexData.length / 2) - 1) / 2,
- );
- }
-
- curvesTexData.push(c.x2, c.y2);
- curvesTexData.push(c.x3, c.y3);
}
- const sizeX = 1 + (gx2 - gx1);
- const sizeY = 1 + (gy2 - gy1);
- let bCount = this.bandCount;
- if (sizeX < bCount || sizeY < bCount) {
- bCount = Math.floor(Math.min(sizeX, sizeY) / 2);
- if (bCount < 1) {
- bCount = 1;
+ const texelCount = Math.floor(a.curves.length / 4);
+ const col = texelCount % TEXTURE_WIDTH;
+ const newRow = col === TEXTURE_WIDTH - 1;
+ if (newRow) {
+ const toAdd = 8 - (a.curves.length % 4);
+ for (let k = 0; k < toAdd; k++) {
+ a.curves.push(-1.0);
}
}
- const bandDimY = Math.ceil(sizeY / bCount);
- let bandMinY = 0;
- let bandMaxY = bandDimY;
-
- // Sort curves by highest Y (max of y1,y2,y3) descending
- curves.sort(
- (a, b) => Math.max(b.x1, b.x2, b.x3) - Math.max(a.x1, a.x2, a.x3),
- );
-
- for (let b = 0; b < bCount; b++) {
- const bandTexelOffset = Math.floor(bandsTexCurveOffsets.length / 2);
- let curveCount = 0;
-
- for (const c of curves) {
- if (c.y1 === c.y2 && c.y2 === c.y3) {
- continue; // perfectly horizontal
- }
- const curveMinY = Math.min(c.y1, c.y2, c.y3);
- const curveMaxY = Math.max(c.y1, c.y2, c.y3);
- if (curveMinY > bandMaxY || curveMaxY < bandMinY) {
- continue; // doesn't cross band
- }
-
- const texelIndex = c.texelIndex ?? 0;
- const curveOffsetX = texelIndex % TEXTURE_WIDTH;
- const curveOffsetY = Math.floor(texelIndex / TEXTURE_WIDTH);
- bandsTexCurveOffsets.push(curveOffsetX, curveOffsetY);
- curveCount++;
- }
- bandsTexBandOffsets.push(curveCount, bandTexelOffset);
- bandMinY += bandDimY;
- bandMaxY += bandDimY;
+ if (c.first || newRow) {
+ c.texelIndex = Math.floor(a.curves.length / 4);
+ a.curves.push(c.x1, c.y1);
+ } else {
+ c.texelIndex = Math.floor((Math.floor(a.curves.length / 2) - 1) / 2);
}
- // For vertical bands, sort by max Y descending
- const bandDimX = Math.ceil(sizeX / bCount);
- let bandMinX = 0;
- let bandMaxX = bandDimX;
-
- curves.sort(
- (a, b) => Math.max(b.y1, b.y2, b.y3) - Math.max(a.y1, a.y2, a.y3),
- );
+ a.curves.push(c.x2, c.y2);
+ a.curves.push(c.x3, c.y3);
+ }
- for (let b = 0; b < bCount; b++) {
- const bandTexelOffset = Math.floor(bandsTexCurveOffsets.length / 2);
- let curveCount = 0;
-
- for (const c of curves) {
- if (c.x1 === c.x2 && c.x2 === c.x3) {
- continue; // perfectly vertical
- }
- const curveMinX = Math.min(c.x1, c.x2, c.x3);
- const curveMaxX = Math.max(c.x1, c.x2, c.x3);
- if (curveMinX > bandMaxX || curveMaxX < bandMinX) {
- continue; // doesn't cross band
- }
-
- const texelIndex = c.texelIndex ?? 0;
- const curveOffsetX = texelIndex % TEXTURE_WIDTH;
- const curveOffsetY = Math.floor(texelIndex / TEXTURE_WIDTH);
- bandsTexCurveOffsets.push(curveOffsetX, curveOffsetY);
- curveCount++;
- }
- bandsTexBandOffsets.push(curveCount, bandTexelOffset);
- bandMinX += bandDimX;
- bandMaxX += bandDimX;
+ const sizeX = 1 + (gx2 - gx1);
+ const sizeY = 1 + (gy2 - gy1);
+ let bCount = a.bandCount;
+ if (sizeX < bCount || sizeY < bCount) {
+ bCount = Math.floor(Math.min(sizeX, sizeY) / 2);
+ if (bCount < 1) {
+ bCount = 1;
}
-
- codePointsData.push({
- codePoint: cp,
- width: Math.floor(gx2 - gx1),
- height: Math.floor(gy2 - gy1),
- advanceWidth: Math.floor(glyph.advanceWidth || 0),
- bearingX: Math.floor(gx1),
- bearingY: Math.floor(gy2),
- bandCount: bCount,
- bandDimX,
- bandDimY,
- bandsTexCoordX: bandsTexelIndex % TEXTURE_WIDTH,
- bandsTexCoordY: Math.floor(bandsTexelIndex / TEXTURE_WIDTH),
- });
}
- // Post-processing
- const bandHeaderTexels = Math.floor(bandsTexBandOffsets.length / 2);
- for (let k = 1; k < bandsTexBandOffsets.length; k += 2) {
- bandsTexBandOffsets[k] += bandHeaderTexels;
- }
+ const bandDimY = Math.ceil(sizeY / bCount);
+ let bandMinY = 0;
+ let bandMaxY = bandDimY;
- return this.buildOutput(
- device,
- codePointsData,
- curvesTexData,
- bandsTexBandOffsets,
- bandsTexCurveOffsets,
- font,
+ // Sort curves by highest Y (max of y1,y2,y3) descending
+ curves.sort(
+ (a, b) => Math.max(b.x1, b.x2, b.x3) - Math.max(a.x1, a.x2, a.x3),
);
- }
- private buildOutput(
- device: GPUDevice | null,
- codePoints: SlugCodePoint[],
- curvesList: number[],
- bandOffsets: number[],
- curveOffsets: number[],
- font: FontkitFont,
- ): SlugGeneratorOutput {
- const map = new Map<number, SlugCodePoint>();
- for (const cp of codePoints) {
- map.set(cp.codePoint, cp);
+ for (let b = 0; b < bCount; b++) {
+ const bandTexelOffset = Math.floor(a.curveOffsets.length / 2);
+ let curveCount = 0;
+
+ for (const c of curves) {
+ if (c.y1 === c.y2 && c.y2 === c.y3) {
+ continue; // perfectly horizontal
+ }
+ const curveMinY = Math.min(c.y1, c.y2, c.y3);
+ const curveMaxY = Math.max(c.y1, c.y2, c.y3);
+ if (curveMinY > bandMaxY || curveMaxY < bandMinY) {
+ continue; // doesn't cross band
+ }
+
+ const texelIndex = c.texelIndex ?? 0;
+ const curveOffsetX = texelIndex % TEXTURE_WIDTH;
+ const curveOffsetY = Math.floor(texelIndex / TEXTURE_WIDTH);
+ a.curveOffsets.push(curveOffsetX, curveOffsetY);
+ curveCount++;
+ }
+ a.bandOffsets.push(curveCount, bandTexelOffset);
+ bandMinY += bandDimY;
+ bandMaxY += bandDimY;
}
- let curvesTex: GPUTexture = null as any;
- let bandsTex: GPUTexture = null as any;
+ // For vertical bands, sort by max Y descending
+ const bandDimX = Math.ceil(sizeX / bCount);
+ let bandMinX = 0;
+ let bandMaxX = bandDimX;
- if (device) {
- const curvesTexels = Math.ceil(curvesList.length / 4);
- const curvesTexHeight = Math.max(
- 1,
- Math.ceil(curvesTexels / TEXTURE_WIDTH),
- );
+ curves.sort(
+ (a, b) => Math.max(b.y1, b.y2, b.y3) - Math.max(a.y1, a.y2, a.y3),
+ );
- const curvesFloatArray = new Float32Array(
- TEXTURE_WIDTH * curvesTexHeight * 4,
- );
- curvesFloatArray.fill(-1.0);
- curvesFloatArray.set(curvesList);
-
- curvesTex = device.createTexture({
- label: "SlugGeneratedCurvesTexture",
- size: [TEXTURE_WIDTH, curvesTexHeight],
- format: "rgba32float",
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
- });
- device.queue.writeTexture(
- { texture: curvesTex },
- curvesFloatArray,
- { bytesPerRow: TEXTURE_WIDTH * 16 },
- [TEXTURE_WIDTH, curvesTexHeight],
- );
+ for (let b = 0; b < bCount; b++) {
+ const bandTexelOffset = Math.floor(a.curveOffsets.length / 2);
+ let curveCount = 0;
- const bandsTexels =
- Math.floor(bandOffsets.length / 2) +
- Math.floor(curveOffsets.length / 2);
- const bandsTexHeight = Math.max(
- 1,
- Math.ceil(bandsTexels / TEXTURE_WIDTH),
- );
+ for (const c of curves) {
+ if (c.x1 === c.x2 && c.x2 === c.x3) {
+ continue; // perfectly vertical
+ }
+ const curveMinX = Math.min(c.x1, c.x2, c.x3);
+ const curveMaxX = Math.max(c.x1, c.x2, c.x3);
+ if (curveMinX > bandMaxX || curveMaxX < bandMinX) {
+ continue; // doesn't cross band
+ }
- const bandsUintArray = new Uint32Array(
- TEXTURE_WIDTH * bandsTexHeight * 2,
- );
- bandsUintArray.set(bandOffsets, 0);
- bandsUintArray.set(curveOffsets, bandOffsets.length);
-
- bandsTex = device.createTexture({
- label: "SlugGeneratedBandsTexture",
- size: [TEXTURE_WIDTH, bandsTexHeight],
- format: "rg32uint",
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
- });
- device.queue.writeTexture(
- { texture: bandsTex },
- bandsUintArray,
- { bytesPerRow: TEXTURE_WIDTH * 8 },
- [TEXTURE_WIDTH, bandsTexHeight],
- );
+ const texelIndex = c.texelIndex ?? 0;
+ const curveOffsetX = texelIndex % TEXTURE_WIDTH;
+ const curveOffsetY = Math.floor(texelIndex / TEXTURE_WIDTH);
+ a.curveOffsets.push(curveOffsetX, curveOffsetY);
+ curveCount++;
+ }
+ a.bandOffsets.push(curveCount, bandTexelOffset);
+ bandMinX += bandDimX;
+ bandMaxX += bandDimX;
}
return {
- codePoints: map,
- curvesTex,
- bandsTex,
+ codePoint,
+ glyphId,
+ width: Math.floor(gx2 - gx1),
+ height: Math.floor(gy2 - gy1),
+ advanceWidth: Math.floor(glyph.advanceWidth || 0),
+ bearingX: Math.floor(gx1),
+ bearingY: Math.floor(gy2),
+ bandCount: bCount,
+ bandDimX,
+ bandDimY,
+ bandsTexCoordX: bandsTexelIndex % TEXTURE_WIDTH,
+ bandsTexCoordY: Math.floor(bandsTexelIndex / TEXTURE_WIDTH),
+ };
+ }
+
+ private buildOutput(font: FontkitFont): SlugGeneratorOutput {
+ const metrics = {
ascender: font.ascent || 0,
descender: font.descent || 0,
lineGap: font.lineGap || 0,
unitsPerEm: font.unitsPerEm || 0,
+ };
+ return {
+ codePoints: new Map<number, SlugCodePoint>(),
+ glyphs: new Map<number, SlugCodePoint>(),
+ curvesTex: null as unknown as GPUTexture,
+ bandsTex: null as unknown as GPUTexture,
+ ...metrics,
_raw: {
- codePoints,
- curvesList,
- bandOffsets,
- curveOffsets,
- metrics: {
- ascender: font.ascent || 0,
- descender: font.descent || 0,
- lineGap: font.lineGap || 0,
- unitsPerEm: font.unitsPerEm || 0,
- },
+ codePoints: [],
+ curvesList: [],
+ bandOffsets: [],
+ curveOffsets: [],
+ metrics,
},
};
}
@@ -954,20 +1088,20 @@ export class SlugGenerator {
const metrics = generatedData._raw.metrics;
const totalBytes =
- 8 + 2 + codePoints.length * 40 + 8 + curvesBytes + 8 + bandsBytes + 16;
+ 8 + 4 + codePoints.length * 44 + 8 + curvesBytes + 8 + bandsBytes + 16;
const buffer = new ArrayBuffer(totalBytes);
const view = new DataView(buffer);
let offset = 0;
for (let i = 0; i < 8; i++) {
- view.setUint8(offset++, SLUGGISH_HEADER_DATA.charCodeAt(i));
+ view.setUint8(offset++, SLUGGISH_HEADER_DATA_V2.charCodeAt(i));
}
- view.setUint16(offset, codePoints.length, true);
- offset += 2;
+ view.setUint32(offset, codePoints.length, true);
+ offset += 4;
for (const cp of codePoints) {
- view.setUint32(offset, cp.codePoint, true);
+ view.setInt32(offset, cp.codePoint, true);
offset += 4;
view.setUint32(offset, cp.width, true);
offset += 4;
@@ -989,6 +1123,8 @@ export class SlugGenerator {
offset += 2;
view.setUint16(offset, cp.bandsTexCoordY, true);
offset += 2;
+ view.setUint32(offset, cp.glyphId ?? 0, true);
+ offset += 4;
}
view.setUint16(offset, TEXTURE_WIDTH, true);
diff --git a/packages/webgpu-renderers/src/slug/slug-geometry.ts b/packages/webgpu-renderers/src/slug/slug-geometry.ts
index 602fe7ea..7e5f9554 100644
--- a/packages/webgpu-renderers/src/slug/slug-geometry.ts
+++ b/packages/webgpu-renderers/src/slug/slug-geometry.ts
@@ -6,8 +6,19 @@ import {
} from "../text-animations/path.js";
import type { TextPathOptions } from "../text-animations/types.js";
import { SlugFontCache } from "./slug-font-cache.js";
-import type { FontkitFont } from "./slug-generator.js";
import type { SlugCodePoint, SlugFont } from "./slug-loader.js";
+import {
+ alignOffset,
+ breakLines,
+ fontIdentity,
+ type PlacedLine,
+ placeLine,
+ resolveAlign,
+ type ShapedCluster,
+ type ShapeStyle,
+ shapeParagraph,
+ type TextDirection,
+} from "./text-shaping.js";
export interface SlugGlyphLayout {
char: string;
@@ -19,6 +30,16 @@ export interface SlugGlyphLayout {
charIndex: number;
unitIndex: number; // Index of the animation unit this glyph belongs to
isSpace: boolean;
+ /** UTF-16 index in the laid-out text of the cluster this glyph draws. */
+ textIndex?: number;
+ /** The glyph belongs to a right-to-left run. */
+ rtl?: boolean;
+ /** Advance of the glyph's whole cluster, px (letter spacing excluded). */
+ clusterAdvance?: number;
+ /** Left edge of the glyph's cluster on its line, px. */
+ clusterX?: number;
+ /** The glyph's paragraph runs right to left (so "start" is the right edge). */
+ baseRtl?: boolean;
pathTangentAngleRad?: number;
perpendicularToPath?: boolean;
pathNormalX?: number;
@@ -60,89 +81,90 @@ export interface SlugLayoutResult {
linesCount: number;
wordsCount: number;
charsCount: number;
+ /** Some text was laid out right to left. */
+ hasRtl?: boolean;
}
-const EMOJI_REGEX =
- /(\p{Extended_Pictographic}|\p{Emoji_Presentation}|[\u2600-\u27BF])/u;
+type Align = "left" | "center" | "right" | "start" | "end";
+type ApplyBy = "line" | "word" | "char";
-const graphemeSegmenter =
- typeof Intl !== "undefined" &&
- (
- Intl as unknown as {
- Segmenter?: new (
- locale: string,
- opts: { granularity: string },
- ) => { segment: (text: string) => Iterable<{ segment: string }> };
- }
- ).Segmenter
- ? new (
- Intl as unknown as {
- Segmenter: new (
- locale: string,
- opts: { granularity: string },
- ) => { segment: (text: string) => Iterable<{ segment: string }> };
- }
- ).Segmenter("en", { granularity: "grapheme" })
- : null;
+const layoutCache = new Map<string, SlugLayoutResult>();
+const MAX_LAYOUT_CACHE = 256;
-function segmentGraphemes(text: string): string[] {
- if (graphemeSegmenter) {
- return Array.from(graphemeSegmenter.segment(text), (s) => s.segment);
+function cacheResult(key: string, result: SlugLayoutResult): SlugLayoutResult {
+ if (layoutCache.size >= MAX_LAYOUT_CACHE) {
+ const firstKey = layoutCache.keys().next().value;
+ if (firstKey) layoutCache.delete(firstKey);
}
- return Array.from(text);
+ layoutCache.set(key, result);
+ return result;
}
-const kernCache = new Map<string, number>();
-
-function resolveParsedFont(font: SlugFont): FontkitFont | null {
- if (font.fontFamily) {
- const parsed = SlugFontCache.getParsed(font.fontFamily);
- if (parsed) return parsed;
+/** Reads a plain value or an animated `{ get() }` one. */
+function resolveValue(v: unknown): unknown {
+ if (
+ v &&
+ typeof v === "object" &&
+ "get" in v &&
+ typeof (v as { get: unknown }).get === "function"
+ ) {
+ return (v as { get: () => unknown }).get();
}
- const globalParsed = (globalThis as Record<symbol, unknown>)[
- Symbol.for("gatewai.slugFontCache.parsed")
- ] as Map<string, FontkitFont> | undefined;
- if (globalParsed) {
- if (font.fontFamily && globalParsed.has(font.fontFamily)) {
- return globalParsed.get(font.fontFamily) ?? null;
- }
- if (globalParsed.size === 1) {
- return globalParsed.values().next().value ?? null;
- }
- }
- return null;
+ return v;
}
-export function getKernOffset(font: SlugFont, a: number, b: number): number {
- const family = font.fontFamily ?? "default";
- const key = `${family}:${a}:${b}`;
- const hit = kernCache.get(key);
- if (hit !== undefined) return hit;
+interface LogicalIndices {
+ charIndex: number;
+ wordIndex: number;
+ unitIndex: number;
+}
- const src = resolveParsedFont(font);
- let v = 0;
- if (src) {
- try {
- const s = String.fromCodePoint(a) + String.fromCodePoint(b);
- const laid = src.layout?.(s);
- if (!laid) throw new Error("font cannot shape text");
- const total = laid.positions.reduce(
- (acc: number, p: { xAdvance: number }) => acc + p.xAdvance,
- 0,
- );
- const advA = src.glyphForCodePoint?.(a)?.advanceWidth ?? 0;
- const advB = src.glyphForCodePoint?.(b)?.advanceWidth ?? 0;
- v = laid.glyphs.length === 2 ? total - (advA + advB) : 0;
- } catch {
- v = 0;
+/**
+ * Animation indices follow reading order, so a right-to-left line reveals
+ * from the right. Emoji count as characters but neither start nor end words.
+ */
+function assignIndices<S extends ShapeStyle>(
+ lines: ShapedCluster<S>[][],
+ applyBy: ApplyBy,
+): {
+ indices: Map<ShapedCluster<S>, LogicalIndices>;
+ words: number;
+ chars: number;
+} {
+ const indices = new Map<ShapedCluster<S>, LogicalIndices>();
+ let wordIndex = 0;
+ let charIndex = 0;
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
+ let inWord = false;
+ for (const c of lines[lineIndex]) {
+ if (!c.isEmoji) {
+ if (c.isSpace) {
+ if (inWord) {
+ wordIndex++;
+ inWord = false;
+ }
+ } else {
+ inWord = true;
+ }
+ }
+ const unitIndex =
+ applyBy === "line"
+ ? lineIndex
+ : applyBy === "word"
+ ? wordIndex
+ : charIndex;
+ indices.set(c, { charIndex, wordIndex, unitIndex });
+ if (c.isEmoji || c.glyphs.length > 0) charIndex++;
}
+ if (inWord) wordIndex++;
}
- kernCache.set(key, v);
- return v;
+ return { indices, words: wordIndex, chars: charIndex };
}
-const layoutCache = new Map<string, SlugLayoutResult>();
-const MAX_LAYOUT_CACHE = 256;
+/** Optional ligatures stay off when text animates per character or is letter-spaced (as in CSS). */
+function useLigatures(applyBy: ApplyBy, letterSpacing: number): boolean {
+ return applyBy !== "char" && letterSpacing === 0;
+}
export class SlugGeometry {
static layout(
@@ -152,40 +174,40 @@ export class SlugGeometry {
letterSpacing: number,
lineHeight: number,
maxWidth: number,
- align: "left" | "center" | "right" | "start" | "end" = "left",
- applyBy: "line" | "word" | "char" = "word",
+ align: Align = "left",
+ applyBy: ApplyBy = "word",
alignWidth?: number,
pathOptions?: TextPathOptions,
spans?: TextSpan[],
+ direction: TextDirection = "auto",
): SlugLayoutResult {
+ const fontKey = fontIdentity(font);
if (spans && spans.length > 0) {
const spansKey = spans
.map(
(s) =>
- `${typeof s.text === "string" ? s.text : ""}:${s.fontFamily ?? ""}:${s.fontWeight ?? ""}:${s.fontSize ?? ""}:${s.fill ?? ""}:${s.baselineShift ?? ""}`,
+ `${typeof s.text === "string" ? s.text : ""}:${s.fontFamily ?? ""}:${s.fontWeight ?? ""}:${s.fontSize ?? ""}:${s.fill ?? ""}:${s.baselineShift ?? ""}:${s.letterSpacing ?? ""}`,
)
.join(";");
- const cacheKey = `${text}|${font.fontFamily ?? ""}|${font.unitsPerEm}|${fontSize}|${letterSpacing}|${lineHeight}|${maxWidth}|${align}|${applyBy}|${alignWidth ?? ""}|${spansKey}`;
+ const cacheKey = `${text}|${fontKey}|${fontSize}|${letterSpacing}|${lineHeight}|${maxWidth}|${align}|${applyBy}|${alignWidth ?? ""}|${direction}|${spansKey}`;
const cached = layoutCache.get(cacheKey);
if (cached) return cached;
- const result = SlugGeometry.layoutSpans(
- spans,
- font,
- fontSize,
- letterSpacing,
- lineHeight,
- maxWidth,
- align,
- applyBy,
- alignWidth,
+ return cacheResult(
+ cacheKey,
+ SlugGeometry.layoutSpans(
+ spans,
+ font,
+ fontSize,
+ letterSpacing,
+ lineHeight,
+ maxWidth,
+ align,
+ applyBy,
+ alignWidth,
+ direction,
+ ),
);
- if (layoutCache.size >= MAX_LAYOUT_CACHE) {
- const firstKey = layoutCache.keys().next().value;
- if (firstKey) layoutCache.delete(firstKey);
- }
- layoutCache.set(cacheKey, result);
- return result;
}
if (pathOptions) {
@@ -196,250 +218,110 @@ export class SlugGeometry {
letterSpacing,
pathOptions,
applyBy,
+ direction,
);
}
- const cacheKey = `${text}|${font.fontFamily ?? ""}|${font.unitsPerEm}|${fontSize}|${letterSpacing}|${lineHeight}|${maxWidth}|${align}|${applyBy}|${alignWidth ?? ""}`;
+ const cacheKey = `${text}|${fontKey}|${fontSize}|${letterSpacing}|${lineHeight}|${maxWidth}|${align}|${applyBy}|${alignWidth ?? ""}|${direction}`;
const cached = layoutCache.get(cacheKey);
if (cached) return cached;
- const fontScale = fontSize / font.unitsPerEm;
-
- // 1. Tokenize text into paragraph lines, words, and spaces
- const rawLines = text.split("\n");
+ const style: ShapeStyle = { font, fontSize, letterSpacing };
+ const ligatures = useLigatures(applyBy, letterSpacing);
- interface RawGlyph {
- char: string;
- cp: SlugCodePoint | null;
- isEmoji: boolean;
- isSpace: boolean;
- x: number; // local X offset in the token
+ // 1. Shape each paragraph and wrap it into lines (logical order).
+ interface Line {
+ clusters: ShapedCluster[];
+ baseLevel: number;
+ textOffset: number;
}
-
- interface RawLine {
- glyphs: RawGlyph[];
- width: number;
- }
-
- const lines: RawLine[] = [];
-
- for (const rawLine of rawLines) {
- const tokens = rawLine.split(/(\s+)/);
- let currentLineGlyphs: RawGlyph[] = [];
- let currentLineWidth = 0;
-
- for (const token of tokens) {
- if (!token) continue;
-
- const isSpace = /^\s+$/.test(token);
- let tokenWidth = 0;
- const tokenGlyphs: RawGlyph[] = [];
-
- const graphemes = segmentGraphemes(token);
-
- for (const char of graphemes) {
- // Ignore invisible standalone variation selectors or zero-width joiners if any
- if (char === "\uFE0F" || char === "\uFE0E" || char === "\u200D") {
- continue;
- }
-
- const codePoint = char.codePointAt(0) || 0;
- const isEmoji = EMOJI_REGEX.test(char);
-
- let cp: SlugCodePoint | null = null;
- let adv = 0;
-
- if (isEmoji) {
- adv = fontSize;
- } else {
- cp =
- font.codePoints.get(codePoint) || font.codePoints.get(-1) || null;
- adv = (cp?.advanceWidth || 0) * fontScale;
- }
-
- tokenGlyphs.push({
- char,
- cp,
- isEmoji,
- isSpace,
- x: tokenWidth,
- });
-
- tokenWidth += adv + letterSpacing;
- }
-
- if (isSpace) {
- // Skip leading spaces on a new line (after a word-wrap reset)
- if (currentLineGlyphs.length === 0) continue;
- for (const tg of tokenGlyphs) {
- tg.x += currentLineWidth;
- currentLineGlyphs.push(tg);
- }
- currentLineWidth += tokenWidth;
- } else {
- const tokenVisualWidth =
- tokenGlyphs.length > 0 && letterSpacing > 0
- ? tokenWidth - letterSpacing
- : tokenWidth;
- if (
- currentLineWidth > 0 &&
- currentLineWidth + tokenVisualWidth > maxWidth
- ) {
- lines.push({
- glyphs: currentLineGlyphs,
- width: currentLineWidth,
- });
- currentLineGlyphs = [];
- currentLineWidth = 0;
- }
-
- for (const tg of tokenGlyphs) {
- tg.x += currentLineWidth;
- currentLineGlyphs.push(tg);
- }
- currentLineWidth += tokenWidth;
- }
- }
-
- lines.push({
- glyphs: currentLineGlyphs,
- width: currentLineWidth,
+ const lines: Line[] = [];
+ let textOffset = 0;
+ for (const paragraph of text.split("\n")) {
+ const shaped = shapeParagraph([{ text: paragraph, style }], {
+ direction,
+ ligatures,
});
- }
-
- // Apply kerning across consecutive non-space glyphs on each line
- for (const line of lines) {
- let shift = 0;
- for (let i = 1; i < line.glyphs.length; i++) {
- const prev = line.glyphs[i - 1];
- const cur = line.glyphs[i];
- if (!prev.isSpace && !cur.isSpace && prev.cp && cur.cp) {
- shift +=
- getKernOffset(font, prev.cp.codePoint, cur.cp.codePoint) *
- fontScale;
- }
- cur.x += shift;
+ for (const clusters of breakLines(shaped.clusters, maxWidth)) {
+ lines.push({ clusters, baseLevel: shaped.baseLevel, textOffset });
}
- line.width += shift;
+ textOffset += paragraph.length + 1;
}
- // 2. Position lines and build detailed glyph descriptions
+ const { indices, words, chars } = assignIndices(
+ lines.map((l) => l.clusters),
+ applyBy,
+ );
+
+ // 2. Order each line for display, align it, and emit glyphs.
const glyphs: SlugGlyphLayout[] = [];
const emojis: SlugEmojiLayout[] = [];
-
- let currentY = font.ascender * fontScale; // Baseline of first line
- let wordIndex = 0;
- let charIndex = 0;
-
- const isCenter = align === "center";
- const isRight = align === "right" || align === "end";
+ let hasRtl = false;
+ let currentY = font.ascender * (fontSize / font.unitsPerEm); // Baseline of first line
+ const targetAlignWidth = alignWidth ?? maxWidth;
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
- const line = lines[lineIndex];
- let visibleLineWidth = line.width;
- for (let i = line.glyphs.length - 1; i >= 0; i--) {
- const g = line.glyphs[i];
- if (!g.isSpace) {
- const adv = g.isEmoji
- ? fontSize
- : (g.cp?.advanceWidth || 0) * fontScale;
- visibleLineWidth = g.x + adv;
- break;
- }
- }
-
- const targetAlignWidth = alignWidth ?? maxWidth;
- let alignOffset = 0;
- if (isCenter) {
- alignOffset = (targetAlignWidth - visibleLineWidth) / 2;
- } else if (isRight) {
- alignOffset = targetAlignWidth - visibleLineWidth;
- }
-
- let inWord = false;
-
- for (let gIdx = 0; gIdx < line.glyphs.length; gIdx++) {
- const g = line.glyphs[gIdx];
- const charX = g.x + alignOffset;
-
- if (g.isEmoji) {
+ const { clusters, baseLevel, textOffset: offset } = lines[lineIndex];
+ const placed = placeLine(clusters, baseLevel);
+ const shift = alignOffset(
+ placed,
+ resolveAlign(align, baseLevel),
+ targetAlignWidth,
+ );
+ const xOf = new Map<ShapedCluster, number>();
+ for (const p of placed.clusters) xOf.set(p.cluster, p.x + shift);
+ if (baseLevel & 1) hasRtl = true;
+
+ // Emit in reading order; positions come from the visual placement.
+ for (const c of clusters) {
+ const x = xOf.get(c) ?? 0;
+ const idx = indices.get(c) as LogicalIndices;
+ const rtl = (c.level & 1) === 1;
+ if (rtl) hasRtl = true;
+ if (c.isEmoji) {
emojis.push({
- char: g.char,
- x: charX,
+ char: c.text,
+ x: x + c.inkStart,
y: currentY - fontSize,
size: fontSize,
lineIndex,
});
- charIndex++;
- } else if (g.cp) {
- if (g.isSpace) {
- if (inWord) {
- wordIndex++;
- inWord = false;
- }
- } else {
- if (!inWord) {
- inWord = true;
- }
- }
-
- let mappedUnitIndex = 0;
- if (applyBy === "line") {
- mappedUnitIndex = lineIndex;
- } else if (applyBy === "word") {
- mappedUnitIndex = wordIndex;
- } else {
- mappedUnitIndex = charIndex;
- }
-
+ continue;
+ }
+ for (const g of c.glyphs) {
glyphs.push({
- char: g.char,
+ char: c.text,
cp: g.cp,
- x: charX,
- y: currentY,
+ x: x + g.dx,
+ y: currentY + g.dy,
lineIndex,
- wordIndex,
- charIndex,
- unitIndex: mappedUnitIndex,
- isSpace: g.isSpace,
+ wordIndex: idx.wordIndex,
+ charIndex: idx.charIndex,
+ unitIndex: idx.unitIndex,
+ isSpace: c.isSpace,
+ textIndex: offset + c.start,
+ rtl,
+ clusterAdvance: c.advance - c.spacing,
+ clusterX: x,
+ baseRtl: (baseLevel & 1) === 1,
});
-
- charIndex++;
}
}
-
- if (inWord) {
- wordIndex++;
- }
currentY += lineHeight;
}
- const totalHeight = currentY - lineHeight + -font.descender * fontScale;
-
- // Calculate total distinct unit counts
- let maxUnitIndex = 0;
- for (const g of glyphs) {
- if (!g.isSpace && g.unitIndex > maxUnitIndex) {
- maxUnitIndex = g.unitIndex;
- }
- }
+ const totalHeight =
+ currentY - lineHeight + -font.descender * (fontSize / font.unitsPerEm);
- const result: SlugLayoutResult = {
+ return cacheResult(cacheKey, {
glyphs,
emojis,
totalHeight,
linesCount: lines.length,
- wordsCount: wordIndex,
- charsCount: charIndex,
- };
-
- if (layoutCache.size >= MAX_LAYOUT_CACHE) {
- const firstKey = layoutCache.keys().next().value;
- if (firstKey) layoutCache.delete(firstKey);
- }
- layoutCache.set(cacheKey, result);
-
- return result;
+ wordsCount: words,
+ charsCount: chars,
+ hasRtl: hasRtl || undefined,
+ });
}
static measure(
@@ -450,6 +332,7 @@ export class SlugGeometry {
lineHeight: number,
maxWidth?: number,
spans?: TextSpan[],
+ direction: TextDirection = "auto",
): { width: number; height: number; layout: SlugLayoutResult } {
const effectiveMaxWidth = maxWidth ?? Number.MAX_SAFE_INTEGER;
const layout = SlugGeometry.layout(
@@ -464,6 +347,7 @@ export class SlugGeometry {
undefined,
undefined,
spans,
+ direction,
);
// Compute the actual content width from the lines
@@ -507,41 +391,26 @@ export class SlugGeometry {
defaultLetterSpacing: number,
defaultLineHeight: number,
maxWidth: number,
- align: "left" | "center" | "right" | "start" | "end" = "left",
- applyBy: "line" | "word" | "char" = "word",
+ align: Align = "left",
+ applyBy: ApplyBy = "word",
alignWidth?: number,
+ direction: TextDirection = "auto",
): SlugLayoutResult {
- interface StreamGrapheme {
- isNewline: boolean;
- char: string;
- cp: SlugCodePoint | null;
- isEmoji: boolean;
- isSpace: boolean;
- advance: number;
+ interface SpanStyle extends ShapeStyle {
spanIndex: number;
- font: SlugFont;
- fontSize: number;
fontScale: number;
- letterSpacing: number;
baselineShift: number;
fill?: string;
opacity?: number;
mark?: TextSpanMark;
}
- const stream: StreamGrapheme[] = [];
-
+ // Split the spans into paragraphs of styled segments.
+ const paragraphs: Array<Array<{ text: string; style: SpanStyle }>> = [[]];
+ let ligatures = useLigatures(applyBy, defaultLetterSpacing);
for (let sIdx = 0; sIdx < spans.length; sIdx++) {
const s = spans[sIdx];
- const rawText =
- typeof s.text === "string"
- ? s.text
- : s.text &&
- typeof s.text === "object" &&
- "get" in s.text &&
- typeof (s.text as { get: () => unknown }).get === "function"
- ? String((s.text as { get: () => unknown }).get())
- : String(s.text ?? "");
+ const rawText = String(resolveValue(s.text) ?? "");
let spanFont = defaultFont;
if (s.fontFamily || s.fontWeight !== undefined) {
@@ -549,269 +418,76 @@ export class SlugGeometry {
const resolved = SlugFontCache.getFont(family, s.fontWeight, null);
if (resolved) spanFont = resolved;
}
-
+ const sizeValue = resolveValue(s.fontSize);
const spanFontSize =
- typeof s.fontSize === "number"
- ? s.fontSize
- : s.fontSize &&
- typeof s.fontSize === "object" &&
- "get" in s.fontSize &&
- typeof (s.fontSize as { get: () => unknown }).get === "function"
- ? Number((s.fontSize as { get: () => unknown }).get())
+ typeof sizeValue === "number"
+ ? sizeValue
+ : sizeValue !== undefined
+ ? Number(sizeValue)
: defaultFontSize;
+ const fillValue = resolveValue(s.fill);
+ const opacityValue = resolveValue(s.opacity);
+ const style: SpanStyle = {
+ font: spanFont,
+ fontSize: spanFontSize,
+ fontScale: spanFontSize / spanFont.unitsPerEm,
+ letterSpacing: s.letterSpacing ?? defaultLetterSpacing,
+ baselineShift: s.baselineShift ?? 0,
+ fill: fillValue !== undefined ? String(fillValue) : undefined,
+ opacity: opacityValue !== undefined ? Number(opacityValue) : undefined,
+ mark: s.mark,
+ spanIndex: sIdx,
+ };
+ if (style.letterSpacing !== 0) ligatures = false;
- const spanFontScale = spanFontSize / spanFont.unitsPerEm;
- const spanLetterSpacing = s.letterSpacing ?? defaultLetterSpacing;
- const spanBaselineShift = s.baselineShift ?? 0;
- const spanFill =
- typeof s.fill === "string"
- ? s.fill
- : s.fill &&
- typeof s.fill === "object" &&
- "get" in s.fill &&
- typeof (s.fill as { get: () => unknown }).get === "function"
- ? String((s.fill as { get: () => unknown }).get())
- : undefined;
- const spanOpacity =
- typeof s.opacity === "number"
- ? s.opacity
- : s.opacity &&
- typeof s.opacity === "object" &&
- "get" in s.opacity &&
- typeof (s.opacity as { get: () => unknown }).get === "function"
- ? Number((s.opacity as { get: () => unknown }).get())
- : undefined;
-
- const graphemes = segmentGraphemes(rawText);
- for (const char of graphemes) {
- if (char === "\uFE0F" || char === "\uFE0E" || char === "\u200D") {
- continue;
- }
- if (char === "\n") {
- stream.push({
- isNewline: true,
- char: "\n",
- cp: null,
- isEmoji: false,
- isSpace: true,
- advance: 0,
- spanIndex: sIdx,
- font: spanFont,
- fontSize: spanFontSize,
- fontScale: spanFontScale,
- letterSpacing: spanLetterSpacing,
- baselineShift: spanBaselineShift,
- fill: spanFill,
- opacity: spanOpacity,
- mark: s.mark,
- });
- continue;
- }
-
- const codePoint = char.codePointAt(0) || 0;
- const isEmoji = EMOJI_REGEX.test(char);
- let cp: SlugCodePoint | null = null;
- let adv = 0;
-
- if (isEmoji) {
- adv = spanFontSize;
- } else {
- cp =
- spanFont.codePoints.get(codePoint) ||
- spanFont.codePoints.get(-1) ||
- null;
- adv = (cp?.advanceWidth || 0) * spanFontScale;
+ const parts = rawText.split("\n");
+ for (let p = 0; p < parts.length; p++) {
+ if (p > 0) paragraphs.push([]);
+ if (parts[p]) {
+ paragraphs[paragraphs.length - 1].push({ text: parts[p], style });
}
-
- stream.push({
- isNewline: false,
- char,
- cp,
- isEmoji,
- isSpace: /^\s+$/.test(char),
- advance: adv,
- spanIndex: sIdx,
- font: spanFont,
- fontSize: spanFontSize,
- fontScale: spanFontScale,
- letterSpacing: spanLetterSpacing,
- baselineShift: spanBaselineShift,
- fill: spanFill,
- opacity: spanOpacity,
- mark: s.mark,
- });
- }
- }
-
- // Tokenize stream into words, spaces, and newlines
- interface Token {
- isNewline: boolean;
- isSpace: boolean;
- glyphs: StreamGrapheme[];
- width: number;
- }
-
- const tokens: Token[] = [];
- let currentTokenGlyphs: StreamGrapheme[] = [];
- let currentTokenIsSpace = false;
- let currentTokenWidth = 0;
-
- const flushToken = () => {
- if (currentTokenGlyphs.length > 0) {
- tokens.push({
- isNewline: false,
- isSpace: currentTokenIsSpace,
- glyphs: currentTokenGlyphs,
- width: currentTokenWidth,
- });
- currentTokenGlyphs = [];
- currentTokenWidth = 0;
- }
- };
-
- for (const g of stream) {
- if (g.isNewline) {
- flushToken();
- tokens.push({
- isNewline: true,
- isSpace: true,
- glyphs: [],
- width: 0,
- });
- continue;
- }
-
- if (currentTokenGlyphs.length === 0) {
- currentTokenIsSpace = g.isSpace;
- currentTokenGlyphs.push(g);
- currentTokenWidth = g.advance + g.letterSpacing;
- } else if (g.isSpace === currentTokenIsSpace) {
- currentTokenGlyphs.push(g);
- currentTokenWidth += g.advance + g.letterSpacing;
- } else {
- flushToken();
- currentTokenIsSpace = g.isSpace;
- currentTokenGlyphs.push(g);
- currentTokenWidth = g.advance + g.letterSpacing;
}
}
- flushToken();
- // Word wrapping into lines
- interface RawSpanGlyph extends StreamGrapheme {
- x: number;
- }
- interface RawSpanLine {
- glyphs: RawSpanGlyph[];
- width: number;
+ interface Line {
+ clusters: ShapedCluster<SpanStyle>[];
+ baseLevel: number;
}
-
- const lines: RawSpanLine[] = [];
- let currentLineGlyphs: RawSpanGlyph[] = [];
- let currentLineWidth = 0;
-
- for (const token of tokens) {
- if (token.isNewline) {
- lines.push({
- glyphs: currentLineGlyphs,
- width: currentLineWidth,
- });
- currentLineGlyphs = [];
- currentLineWidth = 0;
- continue;
- }
-
- if (token.isSpace) {
- // Drop leading space at start of line
- if (currentLineGlyphs.length === 0) continue;
- for (const g of token.glyphs) {
- currentLineGlyphs.push({
- ...g,
- x: currentLineWidth,
- });
- currentLineWidth += g.advance + g.letterSpacing;
- }
- } else {
- // Word token: wrap if exceeding maxWidth
- const lastG = token.glyphs[token.glyphs.length - 1];
- const trailingLs =
- lastG && lastG.letterSpacing > 0 ? lastG.letterSpacing : 0;
- const tokenVisualWidth = token.width - trailingLs;
- if (
- currentLineWidth > 0 &&
- currentLineWidth + tokenVisualWidth > maxWidth
- ) {
- lines.push({
- glyphs: currentLineGlyphs,
- width: currentLineWidth,
- });
- currentLineGlyphs = [];
- currentLineWidth = 0;
- }
-
- for (const g of token.glyphs) {
- currentLineGlyphs.push({
- ...g,
- x: currentLineWidth,
- });
- currentLineWidth += g.advance + g.letterSpacing;
- }
+ const lines: Line[] = [];
+ for (const segments of paragraphs) {
+ const shaped = shapeParagraph(segments, { direction, ligatures });
+ for (const clusters of breakLines(shaped.clusters, maxWidth)) {
+ lines.push({ clusters, baseLevel: shaped.baseLevel });
}
}
- lines.push({
- glyphs: currentLineGlyphs,
- width: currentLineWidth,
- });
- // Kerning per line
- for (const line of lines) {
- let shift = 0;
- for (let i = 1; i < line.glyphs.length; i++) {
- const prev = line.glyphs[i - 1];
- const cur = line.glyphs[i];
- if (
- !prev.isSpace &&
- !cur.isSpace &&
- prev.cp &&
- cur.cp &&
- prev.font === cur.font
- ) {
- shift +=
- getKernOffset(cur.font, prev.cp.codePoint, cur.cp.codePoint) *
- cur.fontScale;
- }
- cur.x += shift;
- }
- line.width += shift;
- }
+ const { indices, chars } = assignIndices(
+ lines.map((l) => l.clusters),
+ applyBy,
+ );
// Baseline alignment & output glyph assembly
const glyphs: SlugGlyphLayout[] = [];
const emojis: SlugEmojiLayout[] = [];
const marks: SlugMarkLayout[] = [];
+ let hasRtl = false;
let currentBaselineY = 0;
- let wordIndex = 0;
- let charIndex = 0;
-
- const isCenter = align === "center";
- const isRight = align === "right" || align === "end";
+ const targetAlignWidth = alignWidth ?? maxWidth;
+ const defaultScale = defaultFontSize / defaultFont.unitsPerEm;
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
- const line = lines[lineIndex];
+ const { clusters, baseLevel } = lines[lineIndex];
- let maxAscenderPx =
- (defaultFont.ascender ?? 800) *
- (defaultFontSize / defaultFont.unitsPerEm);
- let maxDescenderPx =
- -(defaultFont.descender ?? -200) *
- (defaultFontSize / defaultFont.unitsPerEm);
+ let maxAscenderPx = (defaultFont.ascender ?? 800) * defaultScale;
+ let maxDescenderPx = -(defaultFont.descender ?? -200) * defaultScale;
let maxLineHeightPx = defaultLineHeight;
- for (const g of line.glyphs) {
- const asc = (g.font.ascender ?? 800) * g.fontScale;
- const desc = -(g.font.descender ?? -200) * g.fontScale;
- const lh = defaultLineHeight * (g.fontSize / defaultFontSize);
+ for (const c of clusters) {
+ const st = c.style;
+ const asc = (st.font.ascender ?? 800) * st.fontScale;
+ const desc = -(st.font.descender ?? -200) * st.fontScale;
+ const lh = defaultLineHeight * (st.fontSize / defaultFontSize);
if (asc > maxAscenderPx) maxAscenderPx = asc;
if (desc > maxDescenderPx) maxDescenderPx = desc;
if (lh > maxLineHeightPx) maxLineHeightPx = lh;
@@ -821,26 +497,15 @@ export class SlugGeometry {
currentBaselineY = maxAscenderPx;
}
- let visibleLineWidth = line.width;
- for (let i = line.glyphs.length - 1; i >= 0; i--) {
- const g = line.glyphs[i];
- if (!g.isSpace) {
- visibleLineWidth = g.x + g.advance;
- break;
- }
- }
-
- const targetAlignWidth = alignWidth ?? maxWidth;
- let alignOffset = 0;
- if (isCenter) {
- alignOffset = (targetAlignWidth - visibleLineWidth) / 2;
- } else if (isRight) {
- alignOffset = targetAlignWidth - visibleLineWidth;
- }
-
- let inWord = false;
+ const placed: PlacedLine<SpanStyle> = placeLine(clusters, baseLevel);
+ const shift = alignOffset(
+ placed,
+ resolveAlign(align, baseLevel),
+ targetAlignWidth,
+ );
+ if (baseLevel & 1) hasRtl = true;
- // Mark tracking
+ // Mark backgrounds group visually adjacent clusters of one mark.
let activeMark: TextSpanMark | undefined;
let markStartX = 0;
let markEndX = 0;
@@ -851,24 +516,12 @@ export class SlugGeometry {
if (activeMark && markEndX > markStartX) {
const padX = activeMark.paddingX ?? 4;
const padY = activeMark.paddingY ?? 2;
- const bg =
- typeof activeMark.background === "string"
- ? activeMark.background
- : activeMark.background &&
- typeof activeMark.background === "object" &&
- "get" in activeMark.background &&
- typeof (activeMark.background as { get: () => unknown })
- .get === "function"
- ? String(
- (activeMark.background as { get: () => unknown }).get(),
- )
- : String(activeMark.background);
marks.push({
x: markStartX - padX,
y: currentBaselineY - markAsc - padY,
width: markEndX - markStartX + padX * 2,
height: markAsc + markDesc + padY * 2,
- background: bg,
+ background: String(resolveValue(activeMark.background)),
borderRadius: activeMark.borderRadius ?? 4,
lineIndex,
});
@@ -876,89 +529,76 @@ export class SlugGeometry {
activeMark = undefined;
};
- for (let gIdx = 0; gIdx < line.glyphs.length; gIdx++) {
- const g = line.glyphs[gIdx];
- const charX = g.x + alignOffset;
-
- // Mark grouping
- if (g.mark && !g.isSpace) {
- if (!activeMark || activeMark !== g.mark) {
+ const xOf = new Map<ShapedCluster<SpanStyle>, number>();
+ for (const p of placed.clusters) {
+ const c = p.cluster;
+ const x = p.x + shift;
+ xOf.set(c, x);
+ const st = c.style;
+ if (st.mark && !c.isSpace) {
+ const a = (st.font.ascender ?? 800) * st.fontScale;
+ const d = -(st.font.descender ?? -200) * st.fontScale;
+ if (!activeMark || activeMark !== st.mark) {
flushMark();
- activeMark = g.mark;
- markStartX = charX;
- markEndX = charX + g.advance;
- markAsc = (g.font.ascender ?? 800) * g.fontScale;
- markDesc = -(g.font.descender ?? -200) * g.fontScale;
+ activeMark = st.mark;
+ markStartX = x + c.inkStart;
+ markEndX = x + c.inkEnd;
+ markAsc = a;
+ markDesc = d;
} else {
- markEndX = charX + g.advance;
- const a = (g.font.ascender ?? 800) * g.fontScale;
- const d = -(g.font.descender ?? -200) * g.fontScale;
+ markEndX = x + c.inkEnd;
if (a > markAsc) markAsc = a;
if (d > markDesc) markDesc = d;
}
} else {
flushMark();
}
+ }
+ flushMark();
- if (g.isEmoji) {
+ for (const c of clusters) {
+ const x = xOf.get(c) ?? 0;
+ const st = c.style;
+ const idx = indices.get(c) as LogicalIndices;
+ const rtl = (c.level & 1) === 1;
+ if (rtl) hasRtl = true;
+ if (c.isEmoji) {
emojis.push({
- char: g.char,
- x: charX,
- y: currentBaselineY - g.fontSize,
- size: g.fontSize,
+ char: c.text,
+ x: x + c.inkStart,
+ y: currentBaselineY - st.fontSize,
+ size: st.fontSize,
lineIndex,
});
- charIndex++;
- } else if (g.cp) {
- if (g.isSpace) {
- if (inWord) {
- wordIndex++;
- inWord = false;
- }
- } else {
- if (!inWord) {
- inWord = true;
- }
- }
-
- let mappedUnitIndex = 0;
- if (applyBy === "line") {
- mappedUnitIndex = lineIndex;
- } else if (applyBy === "word") {
- mappedUnitIndex = wordIndex;
- } else {
- mappedUnitIndex = charIndex;
- }
-
+ continue;
+ }
+ for (const g of c.glyphs) {
glyphs.push({
- char: g.char,
+ char: c.text,
cp: g.cp,
- x: charX,
- y: currentBaselineY + g.baselineShift,
+ x: x + g.dx,
+ y: currentBaselineY + st.baselineShift + g.dy,
lineIndex,
- wordIndex,
- charIndex,
- unitIndex: mappedUnitIndex,
- isSpace: g.isSpace,
- spanIndex: g.spanIndex,
- fill: g.fill,
- fontSize: g.fontSize,
- fontScale: g.fontScale,
- baselineShift: g.baselineShift,
- opacity: g.opacity,
- fontFamily: g.font.fontFamily,
- font: g.font,
- mark: g.mark,
+ wordIndex: idx.wordIndex,
+ charIndex: idx.charIndex,
+ unitIndex: idx.unitIndex,
+ isSpace: c.isSpace,
+ rtl,
+ clusterAdvance: c.advance - c.spacing,
+ clusterX: x,
+ baseRtl: (baseLevel & 1) === 1,
+ spanIndex: st.spanIndex,
+ fill: st.fill,
+ fontSize: st.fontSize,
+ fontScale: st.fontScale,
+ baselineShift: st.baselineShift,
+ opacity: st.opacity,
+ fontFamily: st.font.fontFamily,
+ font: st.font,
+ mark: st.mark,
});
-
- charIndex++;
}
}
- flushMark();
-
- if (inWord) {
- wordIndex++;
- }
if (lineIndex < lines.length - 1) {
currentBaselineY += Math.max(
@@ -978,9 +618,7 @@ export class SlugGeometry {
const totalHeight =
lines.length > 0
- ? currentBaselineY +
- (defaultFontSize / defaultFont.unitsPerEm) *
- -(defaultFont.descender ?? -200)
+ ? currentBaselineY + defaultScale * -(defaultFont.descender ?? -200)
: 0;
return {
@@ -990,7 +628,8 @@ export class SlugGeometry {
totalHeight,
linesCount: lines.length,
wordsCount: Math.max(0, maxUnitIndex + 1),
- charsCount: charIndex,
+ charsCount: chars,
+ hasRtl: hasRtl || undefined,
};
}
@@ -1000,76 +639,30 @@ export class SlugGeometry {
fontSize: number,
letterSpacing: number,
pathOptions: TextPathOptions,
- applyBy: "line" | "word" | "char" = "word",
+ applyBy: ApplyBy = "word",
+ direction: TextDirection = "auto",
): SlugLayoutResult {
const fontScale = fontSize / font.unitsPerEm;
const segments = generatePathSegments(pathOptions.path);
const chainLUT = buildPathLUT(segments);
const totalLength = chainLUT.totalLength;
- const graphemes = segmentGraphemes(text);
-
- interface TokenChar {
- char: string;
- cp: SlugCodePoint | null;
- isEmoji: boolean;
- isSpace: boolean;
- advance: number;
- charIndex: number;
- wordIndex: number;
- unitIndex: number;
- }
-
- const chars: TokenChar[] = [];
- let wordIndex = 0;
- let charIndex = 0;
- let inWord = false;
-
- for (const char of graphemes) {
- if (char === "\uFE0F" || char === "\uFE0E" || char === "\u200D") {
- continue;
- }
- const isSpace = /^\s+$/.test(char);
- const isEmoji = EMOJI_REGEX.test(char);
- let cp: SlugCodePoint | null = null;
- let advance = 0;
-
- if (isEmoji) {
- advance = fontSize;
- } else {
- const codePoint = char.codePointAt(0) || 0;
- cp = font.codePoints.get(codePoint) || font.codePoints.get(-1) || null;
- advance = (cp?.advanceWidth || 0) * fontScale;
- }
-
- if (isSpace) {
- if (inWord) {
- wordIndex++;
- inWord = false;
- }
- } else {
- if (!inWord) {
- inWord = true;
- }
- }
-
- let unitIdx = charIndex;
- if (applyBy === "word") unitIdx = wordIndex;
- else if (applyBy === "line") unitIdx = 0;
-
- chars.push({
- char,
- cp,
- isEmoji,
- isSpace,
- advance,
- charIndex,
- wordIndex,
- unitIndex: unitIdx,
- });
- charIndex++;
- }
- if (inWord) wordIndex++;
+ // Path text is a single line: shape it whole, then lay it along the
+ // path in display order.
+ const shaped = shapeParagraph(
+ [
+ {
+ text: text.replace(/\n/g, " "),
+ style: { font, fontSize, letterSpacing },
+ },
+ ],
+ { direction, ligatures: useLigatures(applyBy, letterSpacing) },
+ );
+ const clusters = shaped.clusters;
+ const { indices, words, chars } = assignIndices([clusters], applyBy);
+ const visual = placeLine(clusters, shaped.baseLevel).clusters.map(
+ (p) => p.cluster,
+ );
let baselineOffsetPixels = 0;
if (pathOptions.baselineOffset === "center") {
@@ -1090,70 +683,67 @@ export class SlugGeometry {
// Last Margin); force alignment spreads the line across what is left.
const effEnd = Math.max(firstMargin, totalLength - lastMargin);
const pathSpan = effEnd - firstMargin;
- const advanceAt = (i: number): number => {
- const ch = chars[i];
- const next = chars[i + 1];
- const kern =
- next && !ch.isSpace && !next.isSpace && ch.cp && next.cp
- ? getKernOffset(font, ch.cp.codePoint, next.cp.codePoint) * fontScale
- : 0;
- return ch.advance + letterSpacing + kern;
- };
- // The natural run: every advance but the last glyph's own width counts once.
+ // The natural run: every advance but the last cluster's own width counts once.
let naturalLength = 0;
- for (let i = 0; i < chars.length; i++)
- naturalLength += i < chars.length - 1 ? advanceAt(i) : chars[i].advance;
+ for (let i = 0; i < visual.length; i++) {
+ const c = visual[i];
+ naturalLength +=
+ i < visual.length - 1 ? c.advance : c.advance - c.spacing;
+ }
const forceAlignExtra =
- pathOptions.forceAlignment && chars.length > 1
- ? (pathSpan - naturalLength) / (chars.length - 1)
+ pathOptions.forceAlignment && visual.length > 1
+ ? (pathSpan - naturalLength) / (visual.length - 1)
: 0;
- let currentDistance = firstMargin;
-
- for (let i = 0; i < chars.length; i++) {
- const ch = chars[i];
- const d = currentDistance;
-
+ const perpendicular = pathOptions.perpendicularToPath !== false;
+ const sampleAt = (d: number) => {
let s = pathOptions.reversePath ? totalLength - d : d;
if (pathOptions.loop && totalLength > 0) {
s = ((s % totalLength) + totalLength) % totalLength;
}
+ return samplePathChainGeometry(segments, chainLUT, s);
+ };
- const sample = samplePathChainGeometry(segments, chainLUT, s);
- const glyphX = sample.position.x + sample.normal.x * totalShift;
- const glyphY = sample.position.y + sample.normal.y * totalShift;
- const tangentRad =
- pathOptions.perpendicularToPath !== false
- ? (sample.tangentAngleDeg * Math.PI) / 180
- : 0;
-
- if (ch.isEmoji) {
+ let currentDistance = firstMargin;
+ for (const c of visual) {
+ const idx = indices.get(c) as LogicalIndices;
+ if (c.isEmoji) {
+ const sample = sampleAt(currentDistance + c.inkStart);
emojis.push({
- char: ch.char,
- x: glyphX,
- y: glyphY - fontSize,
+ char: c.text,
+ x: sample.position.x + sample.normal.x * totalShift,
+ y: sample.position.y + sample.normal.y * totalShift - fontSize,
size: fontSize,
lineIndex: 0,
});
- } else if (ch.cp) {
- glyphs.push({
- char: ch.char,
- cp: ch.cp,
- x: glyphX,
- y: glyphY,
- lineIndex: 0,
- wordIndex: ch.wordIndex,
- charIndex: ch.charIndex,
- unitIndex: ch.unitIndex,
- isSpace: ch.isSpace,
- pathTangentAngleRad: tangentRad,
- perpendicularToPath: pathOptions.perpendicularToPath !== false,
- pathNormalX: sample.normal.x,
- pathNormalY: sample.normal.y,
- });
+ } else {
+ for (const g of c.glyphs) {
+ // Each glyph (a mark too) sits where its own offset lands on the path.
+ const sample = sampleAt(currentDistance + g.dx);
+ const shift = totalShift + g.dy;
+ glyphs.push({
+ char: c.text,
+ cp: g.cp,
+ x: sample.position.x + sample.normal.x * shift,
+ y: sample.position.y + sample.normal.y * shift,
+ lineIndex: 0,
+ wordIndex: idx.wordIndex,
+ charIndex: idx.charIndex,
+ unitIndex: applyBy === "line" ? 0 : idx.unitIndex,
+ isSpace: c.isSpace,
+ textIndex: c.start,
+ rtl: (c.level & 1) === 1,
+ clusterAdvance: c.advance - c.spacing,
+ pathTangentAngleRad: perpendicular
+ ? (sample.tangentAngleDeg * Math.PI) / 180
+ : 0,
+ perpendicularToPath: perpendicular,
+ pathNormalX: sample.normal.x,
+ pathNormalY: sample.normal.y,
+ });
+ }
}
-
- currentDistance += advanceAt(i) + forceAlignExtra;
+ currentDistance += c.advance + forceAlignExtra;
}
return {
@@ -1161,8 +751,12 @@ export class SlugGeometry {
emojis,
totalHeight: fontSize * 1.5,
linesCount: 1,
- wordsCount: wordIndex,
- charsCount: charIndex,
+ wordsCount: words,
+ charsCount: chars,
+ hasRtl:
+ shaped.baseLevel & 1 || clusters.some((c) => c.level & 1)
+ ? true
+ : undefined,
};
}
}
diff --git a/packages/webgpu-renderers/src/slug/slug-loader.ts b/packages/webgpu-renderers/src/slug/slug-loader.ts
index cbc7503c..acfbe492 100644
--- a/packages/webgpu-renderers/src/slug/slug-loader.ts
+++ b/packages/webgpu-renderers/src/slug/slug-loader.ts
@@ -1,10 +1,15 @@
import { debugLog } from "../debug-log.js";
const SLUGGISH_HEADER_DATA = "SLUGGISH";
+/** v2 adds a glyph id to every record, so shaped (unmapped) glyphs round-trip. */
+const SLUGGISH_HEADER_DATA_V2 = "SLUGGIS2";
const TEXTURE_WIDTH = 4096;
export interface SlugCodePoint {
+ /** Unicode code point, -1 for .notdef, or -2 for a glyph no code point maps to. */
codePoint: number;
+ /** The font's glyph id; shaping output refers to glyphs by this. */
+ glyphId?: number;
width: number;
height: number;
advanceWidth: number;
@@ -19,6 +24,8 @@ export interface SlugCodePoint {
export interface SlugFont {
codePoints: Map<number, SlugCodePoint>;
+ /** The same glyphs keyed by glyph id (shaped text looks glyphs up here). */
+ glyphs?: Map<number, SlugCodePoint>;
curvesTex: GPUTexture;
bandsTex: GPUTexture;
ascender: number;
@@ -30,6 +37,9 @@ export interface SlugFont {
weight?: number;
}
+/** `SlugCodePoint.codePoint` of a glyph that only shaping reaches. */
+export const UNMAPPED_CODE_POINT = -2;
+
export class SlugLoader {
static parse(device: GPUDevice, buffer: ArrayBuffer): SlugFont {
const startTime = performance.now();
@@ -42,20 +52,26 @@ export class SlugLoader {
for (let i = 0; i < 8; i++) {
headerStr += String.fromCharCode(headerBytes[i]);
}
- if (headerStr !== SLUGGISH_HEADER_DATA) {
+ const isV2 = headerStr === SLUGGISH_HEADER_DATA_V2;
+ if (headerStr !== SLUGGISH_HEADER_DATA && !isV2) {
throw new Error(
- `Invalid header found (${headerStr} instead of ${SLUGGISH_HEADER_DATA})`,
+ `Invalid header found (${headerStr} instead of ${SLUGGISH_HEADER_DATA_V2})`,
);
}
offset += 8;
- const codePointCount = dataView.getUint16(offset, true);
- offset += 2;
+ const codePointCount = isV2
+ ? dataView.getUint32(offset, true)
+ : dataView.getUint16(offset, true);
+ offset += isV2 ? 4 : 2;
const codePoints = new Map<number, SlugCodePoint>();
+ const glyphs = new Map<number, SlugCodePoint>();
for (let i = 0; i < codePointCount; i++) {
const cp: SlugCodePoint = {
- codePoint: dataView.getUint32(offset, true),
+ codePoint: isV2
+ ? dataView.getInt32(offset, true)
+ : dataView.getUint32(offset, true),
width: dataView.getUint32(offset + 4, true),
height: dataView.getUint32(offset + 8, true),
advanceWidth: dataView.getUint32(offset + 12, true),
@@ -67,8 +83,13 @@ export class SlugLoader {
bandsTexCoordX: dataView.getUint16(offset + 36, true),
bandsTexCoordY: dataView.getUint16(offset + 38, true),
};
- codePoints.set(cp.codePoint, cp);
- offset += 40;
+ if (isV2) {
+ cp.glyphId = dataView.getUint32(offset + 40, true);
+ glyphs.set(cp.glyphId, cp);
+ }
+ if (cp.codePoint !== UNMAPPED_CODE_POINT)
+ codePoints.set(cp.codePoint, cp);
+ offset += isV2 ? 44 : 40;
}
const curvesTexWidth = dataView.getUint16(offset, true);
@@ -166,6 +187,7 @@ export class SlugLoader {
return {
codePoints,
+ glyphs: isV2 ? glyphs : undefined,
curvesTex,
bandsTex,
ascender,
diff --git a/packages/webgpu-renderers/src/slug/text-shaping.test.ts b/packages/webgpu-renderers/src/slug/text-shaping.test.ts
new file mode 100644
index 00000000..e0f954d3
--- /dev/null
+++ b/packages/webgpu-renderers/src/slug/text-shaping.test.ts
@@ -0,0 +1,309 @@
+import fs from "node:fs";
+import * as fontkit from "fontkit";
+import { beforeAll, describe, expect, it } from "vitest";
+import {
+ createMockDevice,
+ ensureDOMGlobals,
+} from "../renderer2d/test-helpers.js";
+import { type FontkitFont, SlugGenerator } from "./slug-generator.js";
+import { SlugGeometry } from "./slug-geometry.js";
+import {
+ type SlugCodePoint,
+ type SlugFont,
+ SlugLoader,
+} from "./slug-loader.js";
+import { breakLines, placeLine, shapeParagraph } from "./text-shaping.js";
+
+beforeAll(() => {
+ ensureDOMGlobals();
+ if (typeof globalThis.GPUTextureUsage === "undefined") {
+ globalThis.GPUTextureUsage = {
+ TEXTURE_BINDING: 1,
+ COPY_DST: 2,
+ RENDER_ATTACHMENT: 4,
+ COPY_SRC: 8,
+ } as never;
+ }
+});
+
+/** A font with no shaping source: one 100-unit glyph per listed code point. */
+function mockFont(chars: string): SlugFont {
+ const codePoints = new Map<number, SlugCodePoint>();
+ const add = (codePoint: number, advanceWidth: number) =>
+ codePoints.set(codePoint, {
+ codePoint,
+ width: advanceWidth > 0 ? 80 : 0,
+ height: advanceWidth > 0 ? 700 : 0,
+ advanceWidth,
+ bearingX: 10,
+ bearingY: 700,
+ bandCount: 1,
+ bandDimX: 8,
+ bandDimY: 8,
+ bandsTexCoordX: 0,
+ bandsTexCoordY: 0,
+ });
+ add(-1, 100);
+ for (const ch of chars) add(ch.codePointAt(0) ?? 0, ch === " " ? 50 : 100);
+ return {
+ codePoints,
+ curvesTex: null as never,
+ bandsTex: null as never,
+ ascender: 800,
+ descender: -200,
+ lineGap: 0,
+ unitsPerEm: 1000,
+ };
+}
+
+const HEBREW = "אבגדהוזחטיכלמנסעפצקרשת";
+const font = mockFont(`${HEBREW}ABCDEFGHIJ0123456789 ()[]!.,-`);
+const style = { font, fontSize: 10, letterSpacing: 0 };
+
+/** Visual (left-to-right) text of one laid-out paragraph line. */
+function visualText(text: string, direction?: "ltr" | "rtl" | "auto") {
+ const p = shapeParagraph([{ text, style }], { direction });
+ const line = placeLine(p.clusters, p.baseLevel);
+ return {
+ text: line.clusters.map((c) => c.cluster.text).join(""),
+ baseLevel: p.baseLevel,
+ line,
+ };
+}
+
+describe("bidi ordering", () => {
+ it("keeps left-to-right text in logical order", () => {
+ const { text, baseLevel } = visualText("AB CD");
+ expect(baseLevel).toBe(0);
+ expect(text).toBe("AB CD");
+ });
+
+ it("reverses a right-to-left paragraph and detects its direction", () => {
+ const { text, baseLevel } = visualText("אב גד");
+ expect(baseLevel).toBe(1);
+ expect(text).toBe("דג בא");
+ });
+
+ it("keeps Latin words and numbers left to right inside RTL text", () => {
+ // Digits after a Latin word join its left-to-right run (UAX #9 W7).
+ expect(visualText("אב CD 2026 גד").text).toBe("דג CD 2026 בא");
+ expect(visualText("אב 2026 גד").text).toBe("דג 2026 בא");
+ });
+
+ it("honours an explicit base direction", () => {
+ // LTR base: the Hebrew word reverses in place, the sentence stays LTR.
+ expect(visualText("AB אב CD", "ltr").text).toBe("AB בא CD");
+ // RTL base: the Latin run moves to the right-to-left reading position.
+ const rtl = visualText("AB CD", "rtl");
+ expect(rtl.baseLevel).toBe(1);
+ expect(rtl.text).toBe("AB CD");
+ });
+
+ it("mirrors brackets in right-to-left runs", () => {
+ const p = shapeParagraph([{ text: "(אב)", style }]);
+ const line = placeLine(p.clusters, p.baseLevel);
+ const glyphCps = line.clusters.map((c) => c.cluster.glyphs[0].cp.codePoint);
+ // Displayed as "(בא)": the logical ")" shows as "(" on the left.
+ expect(glyphCps[0]).toBe("(".codePointAt(0));
+ expect(glyphCps[glyphCps.length - 1]).toBe(")".codePointAt(0));
+ });
+
+ it("treats emoji as neutral, not as strong left-to-right text", () => {
+ const { text } = visualText("אב 😀 גד");
+ expect(text).toBe("דג 😀 בא");
+ });
+});
+
+describe("RTL line layout", () => {
+ it("wraps from the right: the first words stay on the first line", () => {
+ const p = shapeParagraph([{ text: "אב גד הו זח", style }]);
+ // Each word is 2px wide, each space 0.5px: two words fit in 5px.
+ const lines = breakLines(p.clusters, 5);
+ expect(
+ lines.map((l) =>
+ l
+ .map((c) => c.text)
+ .join("")
+ .trim(),
+ ),
+ ).toEqual(["אב גד", "הו זח"]);
+ });
+
+ it("aligns start to the right edge and keeps trailing spaces out of the ink", () => {
+ const result = SlugGeometry.layout(
+ "אב גד",
+ font,
+ 10,
+ 0,
+ 12,
+ 100,
+ "start",
+ "char",
+ );
+ const visible = result.glyphs.filter((g) => !g.isSpace);
+ const right = Math.max(...visible.map((g) => g.x + 1));
+ expect(right).toBeCloseTo(100, 5);
+ expect(result.hasRtl).toBe(true);
+ });
+
+ it("numbers characters in reading order", () => {
+ const result = SlugGeometry.layout(
+ "אבג",
+ font,
+ 10,
+ 0,
+ 12,
+ 100,
+ "left",
+ "char",
+ );
+ const byIndex = [...result.glyphs].sort(
+ (a, b) => a.charIndex - b.charIndex,
+ );
+ expect(byIndex.map((g) => g.char).join("")).toBe("אבג");
+ // The first character read sits rightmost.
+ expect(byIndex[0].x).toBeGreaterThan(byIndex[2].x);
+ expect(byIndex.every((g) => g.rtl)).toBe(true);
+ });
+
+ it("orders rich-text spans visually and keeps each span's style", () => {
+ const result = SlugGeometry.layout(
+ "אב גד",
+ font,
+ 10,
+ 0,
+ 12,
+ 100,
+ "left",
+ "word",
+ undefined,
+ undefined,
+ [{ text: "אב " }, { text: "גד", fill: "#ff0000" }],
+ );
+ const red = result.glyphs.filter((g) => g.fill === "#ff0000");
+ const plain = result.glyphs.filter((g) => !g.fill && !g.isSpace);
+ expect(red.map((g) => g.char).join("")).toBe("גד");
+ // The second span is read second, so it sits to the left.
+ expect(Math.max(...red.map((g) => g.x))).toBeLessThan(
+ Math.min(...plain.map((g) => g.x)),
+ );
+ });
+
+ it("lays out LTR text exactly as before", () => {
+ const result = SlugGeometry.layout("AB CD", font, 10, 0, 12, 100, "left");
+ expect(result.glyphs.map((g) => g.x)).toEqual([0, 1, 2, 2.5, 3.5]);
+ expect(result.wordsCount).toBe(2);
+ expect(result.charsCount).toBe(5);
+ expect(result.hasRtl).toBeUndefined();
+ });
+});
+
+describe("Slug binary format", () => {
+ it("still reads v1 (SLUGGISH) binaries", () => {
+ const glyphRecord = 40;
+ const curvesBytes = 4096 * 16;
+ const bandsBytes = 4096 * 8;
+ const buffer = new ArrayBuffer(
+ 8 + 2 + glyphRecord + 8 + curvesBytes + 8 + bandsBytes + 16,
+ );
+ const view = new DataView(buffer);
+ let o = 0;
+ for (const ch of "SLUGGISH") view.setUint8(o++, ch.charCodeAt(0));
+ view.setUint16(o, 1, true);
+ o += 2;
+ view.setUint32(o, 65, true); // codePoint
+ view.setUint32(o + 12, 600, true); // advanceWidth
+ o += glyphRecord;
+ view.setUint16(o, 4096, true);
+ view.setUint16(o + 2, 1, true);
+ view.setUint32(o + 4, curvesBytes, true);
+ o += 8 + curvesBytes;
+ view.setUint16(o, 4096, true);
+ view.setUint16(o + 2, 1, true);
+ view.setUint32(o + 4, bandsBytes, true);
+ o += 8 + bandsBytes;
+ view.setInt32(o + 12, 1000, true); // unitsPerEm
+
+ const parsed = SlugLoader.parse(createMockDevice(), buffer);
+ expect(parsed.codePoints.get(65)?.advanceWidth).toBe(600);
+ expect(parsed.glyphs).toBeUndefined();
+ expect(parsed.unitsPerEm).toBe(1000);
+ });
+});
+
+// ── Real fonts (macOS ships these; elsewhere the tests skip) ─────────────
+
+function loadSystemFont(path: string): FontkitFont | null {
+ if (!fs.existsSync(path)) return null;
+ const parsed = fontkit.create(fs.readFileSync(path)) as unknown as
+ | FontkitFont
+ | { fonts: FontkitFont[] };
+ return "fonts" in parsed ? parsed.fonts[0] : parsed;
+}
+
+const sfArabic = loadSystemFont("/System/Library/Fonts/SFArabic.ttf");
+
+describe.skipIf(!sfArabic)("Arabic shaping (SF Arabic)", () => {
+ const source = sfArabic as FontkitFont;
+
+ it("generates the shaped forms on demand and joins letters", () => {
+ const slug = new SlugGenerator().generate(null, source);
+ const before = slug.glyphs?.size ?? 0;
+ const p = shapeParagraph([
+ {
+ text: "لازم نتعلّم",
+ style: { font: slug, fontSize: 90, letterSpacing: 0 },
+ },
+ ]);
+ // Arabic was not in the default set: shaping generated its glyphs.
+ expect(slug.glyphs?.size ?? 0).toBeGreaterThan(before);
+ // Joined forms are not the isolated cmap glyphs.
+ const nun = source.glyphForCodePoint?.("ن".codePointAt(0) ?? 0)?.id;
+ const nunCluster = p.clusters.find((c) => c.text === "ن");
+ expect(nunCluster?.glyphs.some((g) => g.cp.glyphId === nun)).toBe(false);
+ });
+
+ it("forms lam-alef and keeps the shadda with its letter", () => {
+ const slug = new SlugGenerator().generate(null, source);
+ const p = shapeParagraph([
+ {
+ text: "لازم نتعلّم",
+ style: { font: slug, fontSize: 90, letterSpacing: 0 },
+ },
+ ]);
+ const texts = p.clusters.map((c) => c.text);
+ expect(texts).toContain("لا");
+ expect(texts).toContain("لّ");
+ const lamShadda = p.clusters.find((c) => c.text === "لّ");
+ // Base and mark: two glyphs, the mark raised above the baseline.
+ expect(lamShadda?.glyphs.length).toBe(2);
+ expect(
+ Math.min(...(lamShadda?.glyphs.map((g) => g.dy) ?? [0])),
+ ).toBeLessThan(0);
+ });
+
+ it("re-uploads textures when glyphs are added after the first upload", () => {
+ const device = createMockDevice();
+ const slug = new SlugGenerator().generate(device, source);
+ const firstTex = slug.curvesTex;
+ const id = source.glyphForCodePoint?.("ع".codePointAt(0) ?? 0)?.id ?? 0;
+ expect(SlugGenerator.ensureGlyphs(slug, [id])).toBe(true);
+ expect(slug.curvesTex).not.toBe(firstTex);
+ expect(slug.glyphs?.get(id)?.glyphId).toBe(id);
+ // Asking again is a no-op.
+ expect(SlugGenerator.ensureGlyphs(slug, [id])).toBe(false);
+ });
+
+ it("round-trips shaped glyphs through the v2 binary", () => {
+ const slug = new SlugGenerator().generate(null, source);
+ shapeParagraph([
+ { text: "لا", style: { font: slug, fontSize: 90, letterSpacing: 0 } },
+ ]);
+ const buffer = new SlugGenerator().exportSluggish(slug);
+ const parsed = SlugLoader.parse(createMockDevice(), buffer);
+ expect(parsed.glyphs?.size).toBe(slug.glyphs?.size);
+ for (const [id, cp] of slug.glyphs ?? []) {
+ expect(parsed.glyphs?.get(id)?.advanceWidth).toBe(cp.advanceWidth);
+ }
+ });
+});
diff --git a/packages/webgpu-renderers/src/slug/text-shaping.ts b/packages/webgpu-renderers/src/slug/text-shaping.ts
new file mode 100644
index 00000000..1a03f772
--- /dev/null
+++ b/packages/webgpu-renderers/src/slug/text-shaping.ts
@@ -0,0 +1,760 @@
+/**
+ * Turns styled text into positioned glyph clusters: Unicode bidi levels
+ * (bidi-js), OpenType shaping per run (fontkit: GSUB joining forms and
+ * ligatures, GPOS kerning and mark placement), then line breaking and the
+ * per-line visual reordering of UAX #9 (L1, L2).
+ *
+ * Clusters stay in logical (reading) order until {@link placeLine}, so line
+ * breaking, word/char indices and typewriter prefixes all follow the text.
+ */
+import bidiFactory from "bidi-js";
+import {
+ type FontkitFont,
+ type FontkitGlyph,
+ getSlugFontSource,
+ SlugGenerator,
+} from "./slug-generator.js";
+import type { SlugCodePoint, SlugFont } from "./slug-loader.js";
+
+/** Base direction of a paragraph. `auto` takes it from the first strong character. */
+export type TextDirection = "ltr" | "rtl" | "auto";
+
+export interface ShapeStyle {
+ font: SlugFont;
+ fontSize: number;
+ letterSpacing: number;
+}
+
+export interface ShapedGlyph {
+ cp: SlugCodePoint;
+ /** Pen offset from the cluster's visual left edge, px. */
+ dx: number;
+ /** Baseline offset, px, positive down. */
+ dy: number;
+}
+
+export interface ShapedCluster<S extends ShapeStyle = ShapeStyle> {
+ /** Source text of the cluster: one grapheme, or several a ligature joined. */
+ text: string;
+ /** UTF-16 offset of the cluster in the paragraph. */
+ start: number;
+ style: S;
+ isSpace: boolean;
+ isEmoji: boolean;
+ /** Bidi embedding level; odd is right-to-left. */
+ level: number;
+ /** Glyphs in visual order. */
+ glyphs: ShapedGlyph[];
+ /** Pen advance including the letter spacing, px. */
+ advance: number;
+ /** Letter spacing included in `advance`; it trails the cluster in reading order. */
+ spacing: number;
+ /** Visible span within the advance, px from the cluster's left edge. */
+ inkStart: number;
+ inkEnd: number;
+}
+
+interface ShapedParagraph<S extends ShapeStyle = ShapeStyle> {
+ clusters: ShapedCluster<S>[];
+ /** Paragraph embedding level: 0 left-to-right, 1 right-to-left. */
+ baseLevel: number;
+}
+
+interface ShapeOptions {
+ direction?: TextDirection;
+ /** Optional ligatures (`liga`, `clig`); required ones such as lam-alef always apply. */
+ ligatures?: boolean;
+}
+
+const EMOJI_REGEX =
+ /(\p{Extended_Pictographic}|\p{Emoji_Presentation}|[☀-➿])/u;
+
+/** Characters that make bidi analysis necessary (RTL letters and explicit RTL controls). */
+const RTL_REGEX = /[֐-ࣿיִ-﷿ﹰ-‏‫‮⁧\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
+
+/**
+ * Scripts whose letters join; letter spacing would break the joins, so CSS
+ * says not to apply it there (Arabic, Syriac, Thaana, N'Ko, Mongolian, …).
+ */
+const CURSIVE_REGEX = /[؀-ࣿﭐ-﷿ﹰ-᠀-᢯\u{10D00}-\u{10D3F}\u{10F30}-\u{10F6F}]/u;
+
+const SPACE_REGEX = /^\s+$/;
+
+type Bidi = ReturnType<typeof bidiFactory>;
+let bidiInstance: Bidi | null = null;
+function bidi(): Bidi {
+ bidiInstance ??= bidiFactory();
+ return bidiInstance;
+}
+
+/** BMP stand-ins with the same bidi class, for astral characters bidi-js reads per UTF-16 unit. */
+const BIDI_STAND_INS: Record<string, string> = {
+ L: "a",
+ R: "א",
+ AL: "ا",
+ EN: "0",
+ AN: "٠",
+ ES: "+",
+ ET: "#",
+ CS: ",",
+ NSM: "̀",
+ BN: "​",
+ WS: " ",
+ ON: "!",
+};
+
+function bidiLevels(
+ text: string,
+ direction: TextDirection,
+): { levels: Uint8Array; baseLevel: number } {
+ const b = bidi();
+ // bidi-js classifies each UTF-16 unit on its own, so a surrogate pair (an
+ // emoji, say) would read as two strong left-to-right characters.
+ let analysed = text;
+ if (/[\uD800-\uDBFF]/.test(text)) {
+ let out = "";
+ for (const ch of text) {
+ if (ch.length === 1) {
+ out += ch;
+ continue;
+ }
+ const stand = BIDI_STAND_INS[b.getBidiCharTypeName(ch)] ?? "!";
+ out += stand + stand;
+ }
+ analysed = out;
+ }
+ const result = b.getEmbeddingLevels(
+ analysed,
+ direction === "auto" ? undefined : direction,
+ );
+ return {
+ levels: result.levels,
+ baseLevel: result.paragraphs[0]?.level ?? (direction === "rtl" ? 1 : 0),
+ };
+}
+
+interface Grapheme {
+ text: string;
+ start: number;
+}
+
+const graphemeSegmenter: {
+ segment(text: string): Iterable<{ segment: string; index: number }>;
+} | null =
+ typeof Intl !== "undefined" &&
+ typeof (Intl as { Segmenter?: unknown }).Segmenter === "function"
+ ? new (
+ Intl as unknown as {
+ Segmenter: new (
+ locale: string | undefined,
+ opts: { granularity: string },
+ ) => {
+ segment(text: string): Iterable<{ segment: string; index: number }>;
+ };
+ }
+ ).Segmenter(undefined, { granularity: "grapheme" })
+ : null;
+
+function segmentGraphemes(text: string): Grapheme[] {
+ const out: Grapheme[] = [];
+ if (graphemeSegmenter) {
+ for (const s of graphemeSegmenter.segment(text)) {
+ out.push({ text: s.segment, start: s.index });
+ }
+ return out;
+ }
+ let i = 0;
+ for (const ch of text) {
+ out.push({ text: ch, start: i });
+ i += ch.length;
+ }
+ return out;
+}
+
+// ── Shaping ──────────────────────────────────────────────────────────────
+
+interface RunGlyph {
+ cp: SlugCodePoint;
+ /** UTF-16 offset in the run of the glyph's first character. */
+ offset: number;
+ /** UTF-16 offset just past the glyph's last character. */
+ end: number;
+ xAdvance: number;
+ xOffset: number;
+ yOffset: number;
+}
+
+const objectIds = new WeakMap<object, number>();
+let nextObjectId = 1;
+function objectId(o: object): number {
+ let id = objectIds.get(o);
+ if (id === undefined) {
+ id = nextObjectId++;
+ objectIds.set(o, id);
+ }
+ return id;
+}
+
+/** A stable identity for a font, for cache keys (family names are shared by weights). */
+export function fontIdentity(font: SlugFont): number {
+ return objectId(font);
+}
+
+const SHAPE_CACHE_MAX = 2048;
+const shapeCache = new Map<string, RunGlyph[]>();
+
+function resolveShapingSource(font: SlugFont): FontkitFont | null {
+ const own = getSlugFontSource(font);
+ if (own) return own;
+ if (!font.fontFamily) return null;
+ const parsed = (globalThis as Record<symbol, unknown>)[
+ Symbol.for("gatewai.slugFontCache.parsed")
+ ] as Map<string, FontkitFont> | undefined;
+ return parsed?.get(font.fontFamily) ?? null;
+}
+
+function notdef(font: SlugFont): SlugCodePoint | undefined {
+ return font.codePoints.get(-1) ?? font.glyphs?.get(0);
+}
+
+/** Looks a code point up, generating its glyph on first use. */
+function glyphForCodePoint(
+ font: SlugFont,
+ codePoint: number,
+): SlugCodePoint | undefined {
+ let cp = font.codePoints.get(codePoint);
+ if (!cp && SlugGenerator.ensureCodePoints(font, [codePoint])) {
+ cp = font.codePoints.get(codePoint);
+ }
+ return cp ?? notdef(font);
+}
+
+/** Invisible format characters (joiners, bidi controls, variation selectors). */
+function isIgnorable(cp: number): boolean {
+ return (
+ cp === 0x00ad ||
+ (cp >= 0x200b && cp <= 0x200f) ||
+ (cp >= 0x202a && cp <= 0x202e) ||
+ (cp >= 0x2060 && cp <= 0x206f) ||
+ (cp >= 0xfe00 && cp <= 0xfe0f) ||
+ cp === 0xfeff
+ );
+}
+
+function isIgnorableOnly(text: string): boolean {
+ for (const ch of text) {
+ if (!isIgnorable(ch.codePointAt(0) ?? 0)) return false;
+ }
+ return text.length > 0;
+}
+
+/** One glyph per code point through the cmap: fonts with no shaping source. */
+function mapRun(font: SlugFont, text: string): RunGlyph[] {
+ const out: RunGlyph[] = [];
+ let offset = 0;
+ for (const ch of text) {
+ const codePoint = ch.codePointAt(0) ?? 0;
+ if (isIgnorable(codePoint)) {
+ offset += ch.length;
+ continue;
+ }
+ const cp = glyphForCodePoint(font, codePoint);
+ if (cp) {
+ out.push({
+ cp,
+ offset,
+ end: offset + ch.length,
+ xAdvance: cp.advanceWidth,
+ xOffset: 0,
+ yOffset: 0,
+ });
+ }
+ offset += ch.length;
+ }
+ return out;
+}
+
+interface FontkitInternals {
+ glyphsForString?(text: string): FontkitGlyph[];
+ _layoutEngine?: {
+ engine?: {
+ glyphInfos?: Array<{ codePoints: number[] }> | null;
+ cleanup?: () => void;
+ };
+ };
+}
+
+const VARIATION_SELECTOR_REGEX = /[\uFE00-\uFE0F\u{E0100}-\u{E01EF}]/u;
+const MARK_REGEX = /^\p{M}$/u;
+
+/**
+ * Runs fontkit's layout and returns glyphs in logical order with the code
+ * points each one stands for.
+ *
+ * fontkit caches glyph objects per glyph id, and a cached glyph keeps the
+ * code points of whatever text created it first. The shapers read those code
+ * points (Arabic joining types, marks), and so would cluster mapping, so the
+ * run is fed fresh glyph copies carrying this text's code points, and the
+ * post-substitution code points are read from the engine's own glyph infos.
+ */
+function layoutWithCodePoints(
+ source: FontkitFont,
+ text: string,
+ rtl: boolean,
+ ligatures: boolean,
+): {
+ glyphs: FontkitGlyph[];
+ codePoints: number[][];
+ positions: Array<{ xAdvance: number; xOffset: number; yOffset: number }>;
+} | null {
+ const internals = source as FontkitFont & FontkitInternals;
+ if (typeof source.layout !== "function") return null;
+
+ let input: string | FontkitGlyph[] = text;
+ if (typeof internals.glyphsForString === "function") {
+ const base = internals.glyphsForString(text);
+ const chars = Array.from(text);
+ const fresh: FontkitGlyph[] = [];
+ let c = 0;
+ for (const g of base) {
+ while (c < chars.length && VARIATION_SELECTOR_REGEX.test(chars[c])) c++;
+ const cps: number[] = [];
+ if (c < chars.length) cps.push(chars[c++].codePointAt(0) ?? 0);
+ while (c < chars.length && VARIATION_SELECTOR_REGEX.test(chars[c])) {
+ cps.push(chars[c++].codePointAt(0) ?? 0);
+ }
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(g)), g, {
+ codePoints: cps,
+ isMark:
+ cps.length > 0 &&
+ cps.every((cp) => MARK_REGEX.test(String.fromCodePoint(cp))),
+ isLigature: cps.length > 1,
+ }) as FontkitGlyph;
+ fresh.push(copy);
+ }
+ input = fresh;
+ }
+
+ // Capture the engine's glyph infos before its cleanup drops them.
+ const engine = internals._layoutEngine?.engine;
+ let infos: Array<{ codePoints: number[] }> | null = null;
+ const originalCleanup = engine?.cleanup;
+ if (engine && typeof originalCleanup === "function") {
+ engine.cleanup = function (this: typeof engine) {
+ infos = this.glyphInfos ? this.glyphInfos.slice() : null;
+ return originalCleanup.call(this);
+ };
+ }
+ let run: ReturnType<NonNullable<FontkitFont["layout"]>>;
+ try {
+ run = (
+ source.layout as (
+ s: string | FontkitGlyph[],
+ ...rest: unknown[]
+ ) => ReturnType<NonNullable<FontkitFont["layout"]>>
+ )(
+ input,
+ ligatures ? {} : { liga: false, clig: false },
+ undefined,
+ undefined,
+ rtl ? "rtl" : "ltr",
+ );
+ } catch {
+ return null;
+ } finally {
+ if (engine && originalCleanup) {
+ delete (engine as { cleanup?: unknown }).cleanup;
+ if (engine.cleanup !== originalCleanup) engine.cleanup = originalCleanup;
+ }
+ }
+
+ // fontkit hands right-to-left runs back in visual order; work logically.
+ const glyphs = run.glyphs.slice();
+ const positions = run.positions.slice();
+ if (rtl) {
+ glyphs.reverse();
+ positions.reverse();
+ }
+ const captured = infos as Array<{ codePoints: number[] }> | null;
+ const codePoints =
+ captured && captured.length === glyphs.length
+ ? captured.map((info) => info.codePoints ?? [])
+ : glyphs.map((g) => g.codePoints ?? []);
+ return { glyphs, codePoints, positions };
+}
+
+function shapeRun(
+ font: SlugFont,
+ text: string,
+ rtl: boolean,
+ ligatures: boolean,
+): RunGlyph[] {
+ const source = resolveShapingSource(font);
+ if (!source || typeof source.layout !== "function") {
+ return mapRun(font, text);
+ }
+ const key = `${objectId(font)}|${rtl ? 1 : 0}|${ligatures ? 1 : 0}|${text}`;
+ const hit = shapeCache.get(key);
+ if (hit) return hit;
+
+ const shaped = layoutWithCodePoints(source, text, rtl, ligatures);
+ if (!shaped) return mapRun(font, text);
+ const { glyphs, codePoints: glyphCps, positions } = shaped;
+
+ // Code points of the run, with their UTF-16 offsets.
+ const runCps: number[] = [];
+ const cpOffsets: number[] = [];
+ {
+ let o = 0;
+ for (const ch of text) {
+ runCps.push(ch.codePointAt(0) ?? 0);
+ cpOffsets.push(o);
+ o += ch.length;
+ }
+ cpOffsets.push(o);
+ }
+
+ const ids = new Set<number>();
+ for (const g of glyphs) ids.add(g.id);
+ SlugGenerator.ensureGlyphs(font, ids);
+
+ const out: RunGlyph[] = [];
+ let cursor = 0;
+ let lastStart = 0;
+ for (let i = 0; i < glyphs.length; i++) {
+ const g = glyphs[i];
+ const cps = glyphCps[i];
+ const pos = positions[i];
+ const n = cps.length;
+ let start = lastStart;
+ let count = 0;
+ if (n > 0) {
+ // fontkit reports the characters each glyph stands for; find them in
+ // the run, tolerating substitutions that changed the code point.
+ start = Math.min(cursor, runCps.length - 1);
+ for (let k = cursor; k < Math.min(runCps.length, cursor + 8); k++) {
+ if (runCps[k] === cps[0]) {
+ start = k;
+ break;
+ }
+ }
+ count = Math.min(n, runCps.length - start);
+ cursor = Math.max(cursor, start + count);
+ lastStart = start;
+ }
+ const cp =
+ font.glyphs?.get(g.id) ??
+ (n > 0 ? font.codePoints.get(cps[0]) : undefined) ??
+ notdef(font);
+ if (!cp) continue;
+ out.push({
+ cp,
+ offset: cpOffsets[Math.max(0, start)] ?? 0,
+ end: cpOffsets[Math.max(0, start) + Math.max(1, count)] ?? text.length,
+ xAdvance: pos.xAdvance,
+ xOffset: pos.xOffset,
+ yOffset: pos.yOffset,
+ });
+ }
+
+ if (shapeCache.size >= SHAPE_CACHE_MAX) {
+ const first = shapeCache.keys().next().value;
+ if (first !== undefined) shapeCache.delete(first);
+ }
+ shapeCache.set(key, out);
+ return out;
+}
+
+// ── Paragraph ────────────────────────────────────────────────────────────
+
+/**
+ * Shapes one paragraph (no line breaks inside) given as styled segments.
+ * Returns its clusters in logical order and its resolved base level.
+ */
+export function shapeParagraph<S extends ShapeStyle>(
+ segments: ReadonlyArray<{ text: string; style: S }>,
+ options: ShapeOptions = {},
+): ShapedParagraph<S> {
+ const direction = options.direction ?? "auto";
+ const ligatures = options.ligatures ?? true;
+
+ let text = "";
+ const styleAt: S[] = [];
+ for (const seg of segments) {
+ text += seg.text;
+ for (let i = 0; i < seg.text.length; i++) styleAt.push(seg.style);
+ }
+ if (text.length === 0) {
+ return { clusters: [], baseLevel: direction === "rtl" ? 1 : 0 };
+ }
+
+ const needsBidi = direction === "rtl" || RTL_REGEX.test(text);
+ const analysis = needsBidi ? bidiLevels(text, direction) : null;
+ const levels = analysis?.levels ?? null;
+ const levelAt = (i: number) => (levels ? levels[i] : 0);
+ const baseLevel = analysis?.baseLevel ?? 0;
+
+ // Mirror brackets and the like inside right-to-left runs (bidi L4).
+ let shapeText = text;
+ if (levels) {
+ const b = bidi();
+ let mirrored = "";
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ mirrored += levels[i] & 1 ? (b.getMirroredCharacter(ch) ?? ch) : ch;
+ }
+ shapeText = mirrored;
+ }
+
+ const graphemes = segmentGraphemes(text);
+ const graphemeAt = new Int32Array(text.length);
+ for (let g = 0; g < graphemes.length; g++) {
+ const { start, text: gt } = graphemes[g];
+ for (let k = 0; k < gt.length; k++) graphemeAt[start + k] = g;
+ }
+ const isEmojiGrapheme = graphemes.map((g) => EMOJI_REGEX.test(g.text));
+
+ // Glyphs per grapheme, and ligature merges (a glyph spanning graphemes).
+ const glyphsOf: RunGlyph[][] = graphemes.map(() => []);
+ const mergeTo = new Int32Array(graphemes.length);
+ for (let g = 0; g < graphemes.length; g++) mergeTo[g] = g;
+
+ // Itemize: runs of one font/size and one level, emoji kept out.
+ let runStart = 0;
+ const flushRun = (end: number) => {
+ if (end <= runStart) return;
+ const style = styleAt[runStart];
+ const runText = shapeText.slice(runStart, end);
+ const rtl = (levelAt(runStart) & 1) === 1;
+ for (const rg of shapeRun(style.font, runText, rtl, ligatures)) {
+ const at = runStart + rg.offset;
+ const g0 = graphemeAt[Math.min(at, text.length - 1)];
+ const g1 = graphemeAt[Math.min(runStart + rg.end - 1, text.length - 1)];
+ glyphsOf[g0].push(rg);
+ for (let g = g0 + 1; g <= g1; g++) mergeTo[g] = mergeTo[g0];
+ }
+ };
+ for (let g = 0; g < graphemes.length; g++) {
+ const start = graphemes[g].start;
+ if (isEmojiGrapheme[g]) {
+ flushRun(start);
+ runStart = start + graphemes[g].text.length;
+ continue;
+ }
+ if (start > runStart) {
+ const prev = start - 1;
+ if (
+ styleAt[start].font !== styleAt[prev].font ||
+ styleAt[start].fontSize !== styleAt[prev].fontSize ||
+ levelAt(start) !== levelAt(prev)
+ ) {
+ flushRun(start);
+ runStart = start;
+ }
+ }
+ }
+ flushRun(text.length);
+
+ // Build clusters from (merged) graphemes.
+ const clusters: ShapedCluster<S>[] = [];
+ for (let g = 0; g < graphemes.length; ) {
+ let end = g + 1;
+ while (end < graphemes.length && mergeTo[end] === g) end++;
+ const start = graphemes[g].start;
+ const stop = end < graphemes.length ? graphemes[end].start : text.length;
+ const clusterText = text.slice(start, stop);
+ const style = styleAt[start];
+ const level = levelAt(start);
+ const rtl = (level & 1) === 1;
+ const scale = style.fontSize / style.font.unitsPerEm;
+ const isEmoji = isEmojiGrapheme[g];
+ const isSpace = SPACE_REGEX.test(clusterText);
+ if (isIgnorableOnly(clusterText)) {
+ // A stray joiner or variation selector: nothing to draw or count.
+ g = end;
+ continue;
+ }
+
+ const logical: RunGlyph[] = [];
+ for (let k = g; k < end; k++) logical.push(...glyphsOf[k]);
+ const visual = rtl ? logical.slice().reverse() : logical;
+
+ const spacing = CURSIVE_REGEX.test(clusterText) ? 0 : style.letterSpacing;
+ let glyphAdvance = 0;
+ const glyphs: ShapedGlyph[] = [];
+ if (isEmoji) {
+ glyphAdvance = style.fontSize;
+ } else {
+ const lead = rtl ? spacing : 0;
+ for (const rg of visual) {
+ glyphs.push({
+ cp: rg.cp,
+ dx: lead + glyphAdvance + rg.xOffset * scale,
+ dy: -rg.yOffset * scale,
+ });
+ glyphAdvance += rg.xAdvance * scale;
+ }
+ }
+ const inkStart = rtl ? spacing : 0;
+ clusters.push({
+ text: clusterText,
+ start,
+ style,
+ isSpace,
+ isEmoji,
+ level,
+ glyphs,
+ advance: glyphAdvance + spacing,
+ spacing,
+ inkStart,
+ inkEnd: inkStart + glyphAdvance,
+ });
+ g = end;
+ }
+
+ return { clusters, baseLevel };
+}
+
+// ── Lines ────────────────────────────────────────────────────────────────
+
+/**
+ * Greedy word wrap over clusters in logical order: breaks only between
+ * whitespace and non-whitespace runs, drops whitespace at the start of each
+ * line, and never splits a word.
+ */
+export function breakLines<S extends ShapeStyle>(
+ clusters: ShapedCluster<S>[],
+ maxWidth: number,
+): ShapedCluster<S>[][] {
+ const lines: ShapedCluster<S>[][] = [];
+ let line: ShapedCluster<S>[] = [];
+ let lineWidth = 0;
+
+ let i = 0;
+ while (i < clusters.length) {
+ const isSpace = clusters[i].isSpace;
+ let j = i;
+ let tokenWidth = 0;
+ while (j < clusters.length && clusters[j].isSpace === isSpace) {
+ tokenWidth += clusters[j].advance;
+ j++;
+ }
+ const token = clusters.slice(i, j);
+ i = j;
+
+ if (isSpace) {
+ if (line.length === 0) continue;
+ line.push(...token);
+ lineWidth += tokenWidth;
+ continue;
+ }
+ const trailing = token[token.length - 1].spacing;
+ const visualWidth = trailing > 0 ? tokenWidth - trailing : tokenWidth;
+ if (lineWidth > 0 && lineWidth + visualWidth > maxWidth) {
+ lines.push(line);
+ line = [];
+ lineWidth = 0;
+ }
+ line.push(...token);
+ lineWidth += tokenWidth;
+ }
+ lines.push(line);
+ return lines;
+}
+
+export interface PlacedCluster<S extends ShapeStyle = ShapeStyle> {
+ cluster: ShapedCluster<S>;
+ /** Left edge of the cluster on the line, px. */
+ x: number;
+}
+
+export interface PlacedLine<S extends ShapeStyle = ShapeStyle> {
+ /** Clusters left to right. */
+ clusters: PlacedCluster<S>[];
+ /** Visible extent of the line (whitespace and outer letter spacing excluded). */
+ inkLeft: number;
+ inkRight: number;
+}
+
+/**
+ * Orders one line's clusters for display (UAX #9 L1–L2) and lays them out
+ * left to right from x = 0.
+ */
+export function placeLine<S extends ShapeStyle>(
+ line: ShapedCluster<S>[],
+ baseLevel: number,
+): PlacedLine<S> {
+ const n = line.length;
+ const levels = new Array<number>(n);
+ let maxLevel = 0;
+ let minOdd = Number.POSITIVE_INFINITY;
+ // L1: whitespace at the end of the line takes the paragraph level.
+ let trailing = n;
+ while (trailing > 0 && line[trailing - 1].isSpace) trailing--;
+ for (let i = 0; i < n; i++) {
+ const level = i >= trailing ? baseLevel : line[i].level;
+ levels[i] = level;
+ if (level > maxLevel) maxLevel = level;
+ if (level & 1 && level < minOdd) minOdd = level;
+ }
+
+ const order = Array.from({ length: n }, (_, i) => i);
+ // L2: from the highest level down to the lowest odd one, reverse every run at or above it.
+ for (let level = maxLevel; level >= minOdd && level > 0; level--) {
+ let i = 0;
+ while (i < n) {
+ if (levels[order[i]] < level) {
+ i++;
+ continue;
+ }
+ let j = i;
+ while (j < n && levels[order[j]] >= level) j++;
+ const slice = order.slice(i, j).reverse();
+ for (let k = 0; k < slice.length; k++) order[i + k] = slice[k];
+ i = j;
+ }
+ }
+
+ const clusters: PlacedCluster<S>[] = [];
+ let x = 0;
+ let inkLeft = Number.POSITIVE_INFINITY;
+ let inkRight = Number.NEGATIVE_INFINITY;
+ for (const idx of order) {
+ const c = line[idx];
+ clusters.push({ cluster: c, x });
+ if (!c.isSpace) {
+ inkLeft = Math.min(inkLeft, x + c.inkStart);
+ inkRight = Math.max(inkRight, x + c.inkEnd);
+ }
+ x += c.advance;
+ }
+ if (inkLeft > inkRight) {
+ inkLeft = 0;
+ inkRight = 0;
+ }
+ return { clusters, inkLeft, inkRight };
+}
+
+/** Resolves `start`/`end` against a paragraph's direction. */
+export function resolveAlign(
+ align: "left" | "center" | "right" | "start" | "end",
+ baseLevel: number,
+): "left" | "center" | "right" {
+ const rtl = (baseLevel & 1) === 1;
+ if (align === "start") return rtl ? "right" : "left";
+ if (align === "end") return rtl ? "left" : "right";
+ return align;
+}
+
+/** Offset that aligns a placed line inside `width`. */
+export function alignOffset(
+ line: PlacedLine,
+ align: "left" | "center" | "right",
+ width: number,
+): number {
+ if (align === "center") {
+ return (width - (line.inkRight - line.inkLeft)) / 2 - line.inkLeft;
+ }
+ if (align === "right") return width - line.inkRight;
+ return -line.inkLeft;
+}
diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.md
index 7714a47d..8b6a1f38 100644
--- a/plugins/framefields/skills/framefields-compose/SKILL.md
+++ b/plugins/framefields/skills/framefields-compose/SKILL.md
@@ -84,7 +84,7 @@ All `Layer.*` builders return `AnimatableNode<T>` instances with chainable `.ani
| Builder | Node `kind` | Description & Key Options |
|---|---|---|
-| `Layer.text(content, options)` | `"text"` | Slug GPU vector text. Options: `fontSize`, `fontFamily`, `fill`, `letterSpacing`, `lineHeight`, `align`, `animators`, `spans`. |
+| `Layer.text(content, options)` | `"text"` | Slug GPU vector text. Options: `fontSize`, `fontFamily`, `fill`, `letterSpacing`, `lineHeight`, `align`, `direction`, `animators`, `spans`. Arabic, Hebrew and Persian are shaped and laid out right to left automatically (`direction: "auto"`); set `"rtl"`/`"ltr"` to force it. `align: "start"`/`"end"` follow the direction. |
| `Layer.box(options)` | `"box"` | Rectangular container / card. Options: `background`, `borderRadius`, `borderColor`, `borderWidth`, `overflow: "hidden"`, `padding`, `children`. |
| `Layer.flex(options)` | `"flex"` | Auto-layout container (Yoga). Options: `dir: "row" \| "column"`, `gap`, `justify`, `align`, `padding`, `wrap`, `children`. |
| `Layer.video(src, options)` | `"media"` | Video layer decoded via mediabunny. Options: `fit: "cover" \| "contain"`, `trimStartSec`, `muted`, `volume`. |
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ad9c1f8a..7365a1ba 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -394,6 +394,25 @@ importers:
specifier: ^5.8.3
version: 5.9.3
+ examples/26_mac_keyboard_from_3d_primitives:
+ dependencies:
+ framefields:
+ specifier: workspace:*
+ version: link:../../packages/framefields
+ devDependencies:
+ '@framefields/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/node':
+ specifier: ^24.1.0
+ version: 24.10.14
+ tsx:
+ specifier: ^4.20.3
+ version: 4.21.0
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+
nodes/node-apply-lut:
dependencies:
'@framefields/core':
@@ -2933,6 +2952,9 @@ importers:
'@resvg/resvg-js':
specifier: ^2.6.2
version: 2.6.2
+ bidi-js:
+ specifier: ^1.0.3
+ version: 1.0.3
earcut:
specifier: ^3.2.4
version: 3.2.4