@ascii-fx/compiler 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/{chunk-ZQML5MF3.js → chunk-HN45E6LL.js} +95 -20
- package/dist/chunk-HN45E6LL.js.map +1 -0
- package/dist/cli.js +4 -2
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +2 -0
- package/dist/font.d.ts +8 -1
- package/dist/fontkit.d.ts +14 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/profile.d.ts +4 -2
- package/package.json +4 -4
- package/dist/chunk-ZQML5MF3.js.map +0 -1
package/README.md
CHANGED
|
@@ -21,6 +21,8 @@ await writeFile('public/default.asciip', binary)
|
|
|
21
21
|
|
|
22
22
|
Rasterization is an in-house fixed-point scanline rasterizer over [fontkit](https://github.com/foliojs/fontkit)'s glyph outlines — **no system rasterizer anywhere in the path**. The same font and the same options produce byte-identical `.asciip` output on macOS, Linux, and CI.
|
|
23
23
|
|
|
24
|
+
Glyphs that are one code point the font maps rasterize straight from that glyph's outline. Anything else (a conjunct, a base letter with marks, an Arabic presentation form the font leaves unmapped) is shaped by fontkit first and the shaped run rasterized as one outline, so those profiles depend on fontkit's shaping as well as on the font. Golden fixtures built from committed Noto subsets pin every shaped Arabic, Devanagari, Thai and combining-mark glyph, so a fontkit update that moves one fails CI and names the glyph.
|
|
25
|
+
|
|
24
26
|
That matters because a profile's fingerprint is what a `.asciif` frame is validated against. If rasterization drifted between machines, frames compiled on your laptop would be refused by the same code running in CI. Golden-file tests pin it.
|
|
25
27
|
|
|
26
28
|
## Colour glyphs
|
|
@@ -49,6 +51,7 @@ A frame records the fingerprint of the profile it was built against and refuses
|
|
|
49
51
|
|
|
50
52
|
```sh
|
|
51
53
|
npx ascii-fx profile build --font GeistMono-Regular.ttf --out default.asciip
|
|
54
|
+
npx ascii-fx profile build --font "/System/Library/Fonts/GeezaPro.ttc" --face 0 --charset arabic-joined --out arabic.asciip
|
|
52
55
|
npx ascii-fx frame build --image hero.png --profile default.asciip --columns 160 --out hero.asciif
|
|
53
56
|
npx ascii-fx inspect default.asciip
|
|
54
57
|
```
|
|
@@ -1,14 +1,31 @@
|
|
|
1
1
|
// src/font.ts
|
|
2
2
|
import { Buffer } from "buffer";
|
|
3
3
|
import * as FK from "fontkit";
|
|
4
|
-
function loadFont(bytes) {
|
|
4
|
+
function loadFont(bytes, face) {
|
|
5
5
|
const create2 = FK.create ?? FK.default?.create;
|
|
6
6
|
if (!create2) throw new Error("fontkit did not expose create(); incompatible fontkit version.");
|
|
7
|
-
|
|
7
|
+
let font = create2(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
8
|
+
let collectionFace;
|
|
8
9
|
if (font.fonts && font.fonts.length > 0) {
|
|
9
|
-
|
|
10
|
+
const faces = font.fonts;
|
|
11
|
+
const list = faces.map((f, i) => `${i}: ${f.postscriptName ?? "(unnamed)"}`).join(", ");
|
|
12
|
+
if (face === void 0) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
`This is a font collection with ${faces.length} faces; pick one with \`face\` (a PostScript name or an index). Faces: ${list}.`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
const picked = typeof face === "number" ? faces[face] : faces.find((f) => f.postscriptName === face);
|
|
18
|
+
if (!picked)
|
|
19
|
+
throw new Error(`No face ${JSON.stringify(face)} in this collection. Faces: ${list}.`);
|
|
20
|
+
font = picked;
|
|
21
|
+
collectionFace = picked.postscriptName ?? String(faces.indexOf(picked));
|
|
22
|
+
} else if (face !== void 0 && face !== 0 && face !== font.postscriptName) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`\`face\` ${JSON.stringify(face)} was given, but this is a single font (${font.postscriptName ?? "unnamed"}), not a collection.`
|
|
25
|
+
);
|
|
10
26
|
}
|
|
11
27
|
return {
|
|
28
|
+
collectionFace,
|
|
12
29
|
font,
|
|
13
30
|
unitsPerEm: font.unitsPerEm,
|
|
14
31
|
ascent: font.ascent,
|
|
@@ -174,7 +191,11 @@ import { createHash } from "crypto";
|
|
|
174
191
|
import { readFileSync } from "fs";
|
|
175
192
|
import {
|
|
176
193
|
encodeProfile,
|
|
194
|
+
glyphOffset,
|
|
177
195
|
idiv as idiv2,
|
|
196
|
+
joiningSide,
|
|
197
|
+
kashidaText,
|
|
198
|
+
shapingText,
|
|
178
199
|
nextPow2,
|
|
179
200
|
rdiv as rdiv2,
|
|
180
201
|
resolveCharset,
|
|
@@ -220,25 +241,79 @@ function glyphShape6(lumas, out, at) {
|
|
|
220
241
|
for (let m = 0; m < 64; m++) dev += Math.abs(lumas[m] - v0);
|
|
221
242
|
out[at + 5] = dev / 64;
|
|
222
243
|
}
|
|
244
|
+
var IGNORABLE = new RegExp("^\\p{Default_Ignorable_Code_Point}+$", "u");
|
|
245
|
+
function glyphOutline(font, text) {
|
|
246
|
+
const cps = Array.from(text);
|
|
247
|
+
if (cps.length === 1) {
|
|
248
|
+
const cp = text.codePointAt(0);
|
|
249
|
+
if (font.hasGlyphForCodePoint(cp)) {
|
|
250
|
+
const g = font.glyphForCodePoint(cp);
|
|
251
|
+
return { commands: g.path.commands, advance: g.advanceWidth };
|
|
252
|
+
}
|
|
253
|
+
const context = shapingText(text);
|
|
254
|
+
return context === text ? null : shapeOutline(font, context);
|
|
255
|
+
}
|
|
256
|
+
return shapeOutline(font, text);
|
|
257
|
+
}
|
|
258
|
+
var openTypeFirst = /* @__PURE__ */ new WeakMap();
|
|
259
|
+
function shapingFont(font) {
|
|
260
|
+
const tables = font;
|
|
261
|
+
if (!tables.morx || !(tables.GSUB || tables.GPOS)) return font;
|
|
262
|
+
let view = openTypeFirst.get(font);
|
|
263
|
+
if (!view) {
|
|
264
|
+
view = Object.create(font, { morx: { value: void 0 } });
|
|
265
|
+
openTypeFirst.set(font, view);
|
|
266
|
+
}
|
|
267
|
+
return view;
|
|
268
|
+
}
|
|
269
|
+
function shapeOutline(font, text) {
|
|
270
|
+
const run = shapingFont(font).layout(text);
|
|
271
|
+
const commands = [];
|
|
272
|
+
let x = 0;
|
|
273
|
+
let drawn = 0;
|
|
274
|
+
for (let i = 0; i < run.glyphs.length; i++) {
|
|
275
|
+
const g = run.glyphs[i];
|
|
276
|
+
const p = run.positions[i];
|
|
277
|
+
if (g.id === 0) {
|
|
278
|
+
if (!IGNORABLE.test(String.fromCodePoint(...g.codePoints))) return null;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const dx = x + p.xOffset;
|
|
282
|
+
const dy = p.yOffset;
|
|
283
|
+
for (const c of g.path.commands) {
|
|
284
|
+
commands.push({
|
|
285
|
+
command: c.command,
|
|
286
|
+
args: c.args.map((v, j) => j % 2 === 0 ? v + dx : v + dy)
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
x += p.xAdvance;
|
|
290
|
+
drawn++;
|
|
291
|
+
}
|
|
292
|
+
return drawn === 0 ? null : { commands, advance: x };
|
|
293
|
+
}
|
|
223
294
|
function buildProfile(options) {
|
|
224
295
|
const { name: charsetName, glyphs } = resolveCharset(options.charset, options.characters);
|
|
225
|
-
const lf = loadFont(options.font);
|
|
226
|
-
const
|
|
296
|
+
const lf = loadFont(options.font, options.face);
|
|
297
|
+
const outlines = glyphs.map((g) => glyphOutline(lf.font, g));
|
|
298
|
+
const missing = glyphs.filter((_, i) => outlines[i] === null);
|
|
227
299
|
if (missing.length > 0) {
|
|
228
300
|
throw new Error(
|
|
229
301
|
`Font "${lf.familyName ?? "unknown"}" has no glyph for: ${missing.map(
|
|
230
|
-
(c) => `${JSON.stringify(c)} (U+${
|
|
302
|
+
(c) => `${JSON.stringify(c)} (${Array.from(c, (ch) => `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`).join(" ")})`
|
|
231
303
|
).join(", ")}. Remove them from the charset or pick a font that covers them.`
|
|
232
304
|
);
|
|
233
305
|
}
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
);
|
|
241
|
-
|
|
306
|
+
const shapes = outlines;
|
|
307
|
+
let advance = 0;
|
|
308
|
+
for (const g of shapes) if (g.advance > advance) advance = g.advance;
|
|
309
|
+
const tatweel = lf.font.hasGlyphForCodePoint(1600) ? lf.font.glyphForCodePoint(1600).advanceWidth : 0;
|
|
310
|
+
const kashida = tatweel > 0 ? idiv2(advance + tatweel - 1, tatweel) + 1 : 0;
|
|
311
|
+
const drawn = glyphs.map((g, i) => {
|
|
312
|
+
if (kashida === 0 || joiningSide(g) === null) return shapes[i];
|
|
313
|
+
const mapped = Array.from(g).length > 1 || lf.font.hasGlyphForCodePoint(g.codePointAt(0));
|
|
314
|
+
return shapeOutline(lf.font, kashidaText(mapped ? g : shapingText(g), kashida)) ?? shapes[i];
|
|
315
|
+
});
|
|
316
|
+
const shifts = shapes.map((g, i) => glyphOffset(glyphs[i], g.advance, advance, drawn[i].advance));
|
|
242
317
|
const unitsCell = lf.ascent - lf.descent;
|
|
243
318
|
if (!(unitsCell > 0))
|
|
244
319
|
throw new Error("Font reports non-positive ascent\u2212descent; cannot derive a cell box.");
|
|
@@ -246,10 +321,10 @@ function buildProfile(options) {
|
|
|
246
321
|
const cellW = Math.max(1, rdiv2(advance * REF_GLYPH_HEIGHT, unitsCell));
|
|
247
322
|
const baseline = rdiv2(lf.ascent * REF_GLYPH_HEIGHT, unitsCell);
|
|
248
323
|
const baselineFx = rdiv2(lf.ascent * REF_GLYPH_HEIGHT * 64, unitsCell);
|
|
249
|
-
const
|
|
250
|
-
x: (v) => rdiv2(v * REF_GLYPH_HEIGHT * 64, unitsCell),
|
|
324
|
+
const mapFor = (shift) => ({
|
|
325
|
+
x: (v) => rdiv2((v + shift) * REF_GLYPH_HEIGHT * 64, unitsCell),
|
|
251
326
|
y: (v) => baselineFx - rdiv2(v * REF_GLYPH_HEIGHT * 64, unitsCell)
|
|
252
|
-
};
|
|
327
|
+
});
|
|
253
328
|
const n = glyphs.length;
|
|
254
329
|
const masksLo = new Uint32Array(n);
|
|
255
330
|
const masksHi = new Uint32Array(n);
|
|
@@ -267,7 +342,7 @@ function buildProfile(options) {
|
|
|
267
342
|
const wantShape6 = options.shape6 !== void 0 && options.shape6 !== false;
|
|
268
343
|
const cellLumas = wantShape6 ? new Float64Array(n * 64) : void 0;
|
|
269
344
|
for (let i = 0; i < n; i++) {
|
|
270
|
-
const edges = flattenCommands(
|
|
345
|
+
const edges = flattenCommands(drawn[i].commands, mapFor(shifts[i]));
|
|
271
346
|
const raster = rasterizeGlyph(edges, cellW, cellH);
|
|
272
347
|
const mask = deriveMask(raster.maskHits, totals);
|
|
273
348
|
masksLo[i] = mask.lo;
|
|
@@ -315,7 +390,7 @@ function buildProfile(options) {
|
|
|
315
390
|
}
|
|
316
391
|
shape6 = { vectors6, lut3 };
|
|
317
392
|
}
|
|
318
|
-
const fontHash = sha256(options.font);
|
|
393
|
+
const fontHash = lf.collectionFace ? sha256(`${sha256(options.font)}|face:${lf.collectionFace}`) : sha256(options.font);
|
|
319
394
|
const charsetHash = sha256(glyphs.join("\0"));
|
|
320
395
|
const fingerprint = sha256(
|
|
321
396
|
`asciip/1|structural-v1|raster-v1|font:${fontHash}|charset:${charsetHash}|H:${REF_GLYPH_HEIGHT}|S:${SUPERSAMPLE}|pad:${ATLAS_PADDING}|quad:${QUAD_SEGMENTS}|cubic:${CUBIC_SEGMENTS}`
|
|
@@ -400,4 +475,4 @@ export {
|
|
|
400
475
|
buildFrame,
|
|
401
476
|
decodePng
|
|
402
477
|
};
|
|
403
|
-
//# sourceMappingURL=chunk-
|
|
478
|
+
//# sourceMappingURL=chunk-HN45E6LL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/font.ts","../src/raster.ts","../src/profile.ts","../src/frameBuild.ts","../src/png.ts"],"sourcesContent":["import { Buffer } from 'node:buffer'\nimport * as FK from 'fontkit'\nimport type { Font } from 'fontkit'\n\nexport interface LoadedFont {\n font: Font\n unitsPerEm: number\n ascent: number\n descent: number\n lineGap: number\n familyName?: string\n weight?: number\n /** Set when the face came out of a collection: the bytes alone no longer identify the font. */\n collectionFace?: string\n}\n\n/**\n * Parse a font. A collection (.ttc/.otc) holds several faces, and CJK and Arabic system fonts\n * ship that way almost without exception, so `face` picks one: a PostScript name, or an index\n * into the collection. It is required for a collection, which has no meaningful default.\n */\nexport function loadFont(bytes: Uint8Array, face?: string | number): LoadedFont {\n const create =\n (FK as { create?: typeof FK.create }).create ??\n (FK as { default?: { create: typeof FK.create } }).default?.create\n if (!create) throw new Error('fontkit did not expose create(); incompatible fontkit version.')\n let font = create(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n let collectionFace: string | undefined\n if (font.fonts && font.fonts.length > 0) {\n const faces = font.fonts\n const list = faces.map((f, i) => `${i}: ${f.postscriptName ?? '(unnamed)'}`).join(', ')\n if (face === undefined) {\n throw new Error(\n `This is a font collection with ${faces.length} faces; pick one with \\`face\\` ` +\n `(a PostScript name or an index). Faces: ${list}.`,\n )\n }\n const picked =\n typeof face === 'number' ? faces[face] : faces.find((f) => f.postscriptName === face)\n if (!picked)\n throw new Error(`No face ${JSON.stringify(face)} in this collection. Faces: ${list}.`)\n font = picked\n collectionFace = picked.postscriptName ?? String(faces.indexOf(picked))\n } else if (face !== undefined && face !== 0 && face !== font.postscriptName) {\n throw new Error(\n `\\`face\\` ${JSON.stringify(face)} was given, but this is a single font ` +\n `(${font.postscriptName ?? 'unnamed'}), not a collection.`,\n )\n }\n return {\n collectionFace,\n font,\n unitsPerEm: font.unitsPerEm,\n ascent: font.ascent,\n descent: font.descent,\n lineGap: font.lineGap,\n familyName: font.familyName ?? font.postscriptName,\n weight: font['OS/2']?.usWeightClass,\n }\n}\n","// raster-v1 (ALGORITHM.md §13): deterministic fixed-point (26.6) scanline\n// rasterizer. No system rasterizer may replace this — profile bytes must be\n// identical across platforms.\n\nimport { fdiv, idiv, rdiv } from '@ascii-fx/core'\nimport type { FontPathCommand } from 'fontkit'\n\nexport const SUPERSAMPLE = 4\nexport const QUAD_SEGMENTS = 16\nexport const CUBIC_SEGMENTS = 24\n\n/** Font-unit → 26.6 pixel-space mappers (y-down). */\nexport interface FxMapping {\n x(v: number): number\n y(v: number): number\n}\n\n/** Flatten outline commands to non-horizontal line segments [x0,y0,x1,y1, ...] in 26.6. */\nexport function flattenCommands(commands: readonly FontPathCommand[], map: FxMapping): number[] {\n const edges: number[] = []\n let curX = 0\n let curY = 0\n let startX = 0\n let startY = 0\n let open = false\n\n const push = (x0: number, y0: number, x1: number, y1: number): void => {\n if (y0 !== y1) edges.push(x0, y0, x1, y1)\n }\n const lineTo = (x: number, y: number): void => {\n push(curX, curY, x, y)\n curX = x\n curY = y\n }\n const close = (): void => {\n if (open && (curX !== startX || curY !== startY)) push(curX, curY, startX, startY)\n open = false\n }\n\n for (const cmd of commands) {\n const a = cmd.args\n switch (cmd.command) {\n case 'moveTo':\n close()\n curX = startX = map.x(a[0])\n curY = startY = map.y(a[1])\n open = true\n break\n case 'lineTo':\n lineTo(map.x(a[0]), map.y(a[1]))\n break\n case 'quadraticCurveTo': {\n const n = QUAD_SEGMENTS\n const x0 = curX\n const y0 = curY\n const cx = map.x(a[0])\n const cy = map.y(a[1])\n const x2 = map.x(a[2])\n const y2 = map.y(a[3])\n for (let i = 1; i <= n; i++) {\n const w0 = (n - i) * (n - i)\n const w1 = 2 * i * (n - i)\n const w2 = i * i\n lineTo(rdiv(w0 * x0 + w1 * cx + w2 * x2, n * n), rdiv(w0 * y0 + w1 * cy + w2 * y2, n * n))\n }\n break\n }\n case 'bezierCurveTo': {\n const n = CUBIC_SEGMENTS\n const x0 = curX\n const y0 = curY\n const c1x = map.x(a[0])\n const c1y = map.y(a[1])\n const c2x = map.x(a[2])\n const c2y = map.y(a[3])\n const x3 = map.x(a[4])\n const y3 = map.y(a[5])\n for (let i = 1; i <= n; i++) {\n const u = n - i\n const w0 = u * u * u\n const w1 = 3 * i * u * u\n const w2 = 3 * i * i * u\n const w3 = i * i * i\n lineTo(\n rdiv(w0 * x0 + w1 * c1x + w2 * c2x + w3 * x3, n * n * n),\n rdiv(w0 * y0 + w1 * c1y + w2 * c2y + w3 * y3, n * n * n),\n )\n }\n break\n }\n case 'closePath':\n close()\n break\n }\n }\n close()\n return edges\n}\n\nexport interface GlyphRaster {\n /** Per-pixel subsample hit counts, cellW·cellH, each 0..SUPERSAMPLE². */\n hits: Uint8Array\n /** Subsample hits per 8×8 mask cell. */\n maskHits: Int32Array\n totalHits: number\n}\n\n/** Subsample totals per 8×8 mask cell — identical for every glyph of a given cell size. */\nexport function maskTotals(cellW: number, cellH: number): Int32Array {\n const S = SUPERSAMPLE\n const subW = cellW * S\n const subH = cellH * S\n const totals = new Int32Array(64)\n for (let sy = 0; sy < subH; sy++) {\n const rowBase = idiv(sy * 8, subH) * 8\n for (let sx = 0; sx < subW; sx++) totals[rowBase + idiv(sx * 8, subW)]++\n }\n return totals\n}\n\n/** Scanline fill (non-zero winding) over subsample centers. */\nexport function rasterizeGlyph(\n edges: readonly number[],\n cellW: number,\n cellH: number,\n): GlyphRaster {\n const S = SUPERSAMPLE\n const step = idiv(64, S) // 26.6 units between subsample centers\n const half = idiv(step, 2)\n const subW = cellW * S\n const subH = cellH * S\n const hits = new Uint8Array(cellW * cellH)\n const maskHits = new Int32Array(64)\n let totalHits = 0\n if (edges.length === 0) return { hits, maskHits, totalHits }\n\n for (let sy = 0; sy < subH; sy++) {\n const y = sy * step + half\n const crossings: Array<[number, number]> = []\n for (let e = 0; e < edges.length; e += 4) {\n const y0 = edges[e + 1]\n const y1 = edges[e + 3]\n const lo = Math.min(y0, y1)\n const hi = Math.max(y0, y1)\n if (y < lo || y >= hi) continue\n const x0 = edges[e]\n const x1 = edges[e + 2]\n crossings.push([x0 + fdiv((x1 - x0) * (y - y0), y1 - y0), y1 > y0 ? 1 : -1])\n }\n if (crossings.length === 0) continue\n crossings.sort((a, b) => a[0] - b[0])\n const mRowBase = idiv(sy * 8, subH) * 8\n const pRow = idiv(sy, S) * cellW\n let ci = 0\n let winding = 0\n for (let sx = 0; sx < subW; sx++) {\n const X = sx * step + half\n while (ci < crossings.length && crossings[ci][0] <= X) {\n winding += crossings[ci][1]\n ci++\n }\n if (winding !== 0) {\n hits[pRow + idiv(sx, S)]++\n maskHits[mRowBase + idiv(sx * 8, subW)]++\n totalHits++\n }\n }\n }\n return { hits, maskHits, totalHits }\n}\n\n/** Mask bit = 1 ⇔ 2·hits ≥ total (tie → ink). Returns 64-bit mask as lo/hi u32. */\nexport function deriveMask(maskHits: Int32Array, totals: Int32Array): { lo: number; hi: number } {\n let lo = 0\n let hi = 0\n for (let m = 0; m < 64; m++) {\n if (2 * maskHits[m] >= totals[m]) {\n if (m < 32) lo |= 1 << m\n else hi |= 1 << (m - 32)\n }\n }\n return { lo: lo >>> 0, hi: hi >>> 0 }\n}\n","import { createHash } from 'node:crypto'\nimport { readFileSync } from 'node:fs'\nimport type { AsciiProfile, Shape6GlyphData } from '@ascii-fx/core'\nimport {\n encodeProfile,\n glyphOffset,\n idiv,\n joiningSide,\n kashidaText,\n shapingText,\n nextPow2,\n rdiv,\n resolveCharset,\n shape6BucketCenter,\n} from '@ascii-fx/core'\nimport type { Font, FontPathCommand } from 'fontkit'\nimport { loadFont } from './font.js'\nimport {\n CUBIC_SEGMENTS,\n QUAD_SEGMENTS,\n SUPERSAMPLE,\n deriveMask,\n flattenCommands,\n maskTotals,\n rasterizeGlyph,\n} from './raster.js'\n\nexport const COMPILER_VERSION = '0.1.0'\n\n/**\n * The @ascii-fx/compiler version actually installed, read from its own manifest so it cannot\n * drift the way a constant can. Every @ascii-fx/* package releases in one fixed group with\n * exact internal pins, so this moves on any release that could change output bytes — which is\n * what makes it a sound build-cache salt (@ascii-fx/vite keys on it). Deliberately separate\n * from COMPILER_VERSION: that string is embedded in profile metadata, where following the\n * package version would change profile bytes and break the golden fixtures on every release.\n */\nexport const COMPILER_PACKAGE_VERSION: string = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8'),\n).version\nexport const REF_GLYPH_HEIGHT = 64\nexport const ATLAS_PADDING = 4\n\nexport interface BuildProfileOptions {\n /** Raw font bytes (ttf/otf/woff/woff2, or a ttc/otc collection with `face`). */\n font: Uint8Array\n /** Which face of a font collection: its PostScript name, or its index. Required for a collection. */\n face?: string | number\n id?: string\n /** Built-in charset name; default 'ascii'. */\n charset?: string\n /** Custom characters (overrides charset). */\n characters?: string | readonly string[]\n /**\n * Compile shape6-v1 data (ALGORITHM.md §18): 6D glyph vectors, and with\n * `{ lut: true }` the 512KiB dense winner LUT. Opt-in — it grows the profile\n * and only an explicit `matchFrameShape6` uses it (spec §5–6).\n */\n shape6?: boolean | { lut?: boolean }\n}\n\nexport interface BuiltProfile {\n profile: AsciiProfile\n binary: Uint8Array\n}\n\nexport const sha256 = (data: Uint8Array | string): string =>\n createHash('sha256').update(data).digest('hex')\n\n/** Glyph-side shape6 vector (ALGORITHM.md §18): float64 means over mask-cell lumas. */\nfunction glyphShape6(lumas: Float64Array, out: Float32Array, at: number): void {\n let sum = 0\n let top = 0\n let left = 0\n let tl = 0\n let tr = 0\n let bl = 0\n let br = 0\n let center = 0\n for (let m = 0; m < 64; m++) {\n const row = m >> 3\n const col = m & 7\n const v = lumas[m]\n sum += v\n if (row < 4) top += v\n if (col < 4) left += v\n if (row < 4) {\n if (col < 4) tl += v\n else tr += v\n } else if (col < 4) bl += v\n else br += v\n if (row >= 2 && row < 6 && col >= 2 && col < 6) center += v\n }\n const v0 = sum / 64\n out[at] = v0\n out[at + 1] = top / 32 - (sum - top) / 32\n out[at + 2] = left / 32 - (sum - left) / 32\n out[at + 3] = (tl + br - tr - bl) / 32\n out[at + 4] = center / 16 - (sum - center) / 48\n let dev = 0\n for (let m = 0; m < 64; m++) dev += Math.abs(lumas[m] - v0)\n out[at + 5] = dev / 64\n}\n\n/** One glyph's outline in font units, and how far it advances. */\ninterface GlyphOutline {\n commands: FontPathCommand[]\n advance: number\n}\n\n// ZERO WIDTH JOINER, variation selectors and the like: they steer shaping and draw nothing, so a\n// font without a glyph for one has not failed to cover it.\nconst IGNORABLE = /^\\p{Default_Ignorable_Code_Point}+$/u\n\n/**\n * A glyph string's outline (ALGORITHM.md §13). One code point the font maps is its glyph, exactly\n * as raster-v1 has always drawn it. Anything else is shaped with the font's own OpenType rules:\n * a grapheme of several code points (a conjunct, a base and its marks), or an Arabic presentation\n * form the font leaves unmapped, which shapes from its base letter in joining context. Null when\n * the font cannot draw it.\n */\nfunction glyphOutline(font: Font, text: string): GlyphOutline | null {\n const cps = Array.from(text)\n if (cps.length === 1) {\n const cp = text.codePointAt(0)!\n if (font.hasGlyphForCodePoint(cp)) {\n const g = font.glyphForCodePoint(cp)\n return { commands: g.path.commands, advance: g.advanceWidth }\n }\n const context = shapingText(text)\n return context === text ? null : shapeOutline(font, context)\n }\n return shapeOutline(font, text)\n}\n\nconst openTypeFirst = new WeakMap<Font, Font>()\n\n/**\n * The font as fontkit should shape it. fontkit takes Apple's `morx` tables over OpenType's\n * GSUB/GPOS whenever a font has both, and its morx engine can loop without end — Thai sara am\n * (U+0E33) in Ayuthaya never returns. A font that carries OpenType tables is shaped with them\n * (the standard path, and the one browsers take); `morx` is used only by a font with nothing\n * else. The view shadows `morx` and leaves the font itself untouched.\n */\nfunction shapingFont(font: Font): Font {\n const tables = font as Font & { morx?: unknown; GSUB?: unknown; GPOS?: unknown }\n if (!tables.morx || !(tables.GSUB || tables.GPOS)) return font\n let view = openTypeFirst.get(font)\n if (!view) {\n view = Object.create(font, { morx: { value: undefined } }) as Font\n openTypeFirst.set(font, view)\n }\n return view\n}\n\n/** Shape `text` and merge the run into one outline, each glyph moved to its shaped position. */\nfunction shapeOutline(font: Font, text: string): GlyphOutline | null {\n const run = shapingFont(font).layout(text)\n const commands: FontPathCommand[] = []\n let x = 0\n let drawn = 0\n for (let i = 0; i < run.glyphs.length; i++) {\n const g = run.glyphs[i]\n const p = run.positions[i]\n if (g.id === 0) {\n // .notdef: a gap in the font, unless it stands for something that draws nothing anyway.\n if (!IGNORABLE.test(String.fromCodePoint(...g.codePoints))) return null\n continue\n }\n const dx = x + p.xOffset\n const dy = p.yOffset\n for (const c of g.path.commands) {\n commands.push({\n command: c.command,\n args: c.args.map((v, j) => (j % 2 === 0 ? v + dx : v + dy)),\n })\n }\n x += p.xAdvance\n drawn++\n }\n return drawn === 0 ? null : { commands, advance: x }\n}\n\n/** Build a deterministic .asciip profile (ALGORITHM.md §13–14). */\nexport function buildProfile(options: BuildProfileOptions): BuiltProfile {\n const { name: charsetName, glyphs } = resolveCharset(options.charset, options.characters)\n const lf = loadFont(options.font, options.face)\n\n const outlines = glyphs.map((g) => glyphOutline(lf.font, g))\n const missing = glyphs.filter((_, i) => outlines[i] === null)\n if (missing.length > 0) {\n throw new Error(\n `Font \"${lf.familyName ?? 'unknown'}\" has no glyph for: ${missing\n .map(\n (c) =>\n `${JSON.stringify(c)} (${Array.from(c, (ch) => `U+${ch.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')}`).join(' ')})`,\n )\n .join(', ')}. Remove them from the charset or pick a font that covers them.`,\n )\n }\n const shapes = outlines as GlyphOutline[]\n\n // The cell is as wide as the widest glyph, and narrower ones are centred in it, or flush with\n // the edge they join at (§13, joining.ts in core). A\n // monospace set has every shift at 0 and compiles exactly as it always has; this is what lets\n // a proportional script (Arabic, in any font) or a mix of half- and full-width glyphs compile.\n let advance = 0\n for (const g of shapes) if (g.advance > advance) advance = g.advance\n\n // Joining forms are drawn with kashida on their joining side(s), enough to cross the cell, so\n // their strokes meet the next cell's at the edge (ALGORITHM.md §13). Only where the font has a\n // tatweel to draw it with; without one a joining form is just pushed to its edge.\n const tatweel = lf.font.hasGlyphForCodePoint(0x640)\n ? lf.font.glyphForCodePoint(0x640).advanceWidth\n : 0\n const kashida = tatweel > 0 ? idiv(advance + tatweel - 1, tatweel) + 1 : 0\n const drawn = glyphs.map((g, i) => {\n if (kashida === 0 || joiningSide(g) === null) return shapes[i]\n const mapped = Array.from(g).length > 1 || lf.font.hasGlyphForCodePoint(g.codePointAt(0)!)\n return shapeOutline(lf.font, kashidaText(mapped ? g : shapingText(g), kashida)) ?? shapes[i]\n })\n const shifts = shapes.map((g, i) => glyphOffset(glyphs[i], g.advance, advance, drawn[i].advance))\n\n const unitsCell = lf.ascent - lf.descent\n if (!(unitsCell > 0))\n throw new Error('Font reports non-positive ascent−descent; cannot derive a cell box.')\n const cellH = REF_GLYPH_HEIGHT\n const cellW = Math.max(1, rdiv(advance * REF_GLYPH_HEIGHT, unitsCell))\n const baseline = rdiv(lf.ascent * REF_GLYPH_HEIGHT, unitsCell)\n const baselineFx = rdiv(lf.ascent * REF_GLYPH_HEIGHT * 64, unitsCell)\n const mapFor = (shift: number) => ({\n x: (v: number) => rdiv((v + shift) * REF_GLYPH_HEIGHT * 64, unitsCell),\n y: (v: number) => baselineFx - rdiv(v * REF_GLYPH_HEIGHT * 64, unitsCell),\n })\n\n const n = glyphs.length\n const masksLo = new Uint32Array(n)\n const masksHi = new Uint32Array(n)\n const coverage = new Uint16Array(n)\n\n const pitchW = nextPow2(cellW + 2 * ATLAS_PADDING)\n const pitchH = nextPow2(cellH + 2 * ATLAS_PADDING)\n let atlasColumns = 1\n while (atlasColumns * atlasColumns < n) atlasColumns++\n const atlasRows = idiv(n + atlasColumns - 1, atlasColumns)\n const atlasW = atlasColumns * pitchW\n const atlasH = atlasRows * pitchH\n const atlasData = new Uint8Array(atlasW * atlasH)\n\n const totals = maskTotals(cellW, cellH)\n const subsamplesPerCell = cellW * cellH * SUPERSAMPLE * SUPERSAMPLE\n const wantShape6 = options.shape6 !== undefined && options.shape6 !== false\n const cellLumas = wantShape6 ? new Float64Array(n * 64) : undefined\n\n for (let i = 0; i < n; i++) {\n const edges = flattenCommands(drawn[i].commands, mapFor(shifts[i]))\n const raster = rasterizeGlyph(edges, cellW, cellH)\n const mask = deriveMask(raster.maskHits, totals)\n masksLo[i] = mask.lo\n masksHi[i] = mask.hi\n coverage[i] = rdiv(raster.totalHits * 65535, subsamplesPerCell)\n if (cellLumas) {\n for (let m = 0; m < 64; m++) cellLumas[i * 64 + m] = (raster.maskHits[m] / totals[m]) * 255\n }\n const tileX = (i % atlasColumns) * pitchW + ATLAS_PADDING\n const tileY = idiv(i, atlasColumns) * pitchH + ATLAS_PADDING\n for (let py = 0; py < cellH; py++) {\n const dst = (tileY + py) * atlasW + tileX\n const src = py * cellW\n for (let px = 0; px < cellW; px++) {\n atlasData[dst + px] = rdiv(raster.hits[src + px] * 255, SUPERSAMPLE * SUPERSAMPLE)\n }\n }\n }\n\n let shape6: Shape6GlyphData | undefined\n if (cellLumas) {\n const vectors6 = new Float32Array(n * 6)\n for (let i = 0; i < n; i++)\n glyphShape6(cellLumas.subarray(i * 64, i * 64 + 64), vectors6, i * 6)\n let lut3: Uint16Array | undefined\n if (typeof options.shape6 === 'object' && options.shape6.lut) {\n lut3 = new Uint16Array(8 ** 6)\n const center = new Float64Array(6)\n for (let idx = 0; idx < lut3.length; idx++) {\n shape6BucketCenter(idx, center)\n let best = 0\n let bestD = Infinity\n for (let g = 0; g < n; g++) {\n let d = 0\n for (let c = 0; c < 6; c++) {\n const e = center[c] - vectors6[g * 6 + c]\n d += e * e\n }\n if (d < bestD) {\n bestD = d\n best = g\n }\n }\n lut3[idx] = best\n }\n }\n shape6 = { vectors6, lut3 }\n }\n\n // A collection's bytes hold every face, so they identify the font only together with the face.\n // Single fonts hash exactly as before, which keeps existing fingerprints stable.\n const fontHash = lf.collectionFace\n ? sha256(`${sha256(options.font)}|face:${lf.collectionFace}`)\n : sha256(options.font)\n const charsetHash = sha256(glyphs.join('\\u0000'))\n const fingerprint = sha256(\n `asciip/1|structural-v1|raster-v1|font:${fontHash}|charset:${charsetHash}` +\n `|H:${REF_GLYPH_HEIGHT}|S:${SUPERSAMPLE}|pad:${ATLAS_PADDING}|quad:${QUAD_SEGMENTS}|cubic:${CUBIC_SEGMENTS}`,\n )\n\n const profile: AsciiProfile = {\n version: 1,\n id: options.id ?? 'default',\n fingerprint,\n charsetHash,\n fontHash,\n glyphs,\n glyphCount: n,\n metrics: {\n unitsPerEm: lf.unitsPerEm,\n ascent: lf.ascent,\n descent: lf.descent,\n lineGap: lf.lineGap,\n advanceUnits: advance,\n cellWidth: cellW,\n cellHeight: cellH,\n baseline,\n },\n atlas: {\n width: atlasW,\n height: atlasH,\n pitchWidth: pitchW,\n pitchHeight: pitchH,\n cellWidth: cellW,\n cellHeight: cellH,\n padding: ATLAS_PADDING,\n columns: atlasColumns,\n data: atlasData,\n },\n structural: { masksLo, masksHi, coverage },\n shape6,\n metadata: {\n id: options.id ?? 'default',\n charset: charsetName,\n fontFamily: lf.familyName,\n fontWeight: lf.weight,\n compilerVersion: COMPILER_VERSION,\n },\n }\n\n return { profile, binary: encodeProfile(profile) }\n}\n","import type { AsciiFrame, AsciiProfile, MatchOptions, RawImage } from '@ascii-fx/core'\nimport { encodeFrame, matchFrame } from '@ascii-fx/core'\n\nexport interface BuildFrameOptions extends Omit<MatchOptions, 'profile'> {\n image: RawImage\n profile: AsciiProfile\n}\n\nexport interface BuiltFrame {\n frame: AsciiFrame\n binary: Uint8Array\n}\n\n/** Build-time static frame: run the exact matcher now so the client never has to. */\nexport function buildFrame(options: BuildFrameOptions): BuiltFrame {\n const { image, ...match } = options\n const frame = matchFrame(image, match)\n return { frame, binary: encodeFrame(frame) }\n}\n","import { Buffer } from 'node:buffer'\nimport { PNG } from 'pngjs'\nimport type { RawImage } from '@ascii-fx/core'\n\nexport function decodePng(bytes: Uint8Array): RawImage {\n const png = PNG.sync.read(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n return {\n width: png.width,\n height: png.height,\n data: new Uint8Array(png.data.buffer, png.data.byteOffset, png.data.length),\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,YAAY,QAAQ;AAoBb,SAAS,SAAS,OAAmB,MAAoC;AAC9E,QAAMA,UACkC,aACa,YAAS;AA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ACf,iBAAiB;AAAA,IACnB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,QAAQ,cAAc,OAAO,EAAE;AACnD;;;ACpWA,SAAS,aAAa,kBAAkB;AAajC,SAAS,WAAW,SAAwC;AACjE,QAAM,EAAE,OAAO,GAAG,MAAM,IAAI;AAC5B,QAAM,QAAQ,WAAW,OAAO,KAAK;AACrC,SAAO,EAAE,OAAO,QAAQ,YAAY,KAAK,EAAE;AAC7C;;;AClBA,SAAS,UAAAC,eAAc;AACvB,SAAS,WAAW;AAGb,SAAS,UAAU,OAA6B;AACrD,QAAM,MAAM,IAAI,KAAK,KAAKA,QAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC;AACvF,SAAO;AAAA,IACL,OAAO,IAAI;AAAA,IACX,QAAQ,IAAI;AAAA,IACZ,MAAM,IAAI,WAAW,IAAI,KAAK,QAAQ,IAAI,KAAK,YAAY,IAAI,KAAK,MAAM;AAAA,EAC5E;AACF;","names":["create","idiv","rdiv","idiv","rdiv","Buffer"]}
|
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
buildFrame,
|
|
4
4
|
buildProfile,
|
|
5
5
|
decodePng
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-HN45E6LL.js";
|
|
7
7
|
|
|
8
8
|
// src/cli.ts
|
|
9
9
|
import { readFile, writeFile } from "fs/promises";
|
|
@@ -56,7 +56,7 @@ var USAGE = `ascii-fx \u2014 ASCII FX build-time compiler
|
|
|
56
56
|
|
|
57
57
|
Usage:
|
|
58
58
|
ascii-fx profile build --font <file> --out <file.asciip> [--charset ascii] [--characters "<chars>"] [--id default]
|
|
59
|
-
[--shape6] [--shape6-lut]
|
|
59
|
+
[--face <postscript-name|index>] [--shape6] [--shape6-lut]
|
|
60
60
|
ascii-fx frame build --image <file.png> --profile <file.asciip> --out <file.asciif>
|
|
61
61
|
[--columns N] [--rows N] [--color mono|foreground|full] [--alpha mask|ignore]
|
|
62
62
|
ascii-fx inspect <file.asciip | file.asciif>
|
|
@@ -79,8 +79,10 @@ async function main() {
|
|
|
79
79
|
const outPath = requireStr(args, "out");
|
|
80
80
|
const font = new Uint8Array(await readFile(fontPath));
|
|
81
81
|
const characters = str(args, "characters");
|
|
82
|
+
const face = str(args, "face");
|
|
82
83
|
const { profile, binary } = buildProfile({
|
|
83
84
|
font,
|
|
85
|
+
face: face !== void 0 && /^\d+$/.test(face) ? Number(face) : face,
|
|
84
86
|
id: str(args, "id") ?? "default",
|
|
85
87
|
charset: str(args, "charset"),
|
|
86
88
|
characters,
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/cliArgs.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFile, writeFile } from 'node:fs/promises'\nimport process from 'node:process'\nimport { decodeProfile, peekFrame } from '@ascii-fx/core'\nimport { type Args, enumFlag, parseArgs, positiveIntFlag, str } from './cliArgs.js'\nimport { buildProfile } from './profile.js'\nimport { buildFrame } from './frameBuild.js'\nimport { decodePng } from './png.js'\n\nconst USAGE = `ascii-fx — ASCII FX build-time compiler\n\nUsage:\n ascii-fx profile build --font <file> --out <file.asciip> [--charset ascii] [--characters \"<chars>\"] [--id default]\n [--shape6] [--shape6-lut]\n ascii-fx frame build --image <file.png> --profile <file.asciip> --out <file.asciif>\n [--columns N] [--rows N] [--color mono|foreground|full] [--alpha mask|ignore]\n ascii-fx inspect <file.asciip | file.asciif>\n`\n\nconst requireStr = (args: Args, key: string): string => {\n const v = str(args, key)\n if (v === undefined) {\n console.error(`Missing required --${key}\\n\\n${USAGE}`)\n process.exit(1)\n }\n return v\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2))\n const [cmd, sub] = args.positional\n\n if (cmd === 'profile' && sub === 'build') {\n const fontPath = requireStr(args, 'font')\n const outPath = requireStr(args, 'out')\n const font = new Uint8Array(await readFile(fontPath))\n const characters = str(args, 'characters')\n const { profile, binary } = buildProfile({\n font,\n id: str(args, 'id') ?? 'default',\n charset: str(args, 'charset'),\n characters,\n shape6:\n args.flags.get('shape6-lut') === true ? { lut: true } : args.flags.get('shape6') === true,\n })\n await writeFile(outPath, binary)\n console.log(\n `${outPath}: ${profile.glyphCount} glyphs (${profile.metadata.charset}), ` +\n `cell ${profile.atlas.cellWidth}×${profile.atlas.cellHeight}, atlas ${profile.atlas.width}×${profile.atlas.height}, ` +\n `${binary.length} bytes, fingerprint ${profile.fingerprint.slice(0, 12)}…`,\n )\n return\n }\n\n if (cmd === 'frame' && sub === 'build') {\n const imagePath = requireStr(args, 'image')\n const profilePath = requireStr(args, 'profile')\n const outPath = requireStr(args, 'out')\n if (!imagePath.toLowerCase().endsWith('.png')) {\n console.error('frame build currently decodes PNG only.')\n process.exit(1)\n }\n const profile = decodeProfile(new Uint8Array(await readFile(profilePath)))\n const image = decodePng(new Uint8Array(await readFile(imagePath)))\n const { frame, binary } = buildFrame({\n image,\n profile,\n columns: positiveIntFlag('columns', str(args, 'columns')),\n rows: positiveIntFlag('rows', str(args, 'rows')),\n color:\n enumFlag('color', str(args, 'color'), ['mono', 'foreground', 'full'] as const) ?? 'mono',\n alpha: enumFlag('alpha', str(args, 'alpha'), ['mask', 'ignore'] as const),\n })\n await writeFile(outPath, binary)\n console.log(\n `${outPath}: ${frame.columns}×${frame.rows} cells, ${frame.colorMode}, ${binary.length} bytes`,\n )\n return\n }\n\n if (cmd === 'inspect') {\n const file = args.positional[1]\n if (!file) {\n console.error(USAGE)\n process.exit(1)\n }\n const bytes = new Uint8Array(await readFile(file))\n if (bytes[3] === 0x49) {\n const p = decodeProfile(bytes)\n console.log(\n JSON.stringify(\n {\n format: 'asciip/1',\n id: p.id,\n charset: p.metadata.charset,\n fontFamily: p.metadata.fontFamily,\n glyphCount: p.glyphCount,\n cell: `${p.atlas.cellWidth}×${p.atlas.cellHeight}`,\n baseline: p.metrics.baseline,\n atlas: `${p.atlas.width}×${p.atlas.height} (pitch ${p.atlas.pitchWidth}×${p.atlas.pitchHeight})`,\n fingerprint: p.fingerprint,\n fontHash: p.fontHash,\n charsetHash: p.charsetHash,\n compilerVersion: p.metadata.compilerVersion,\n bytes: bytes.length,\n },\n null,\n 2,\n ),\n )\n } else {\n const m = peekFrame(bytes)\n console.log(JSON.stringify({ format: 'asciif/1', ...m, bytes: bytes.length }, null, 2))\n }\n return\n }\n\n console.error(USAGE)\n process.exit(cmd === undefined ? 0 : 1)\n}\n\nmain().catch((err: unknown) => {\n console.error(err instanceof Error ? err.message : err)\n process.exit(1)\n})\n","/**\n * CLI argument parsing and validation, separate from cli.ts so it is testable\n * without spawning the built binary (the node suite runs before `pnpm build`\n * in CI, so dist/cli.js may not exist when tests do).\n *\n * Validators throw plain Errors; cli.ts's top-level catch prints the message\n * and exits 1. They exist because the underlying builders do not reject what\n * they cannot handle: an unknown --color used to encode a silently wrong\n * artifact and a non-numeric --columns an unloadable one, both with exit 0.\n */\n\nexport interface Args {\n positional: string[]\n flags: Map<string, string | true>\n}\n\nexport function parseArgs(argv: string[]): Args {\n const positional: string[] = []\n const flags = new Map<string, string | true>()\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]\n if (a.startsWith('--')) {\n const key = a.slice(2)\n const next = argv[i + 1]\n if (next !== undefined && !next.startsWith('--')) {\n flags.set(key, next)\n i++\n } else {\n flags.set(key, true)\n }\n } else {\n positional.push(a)\n }\n }\n return { positional, flags }\n}\n\nexport const str = (args: Args, key: string): string | undefined => {\n const v = args.flags.get(key)\n return typeof v === 'string' ? v : undefined\n}\n\n/** An enum-valued flag: anything outside `allowed` is an error, never a guess. */\nexport function enumFlag<T extends string>(\n key: string,\n value: string | undefined,\n allowed: readonly T[],\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as readonly string[]).includes(value)) return value as T\n throw new Error(\n `Invalid --${key} ${JSON.stringify(value)}: expected one of ${allowed.join(' | ')}.`,\n )\n}\n\n/** A grid-dimension flag: positive integers only — NaN and fractions reach typed-array sizes otherwise. */\nexport function positiveIntFlag(key: string, value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(`Invalid --${key} ${JSON.stringify(value)}: expected a positive integer.`)\n }\n return n\n}\n"],"mappings":";;;;;;;;AACA,SAAS,UAAU,iBAAiB;AACpC,OAAO,aAAa;AACpB,SAAS,eAAe,iBAAiB;;;ACalC,SAAS,UAAU,MAAsB;AAC9C,QAAM,aAAuB,CAAC;AAC9B,QAAM,QAAQ,oBAAI,IAA2B;AAC7C,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,IAAI,KAAK,CAAC;AAChB,QAAI,EAAE,WAAW,IAAI,GAAG;AACtB,YAAM,MAAM,EAAE,MAAM,CAAC;AACrB,YAAM,OAAO,KAAK,IAAI,CAAC;AACvB,UAAI,SAAS,UAAa,CAAC,KAAK,WAAW,IAAI,GAAG;AAChD,cAAM,IAAI,KAAK,IAAI;AACnB;AAAA,MACF,OAAO;AACL,cAAM,IAAI,KAAK,IAAI;AAAA,MACrB;AAAA,IACF,OAAO;AACL,iBAAW,KAAK,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO,EAAE,YAAY,MAAM;AAC7B;AAEO,IAAM,MAAM,CAAC,MAAY,QAAoC;AAClE,QAAM,IAAI,KAAK,MAAM,IAAI,GAAG;AAC5B,SAAO,OAAO,MAAM,WAAW,IAAI;AACrC;AAGO,SAAS,SACd,KACA,OACA,SACe;AACf,MAAI,UAAU,OAAW,QAAO;AAChC,MAAK,QAA8B,SAAS,KAAK,EAAG,QAAO;AAC3D,QAAM,IAAI;AAAA,IACR,aAAa,GAAG,IAAI,KAAK,UAAU,KAAK,CAAC,qBAAqB,QAAQ,KAAK,KAAK,CAAC;AAAA,EACnF;AACF;AAGO,SAAS,gBAAgB,KAAa,OAA+C;AAC1F,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,IAAI,O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,MAAM,SAAS,IAAI,CAAC;AACjD,QAAI,MAAM,CAAC,MAAM,IAAM;AACrB,YAAM,IAAI,cAAc,KAAK;AAC7B,cAAQ;AAAA,QACN,KAAK;AAAA,UACH;AAAA,YACE,QAAQ;AAAA,YACR,IAAI,EAAE;AAAA,YACN,SAAS,EAAE,SAAS;AAAA,YACpB,YAAY,EAAE,SAAS;AAAA,YACvB,YAAY,EAAE;AAAA,YACd,MAAM,GAAG,EAAE,MAAM,SAAS,OAAI,EAAE,MAAM,UAAU;AAAA,YAChD,UAAU,EAAE,QAAQ;AAAA,YACpB,OAAO,GAAG,EAAE,MAAM,KAAK,OAAI,EAAE,MAAM,MAAM,WAAW,EAAE,MAAM,UAAU,OAAI,EAAE,MAAM,WAAW;AAAA,YAC7F,aAAa,EAAE;AAAA,YACf,UAAU,EAAE;AAAA,YACZ,aAAa,EAAE;AAAA,YACf,iBAAiB,EAAE,SAAS;AAAA,YAC5B,OAAO,MAAM;AAAA,UACf;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AACL,YAAM,IAAI,UAAU,KAAK;AACzB,cAAQ,IAAI,KAAK,UAAU,EAAE,QAAQ,YAAY,GAAG,GAAG,OAAO,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC;AAAA,IACxF;AACA;AAAA,EACF;AAEA,UAAQ,MAAM,KAAK;AACnB,UAAQ,KAAK,QAAQ,SAAY,IAAI,CAAC;AACxC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,GAAG;AACtD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/cliArgs.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFile, writeFile } from 'node:fs/promises'\nimport process from 'node:process'\nimport { decodeProfile, peekFrame } from '@ascii-fx/core'\nimport { type Args, enumFlag, parseArgs, positiveIntFlag, str } from './cliArgs.js'\nimport { buildProfile } from './profile.js'\nimport { buildFrame } from './frameBuild.js'\nimport { decodePng } from './png.js'\n\nconst USAGE = `ascii-fx — ASCII FX build-time compiler\n\nUsage:\n ascii-fx profile build --font <file> --out <file.asciip> [--charset ascii] [--characters \"<chars>\"] [--id default]\n [--face <postscript-name|index>] [--shape6] [--shape6-lut]\n ascii-fx frame build --image <file.png> --profile <file.asciip> --out <file.asciif>\n [--columns N] [--rows N] [--color mono|foreground|full] [--alpha mask|ignore]\n ascii-fx inspect <file.asciip | file.asciif>\n`\n\nconst requireStr = (args: Args, key: string): string => {\n const v = str(args, key)\n if (v === undefined) {\n console.error(`Missing required --${key}\\n\\n${USAGE}`)\n process.exit(1)\n }\n return v\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2))\n const [cmd, sub] = args.positional\n\n if (cmd === 'profile' && sub === 'build') {\n const fontPath = requireStr(args, 'font')\n const outPath = requireStr(args, 'out')\n const font = new Uint8Array(await readFile(fontPath))\n const characters = str(args, 'characters')\n const face = str(args, 'face')\n const { profile, binary } = buildProfile({\n font,\n face: face !== undefined && /^\\d+$/.test(face) ? Number(face) : face,\n id: str(args, 'id') ?? 'default',\n charset: str(args, 'charset'),\n characters,\n shape6:\n args.flags.get('shape6-lut') === true ? { lut: true } : args.flags.get('shape6') === true,\n })\n await writeFile(outPath, binary)\n console.log(\n `${outPath}: ${profile.glyphCount} glyphs (${profile.metadata.charset}), ` +\n `cell ${profile.atlas.cellWidth}×${profile.atlas.cellHeight}, atlas ${profile.atlas.width}×${profile.atlas.height}, ` +\n `${binary.length} bytes, fingerprint ${profile.fingerprint.slice(0, 12)}…`,\n )\n return\n }\n\n if (cmd === 'frame' && sub === 'build') {\n const imagePath = requireStr(args, 'image')\n const profilePath = requireStr(args, 'profile')\n const outPath = requireStr(args, 'out')\n if (!imagePath.toLowerCase().endsWith('.png')) {\n console.error('frame build currently decodes PNG only.')\n process.exit(1)\n }\n const profile = decodeProfile(new Uint8Array(await readFile(profilePath)))\n const image = decodePng(new Uint8Array(await readFile(imagePath)))\n const { frame, binary } = buildFrame({\n image,\n profile,\n columns: positiveIntFlag('columns', str(args, 'columns')),\n rows: positiveIntFlag('rows', str(args, 'rows')),\n color:\n enumFlag('color', str(args, 'color'), ['mono', 'foreground', 'full'] as const) ?? 'mono',\n alpha: enumFlag('alpha', str(args, 'alpha'), ['mask', 'ignore'] as const),\n })\n await writeFile(outPath, binary)\n console.log(\n `${outPath}: ${frame.columns}×${frame.rows} cells, ${frame.colorMode}, ${binary.length} bytes`,\n )\n return\n }\n\n if (cmd === 'inspect') {\n const file = args.positional[1]\n if (!file) {\n console.error(USAGE)\n process.exit(1)\n }\n const bytes = new Uint8Array(await readFile(file))\n if (bytes[3] === 0x49) {\n const p = decodeProfile(bytes)\n console.log(\n JSON.stringify(\n {\n format: 'asciip/1',\n id: p.id,\n charset: p.metadata.charset,\n fontFamily: p.metadata.fontFamily,\n glyphCount: p.glyphCount,\n cell: `${p.atlas.cellWidth}×${p.atlas.cellHeight}`,\n baseline: p.metrics.baseline,\n atlas: `${p.atlas.width}×${p.atlas.height} (pitch ${p.atlas.pitchWidth}×${p.atlas.pitchHeight})`,\n fingerprint: p.fingerprint,\n fontHash: p.fontHash,\n charsetHash: p.charsetHash,\n compilerVersion: p.metadata.compilerVersion,\n bytes: bytes.length,\n },\n null,\n 2,\n ),\n )\n } else {\n const m = peekFrame(bytes)\n console.log(JSON.stringify({ format: 'asciif/1', ...m, bytes: bytes.length }, null, 2))\n }\n return\n }\n\n console.error(USAGE)\n process.exit(cmd === undefined ? 0 : 1)\n}\n\nmain().catch((err: unknown) => {\n console.error(err instanceof Error ? err.message : err)\n process.exit(1)\n})\n","/**\n * CLI argument parsing and validation, separate from cli.ts so it is testable\n * without spawning the built binary (the node suite runs before `pnpm build`\n * in CI, so dist/cli.js may not exist when tests do).\n *\n * Validators throw plain Errors; cli.ts's top-level catch prints the message\n * and exits 1. They exist because the underlying builders do not reject what\n * they cannot handle: an unknown --color used to encode a silently wrong\n * artifact and a non-numeric --columns an unloadable one, both with exit 0.\n */\n\nexport interface Args {\n positional: string[]\n flags: Map<string, string | true>\n}\n\nexport function parseArgs(argv: string[]): Args {\n const positional: string[] = []\n const flags = new Map<string, string | true>()\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]\n if (a.startsWith('--')) {\n const key = a.slice(2)\n const next = argv[i + 1]\n if (next !== undefined && !next.startsWith('--')) {\n flags.set(key, next)\n i++\n } else {\n flags.set(key, true)\n }\n } else {\n positional.push(a)\n }\n }\n return { positional, flags }\n}\n\nexport const str = (args: Args, key: string): string | undefined => {\n const v = args.flags.get(key)\n return typeof v === 'string' ? v : undefined\n}\n\n/** An enum-valued flag: anything outside `allowed` is an error, never a guess. */\nexport function enumFlag<T extends string>(\n key: string,\n value: string | undefined,\n allowed: readonly T[],\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as readonly string[]).includes(value)) return value as T\n throw new Error(\n `Invalid --${key} ${JSON.stringify(value)}: expected one of ${allowed.join(' | ')}.`,\n )\n}\n\n/** A grid-dimension flag: positive integers only — NaN and fractions reach typed-array sizes otherwise. */\nexport function positiveIntFlag(key: string, value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(`Invalid --${key} ${JSON.stringify(value)}: expected a positive integer.`)\n }\n return n\n}\n"],"mappings":";;;;;;;;AACA,SAAS,UAAU,iBAAiB;AACpC,OAAO,aAAa;AACpB,SAAS,eAAe,iBAAiB;;;ACalC,SAAS,UAAU,MAAsB;AAC9C,QAAM,aAAuB,CAAC;AAC9B,QAAM,QAAQ,oBAAI,IAA2B;AAC7C,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,IAAI,KAAK,CAAC;AAChB,QAAI,EAAE,WAAW,IAAI,GAAG;AACtB,YAAM,MAAM,EAAE,MAAM,CAAC;AACrB,YAAM,OAAO,KAAK,I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E,MAAM,UAAU,OAAI,EAAE,MAAM,WAAW;AAAA,YAC7F,aAAa,EAAE;AAAA,YACf,UAAU,EAAE;AAAA,YACZ,aAAa,EAAE;AAAA,YACf,iBAAiB,EAAE,SAAS;AAAA,YAC5B,OAAO,MAAM;AAAA,UACf;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AACL,YAAM,IAAI,UAAU,KAAK;AACzB,cAAQ,IAAI,KAAK,UAAU,EAAE,QAAQ,YAAY,GAAG,GAAG,OAAO,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC;AAAA,IACxF;AACA;AAAA,EACF;AAEA,UAAQ,MAAM,KAAK;AACnB,UAAQ,KAAK,QAAQ,SAAY,IAAI,CAAC;AACxC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,GAAG;AACtD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
package/dist/config.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { AlphaMode, ColorMode } from '@ascii-fx/core';
|
|
|
2
2
|
export interface AsciiProfileConfig {
|
|
3
3
|
/** Path to the font file, relative to the config file. */
|
|
4
4
|
font: string;
|
|
5
|
+
/** Which face of a .ttc/.otc collection: PostScript name or index. */
|
|
6
|
+
face?: string | number;
|
|
5
7
|
charset?: string;
|
|
6
8
|
characters?: string | string[];
|
|
7
9
|
/** Compile shape6-v1 data (ALGORITHM.md §18); `{ lut: true }` adds the dense LUT. */
|
package/dist/font.d.ts
CHANGED
|
@@ -7,5 +7,12 @@ export interface LoadedFont {
|
|
|
7
7
|
lineGap: number;
|
|
8
8
|
familyName?: string;
|
|
9
9
|
weight?: number;
|
|
10
|
+
/** Set when the face came out of a collection: the bytes alone no longer identify the font. */
|
|
11
|
+
collectionFace?: string;
|
|
10
12
|
}
|
|
11
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Parse a font. A collection (.ttc/.otc) holds several faces, and CJK and Arabic system fonts
|
|
15
|
+
* ship that way almost without exception, so `face` picks one: a PostScript name, or an index
|
|
16
|
+
* into the collection. It is required for a collection, which has no meaningful default.
|
|
17
|
+
*/
|
|
18
|
+
export declare function loadFont(bytes: Uint8Array, face?: string | number): LoadedFont;
|
package/dist/fontkit.d.ts
CHANGED
|
@@ -7,9 +7,22 @@ declare module 'fontkit' {
|
|
|
7
7
|
commands: FontPathCommand[]
|
|
8
8
|
}
|
|
9
9
|
export interface FontGlyph {
|
|
10
|
+
id: number
|
|
11
|
+
codePoints: number[]
|
|
10
12
|
advanceWidth: number
|
|
11
13
|
path: FontPath
|
|
12
14
|
}
|
|
15
|
+
export interface GlyphPosition {
|
|
16
|
+
xAdvance: number
|
|
17
|
+
yAdvance: number
|
|
18
|
+
xOffset: number
|
|
19
|
+
yOffset: number
|
|
20
|
+
}
|
|
21
|
+
/** Shaped text, in visual order. */
|
|
22
|
+
export interface GlyphRun {
|
|
23
|
+
glyphs: FontGlyph[]
|
|
24
|
+
positions: GlyphPosition[]
|
|
25
|
+
}
|
|
13
26
|
export interface Font {
|
|
14
27
|
unitsPerEm: number
|
|
15
28
|
ascent: number
|
|
@@ -21,6 +34,7 @@ declare module 'fontkit' {
|
|
|
21
34
|
fonts?: Font[]
|
|
22
35
|
hasGlyphForCodePoint(codePoint: number): boolean
|
|
23
36
|
glyphForCodePoint(codePoint: number): FontGlyph
|
|
37
|
+
layout(text: string): GlyphRun
|
|
24
38
|
}
|
|
25
39
|
export function create(buffer: Uint8Array): Font
|
|
26
40
|
const fontkit: { create(buffer: Uint8Array): Font }
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/chromatic.ts"],"sourcesContent":["import type { AlphaMode, ColorMode } from '@ascii-fx/core'\n\nexport interface AsciiProfileConfig {\n /** Path to the font file, relative to the config file. */\n font: string\n charset?: string\n characters?: string | string[]\n /** Compile shape6-v1 data (ALGORITHM.md §18); `{ lut: true }` adds the dense LUT. */\n shape6?: boolean | { lut?: boolean }\n}\n\n/** Static build-time frame (spec §16). Matching happens at build, not runtime. */\nexport interface AsciiFrameConfig {\n /** Path to the source image (PNG in v1), relative to the config file. */\n image: string\n /** Profile name from `profiles`. Default 'default'. */\n profile?: string\n columns?: number\n rows?: number\n color?: ColorMode\n alpha?: AlphaMode\n}\n\nexport interface AsciiConfig {\n profiles: Record<string, AsciiProfileConfig>\n frames?: Record<string, AsciiFrameConfig>\n}\n\nexport function defineAsciiConfig(config: AsciiConfig): AsciiConfig {\n return config\n}\n","// Builds chromatic-v1 profiles (ALGORITHM.md §C) from decoded colour images\n// rather than from a font. There is no rasterization step: colour emoji ship as\n// PNG assets (Noto, Twemoji, Fluent) or as bitmap strikes inside a font, so the\n// deterministic path is decode-then-box-filter, not outline flattening. That\n// makes raster-v1 (§13) inapplicable here by construction, not by omission.\n\nimport type { AsciiProfile, RawImage } from '@ascii-fx/core'\nimport { encodeProfile, idiv, nextPow2, rdiv } from '@ascii-fx/core'\nimport { COMPILER_VERSION, sha256 } from './profile.js'\n\nconst ATLAS_PADDING = 4\n/**\n * Reference cell for chromatic profiles. Square, unlike a text cell, and sized\n * so `cell + 2 * ATLAS_PADDING` is already a power of two: the pow2 pitch rule\n * (§13) exists so padding survives mip levels, and any other cell size rounds\n * up and wastes the difference. 32 would round 40 up to 64 and throw away 61%\n * of the atlas; 24 fits 32 exactly. The efficient sizes are 24, 56, and 120.\n */\nexport const CHROMATIC_CELL = 24\nexport const CHROMATIC_RASTER_VERSION = 'raster-chromatic-v1'\n\nexport interface ChromaticGlyphSource {\n /** The grapheme this glyph draws; may be several code points (ZWJ, VS16, modifiers). */\n char: string\n image: RawImage\n}\n\nexport interface BuildChromaticOptions {\n glyphs: readonly ChromaticGlyphSource[]\n /** Reference cell size in px, square. Default CHROMATIC_CELL (24). */\n cellSize?: number\n id?: string\n}\n\nexport interface BuiltChromaticProfile {\n profile: AsciiProfile\n binary: Uint8Array\n}\n\n/**\n * Alpha-weighted box filter, the same rule as reduce-v1 (§4): colour is\n * weighted by alpha so transparent pixels cannot drag the mean toward whatever\n * RGB happens to sit under them, while alpha itself is a plain mean.\n */\nfunction boxFilter(img: RawImage, tw: number, th: number): Uint8Array {\n const { width: w, height: h, data } = img\n const out = new Uint8Array(tw * th * 4)\n for (let ty = 0; ty < th; ty++) {\n const y0 = idiv(ty * h, th)\n const y1 = Math.max(y0 + 1, idiv((ty + 1) * h, th))\n for (let tx = 0; tx < tw; tx++) {\n const x0 = idiv(tx * w, tw)\n const x1 = Math.max(x0 + 1, idiv((tx + 1) * w, tw))\n let sr = 0\n let sg = 0\n let sb = 0\n let sa = 0\n let count = 0\n for (let y = y0; y < y1; y++) {\n for (let x = x0; x < x1; x++) {\n const p = (y * w + x) * 4\n const a = data[p + 3]\n sr += data[p] * a\n sg += data[p + 1] * a\n sb += data[p + 2] * a\n sa += a\n count++\n }\n }\n const q = (ty * tw + tx) * 4\n if (sa === 0) {\n out[q] = 0\n out[q + 1] = 0\n out[q + 2] = 0\n out[q + 3] = 0\n } else {\n out[q] = rdiv(sr, sa)\n out[q + 1] = rdiv(sg, sa)\n out[q + 2] = rdiv(sb, sa)\n out[q + 3] = rdiv(sa, count)\n }\n }\n }\n return out\n}\n\nexport function buildChromaticProfile(options: BuildChromaticOptions): BuiltChromaticProfile {\n const sources = options.glyphs\n const n = sources.length\n if (n === 0) throw new Error('buildChromaticProfile needs at least one glyph.')\n if (n > 65536)\n throw new Error(`Chromatic profiles hold at most 65536 glyphs (got ${n}); glyph ids are u16.`)\n\n const seen = new Set<string>()\n for (const g of sources) {\n if (g.char.length === 0) throw new Error('A chromatic glyph has an empty character.')\n if (seen.has(g.char)) {\n throw new Error(\n `Duplicate chromatic glyph ${JSON.stringify(g.char)}. Each grapheme may appear once.`,\n )\n }\n seen.add(g.char)\n if (g.image.width < 1 || g.image.height < 1) {\n throw new Error(`Glyph ${JSON.stringify(g.char)} has an empty image.`)\n }\n if (g.image.data.length !== g.image.width * g.image.height * 4) {\n throw new Error(`Glyph ${JSON.stringify(g.char)} image data is not width * height * 4.`)\n }\n }\n\n const cell = options.cellSize ?? CHROMATIC_CELL\n if (!Number.isInteger(cell) || cell < 8)\n throw new Error(`cellSize must be an integer >= 8 (got ${cell}).`)\n\n const pitch = nextPow2(cell + 2 * ATLAS_PADDING)\n let atlasColumns = 1\n while (atlasColumns * atlasColumns < n) atlasColumns++\n const atlasRows = idiv(n + atlasColumns - 1, atlasColumns)\n const atlasW = atlasColumns * pitch\n const atlasH = atlasRows * pitch\n\n const coverageAtlas = new Uint8Array(atlasW * atlasH)\n const rgbaAtlas = new Uint8Array(atlasW * atlasH * 4)\n const samples = new Uint8Array(n * 256)\n const masksLo = new Uint32Array(n)\n const masksHi = new Uint32Array(n)\n const coverage = new Uint16Array(n)\n\n for (let i = 0; i < n; i++) {\n const tile = boxFilter(sources[i].image, cell, cell)\n const tileX = (i % atlasColumns) * pitch + ATLAS_PADDING\n const tileY = idiv(i, atlasColumns) * pitch + ATLAS_PADDING\n let totalAlpha = 0\n for (let y = 0; y < cell; y++) {\n for (let x = 0; x < cell; x++) {\n const src = (y * cell + x) * 4\n const dst = (tileY + y) * atlasW + tileX + x\n rgbaAtlas[dst * 4] = tile[src]\n rgbaAtlas[dst * 4 + 1] = tile[src + 1]\n rgbaAtlas[dst * 4 + 2] = tile[src + 2]\n rgbaAtlas[dst * 4 + 3] = tile[src + 3]\n // The coverage plane is the alpha channel, which keeps blankGlyphId and\n // every structural consumer meaningful on a chromatic profile.\n coverageAtlas[dst] = tile[src + 3]\n totalAlpha += tile[src + 3]\n }\n }\n coverage[i] = rdiv(totalAlpha * 65535, cell * cell * 255)\n\n const small = boxFilter(sources[i].image, 8, 8)\n samples.set(small, i * 256)\n let lo = 0\n let hi = 0\n for (let k = 0; k < 64; k++) {\n // Same 0.5 threshold as raster-v1's mask rule (§13); ties are ink.\n if (small[k * 4 + 3] >= 128) {\n if (k < 32) lo |= 1 << k\n else hi |= 1 << (k - 32)\n }\n }\n masksLo[i] = lo >>> 0\n masksHi[i] = hi >>> 0\n }\n\n const glyphs = sources.map((g) => g.char)\n // There is no font, so the slot carrying a font's identity carries the\n // identity of the source images instead: same role, different provenance.\n let total = 0\n for (const g of sources) total += g.image.data.length\n const imageBytes = new Uint8Array(total)\n let at = 0\n for (const g of sources) {\n imageBytes.set(\n g.image.data instanceof Uint8Array ? g.image.data : new Uint8Array(g.image.data),\n at,\n )\n at += g.image.data.length\n }\n const sourceHash = sha256(imageBytes)\n const charsetHash = sha256(glyphs.join(' '))\n const fingerprint = sha256(\n `asciip/1|chromatic-v1|${CHROMATIC_RASTER_VERSION}|images:${sourceHash}|charset:${charsetHash}` +\n `|cell:${cell}|pad:${ATLAS_PADDING}`,\n )\n\n const profile: AsciiProfile = {\n version: 1,\n id: options.id ?? 'chromatic',\n fingerprint,\n charsetHash,\n fontHash: sourceHash,\n glyphs,\n glyphCount: n,\n // A chromatic cell is square and has no baseline; these describe that box so\n // grid-v1 derives square cells without the matcher special-casing anything.\n metrics: {\n unitsPerEm: cell,\n ascent: cell,\n descent: 0,\n lineGap: 0,\n advanceUnits: cell,\n cellWidth: cell,\n cellHeight: cell,\n baseline: cell,\n },\n atlas: {\n width: atlasW,\n height: atlasH,\n pitchWidth: pitch,\n pitchHeight: pitch,\n cellWidth: cell,\n cellHeight: cell,\n padding: ATLAS_PADDING,\n columns: atlasColumns,\n data: coverageAtlas,\n rgba: rgbaAtlas,\n },\n structural: { masksLo, masksHi, coverage },\n chromatic: { samples },\n metadata: {\n id: options.id ?? 'chromatic',\n charset: 'chromatic',\n compilerVersion: COMPILER_VERSION,\n },\n }\n\n return { profile, binary: encodeProfile(profile) }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BO,SAAS,kBAAkB,QAAkC;AAClE,SAAO;AACT;;;ACvBA,SAAS,eAAe,MAAM,UAAU,YAAY;AAGpD,IAAMA,iBAAgB;AAQf,IAAM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A,IACzC,WAAW,EAAE,QAAQ;AAAA,IACrB,UAAU;AAAA,MACR,IAAI,QAAQ,MAAM;AAAA,MAClB,SAAS;AAAA,MACT,iBAAiB;AAAA,IACnB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,QAAQ,cAAc,OAAO,EAAE;AACnD;","names":["ATLAS_PADDING"]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/chromatic.ts"],"sourcesContent":["import type { AlphaMode, ColorMode } from '@ascii-fx/core'\n\nexport interface AsciiProfileConfig {\n /** Path to the font file, relative to the config file. */\n font: string\n /** Which face of a .ttc/.otc collection: PostScript name or index. */\n face?: string | number\n charset?: string\n characters?: string | string[]\n /** Compile shape6-v1 data (ALGORITHM.md §18); `{ lut: true }` adds the dense LUT. */\n shape6?: boolean | { lut?: boolean }\n}\n\n/** Static build-time frame (spec §16). Matching happens at build, not runtime. */\nexport interface AsciiFrameConfig {\n /** Path to the source image (PNG in v1), relative to the config file. */\n image: string\n /** Profile name from `profiles`. Default 'default'. */\n profile?: string\n columns?: number\n rows?: number\n color?: ColorMode\n alpha?: AlphaMode\n}\n\nexport interface AsciiConfig {\n profiles: Record<string, AsciiProfileConfig>\n frames?: Record<string, AsciiFrameConfig>\n}\n\nexport function defineAsciiConfig(config: AsciiConfig): AsciiConfig {\n return config\n}\n","// Builds chromatic-v1 profiles (ALGORITHM.md §C) from decoded colour images\n// rather than from a font. There is no rasterization step: colour emoji ship as\n// PNG assets (Noto, Twemoji, Fluent) or as bitmap strikes inside a font, so the\n// deterministic path is decode-then-box-filter, not outline flattening. That\n// makes raster-v1 (§13) inapplicable here by construction, not by omission.\n\nimport type { AsciiProfile, RawImage } from '@ascii-fx/core'\nimport { encodeProfile, idiv, nextPow2, rdiv } from '@ascii-fx/core'\nimport { COMPILER_VERSION, sha256 } from './profile.js'\n\nconst ATLAS_PADDING = 4\n/**\n * Reference cell for chromatic profiles. Square, unlike a text cell, and sized\n * so `cell + 2 * ATLAS_PADDING` is already a power of two: the pow2 pitch rule\n * (§13) exists so padding survives mip levels, and any other cell size rounds\n * up and wastes the difference. 32 would round 40 up to 64 and throw away 61%\n * of the atlas; 24 fits 32 exactly. The efficient sizes are 24, 56, and 120.\n */\nexport const CHROMATIC_CELL = 24\nexport const CHROMATIC_RASTER_VERSION = 'raster-chromatic-v1'\n\nexport interface ChromaticGlyphSource {\n /** The grapheme this glyph draws; may be several code points (ZWJ, VS16, modifiers). */\n char: string\n image: RawImage\n}\n\nexport interface BuildChromaticOptions {\n glyphs: readonly ChromaticGlyphSource[]\n /** Reference cell size in px, square. Default CHROMATIC_CELL (24). */\n cellSize?: number\n id?: string\n}\n\nexport interface BuiltChromaticProfile {\n profile: AsciiProfile\n binary: Uint8Array\n}\n\n/**\n * Alpha-weighted box filter, the same rule as reduce-v1 (§4): colour is\n * weighted by alpha so transparent pixels cannot drag the mean toward whatever\n * RGB happens to sit under them, while alpha itself is a plain mean.\n */\nfunction boxFilter(img: RawImage, tw: number, th: number): Uint8Array {\n const { width: w, height: h, data } = img\n const out = new Uint8Array(tw * th * 4)\n for (let ty = 0; ty < th; ty++) {\n const y0 = idiv(ty * h, th)\n const y1 = Math.max(y0 + 1, idiv((ty + 1) * h, th))\n for (let tx = 0; tx < tw; tx++) {\n const x0 = idiv(tx * w, tw)\n const x1 = Math.max(x0 + 1, idiv((tx + 1) * w, tw))\n let sr = 0\n let sg = 0\n let sb = 0\n let sa = 0\n let count = 0\n for (let y = y0; y < y1; y++) {\n for (let x = x0; x < x1; x++) {\n const p = (y * w + x) * 4\n const a = data[p + 3]\n sr += data[p] * a\n sg += data[p + 1] * a\n sb += data[p + 2] * a\n sa += a\n count++\n }\n }\n const q = (ty * tw + tx) * 4\n if (sa === 0) {\n out[q] = 0\n out[q + 1] = 0\n out[q + 2] = 0\n out[q + 3] = 0\n } else {\n out[q] = rdiv(sr, sa)\n out[q + 1] = rdiv(sg, sa)\n out[q + 2] = rdiv(sb, sa)\n out[q + 3] = rdiv(sa, count)\n }\n }\n }\n return out\n}\n\nexport function buildChromaticProfile(options: BuildChromaticOptions): BuiltChromaticProfile {\n const sources = options.glyphs\n const n = sources.length\n if (n === 0) throw new Error('buildChromaticProfile needs at least one glyph.')\n if (n > 65536)\n throw new Error(`Chromatic profiles hold at most 65536 glyphs (got ${n}); glyph ids are u16.`)\n\n const seen = new Set<string>()\n for (const g of sources) {\n if (g.char.length === 0) throw new Error('A chromatic glyph has an empty character.')\n if (seen.has(g.char)) {\n throw new Error(\n `Duplicate chromatic glyph ${JSON.stringify(g.char)}. Each grapheme may appear once.`,\n )\n }\n seen.add(g.char)\n if (g.image.width < 1 || g.image.height < 1) {\n throw new Error(`Glyph ${JSON.stringify(g.char)} has an empty image.`)\n }\n if (g.image.data.length !== g.image.width * g.image.height * 4) {\n throw new Error(`Glyph ${JSON.stringify(g.char)} image data is not width * height * 4.`)\n }\n }\n\n const cell = options.cellSize ?? CHROMATIC_CELL\n if (!Number.isInteger(cell) || cell < 8)\n throw new Error(`cellSize must be an integer >= 8 (got ${cell}).`)\n\n const pitch = nextPow2(cell + 2 * ATLAS_PADDING)\n let atlasColumns = 1\n while (atlasColumns * atlasColumns < n) atlasColumns++\n const atlasRows = idiv(n + atlasColumns - 1, atlasColumns)\n const atlasW = atlasColumns * pitch\n const atlasH = atlasRows * pitch\n\n const coverageAtlas = new Uint8Array(atlasW * atlasH)\n const rgbaAtlas = new Uint8Array(atlasW * atlasH * 4)\n const samples = new Uint8Array(n * 256)\n const masksLo = new Uint32Array(n)\n const masksHi = new Uint32Array(n)\n const coverage = new Uint16Array(n)\n\n for (let i = 0; i < n; i++) {\n const tile = boxFilter(sources[i].image, cell, cell)\n const tileX = (i % atlasColumns) * pitch + ATLAS_PADDING\n const tileY = idiv(i, atlasColumns) * pitch + ATLAS_PADDING\n let totalAlpha = 0\n for (let y = 0; y < cell; y++) {\n for (let x = 0; x < cell; x++) {\n const src = (y * cell + x) * 4\n const dst = (tileY + y) * atlasW + tileX + x\n rgbaAtlas[dst * 4] = tile[src]\n rgbaAtlas[dst * 4 + 1] = tile[src + 1]\n rgbaAtlas[dst * 4 + 2] = tile[src + 2]\n rgbaAtlas[dst * 4 + 3] = tile[src + 3]\n // The coverage plane is the alpha channel, which keeps blankGlyphId and\n // every structural consumer meaningful on a chromatic profile.\n coverageAtlas[dst] = tile[src + 3]\n totalAlpha += tile[src + 3]\n }\n }\n coverage[i] = rdiv(totalAlpha * 65535, cell * cell * 255)\n\n const small = boxFilter(sources[i].image, 8, 8)\n samples.set(small, i * 256)\n let lo = 0\n let hi = 0\n for (let k = 0; k < 64; k++) {\n // Same 0.5 threshold as raster-v1's mask rule (§13); ties are ink.\n if (small[k * 4 + 3] >= 128) {\n if (k < 32) lo |= 1 << k\n else hi |= 1 << (k - 32)\n }\n }\n masksLo[i] = lo >>> 0\n masksHi[i] = hi >>> 0\n }\n\n const glyphs = sources.map((g) => g.char)\n // There is no font, so the slot carrying a font's identity carries the\n // identity of the source images instead: same role, different provenance.\n let total = 0\n for (const g of sources) total += g.image.data.length\n const imageBytes = new Uint8Array(total)\n let at = 0\n for (const g of sources) {\n imageBytes.set(\n g.image.data instanceof Uint8Array ? g.image.data : new Uint8Array(g.image.data),\n at,\n )\n at += g.image.data.length\n }\n const sourceHash = sha256(imageBytes)\n const charsetHash = sha256(glyphs.join(' '))\n const fingerprint = sha256(\n `asciip/1|chromatic-v1|${CHROMATIC_RASTER_VERSION}|images:${sourceHash}|charset:${charsetHash}` +\n `|cell:${cell}|pad:${ATLAS_PADDING}`,\n )\n\n const profile: AsciiProfile = {\n version: 1,\n id: options.id ?? 'chromatic',\n fingerprint,\n charsetHash,\n fontHash: sourceHash,\n glyphs,\n glyphCount: n,\n // A chromatic cell is square and has no baseline; these describe that box so\n // grid-v1 derives square cells without the matcher special-casing anything.\n metrics: {\n unitsPerEm: cell,\n ascent: cell,\n descent: 0,\n lineGap: 0,\n advanceUnits: cell,\n cellWidth: cell,\n cellHeight: cell,\n baseline: cell,\n },\n atlas: {\n width: atlasW,\n height: atlasH,\n pitchWidth: pitch,\n pitchHeight: pitch,\n cellWidth: cell,\n cellHeight: cell,\n padding: ATLAS_PADDING,\n columns: atlasColumns,\n data: coverageAtlas,\n rgba: rgbaAtlas,\n },\n structural: { masksLo, masksHi, coverage },\n chromatic: { samples },\n metadata: {\n id: options.id ?? 'chromatic',\n charset: 'chromatic',\n compilerVersion: COMPILER_VERSION,\n },\n }\n\n return { profile, binary: encodeProfile(profile) }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8BO,SAAS,kBAAkB,QAAkC;AAClE,SAAO;AACT;;;ACzBA,SAAS,eAAe,MAAM,UAAU,YAAY;AAGpD,IAAMA,iBAAgB;AAQf,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AAyBxC,SAAS,UAAU,KAAe,IAAY,IAAwB;AACpE,QAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,IAAI;AACtC,QAAM,MAAM,IAAI,WAAW,KAAK,KAAK,CAAC;AACtC,WAAS,KAAK,GAAG,KAAK,IAAI,MAAM;AAC9B,UAAM,KAAK,KAAK,KAAK,GAAG,EAAE;AAC1B,UAAM,KAAK,KAAK,IAAI,KAAK,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,CAAC;AAClD,aAAS,KAAK,GAAG,KAAK,IAAI,MAAM;AAC9B,YAAM,KAAK,KAAK,KAAK,GAAG,EAAE;AAC1B,YAAM,KAAK,KAAK,IAAI,KAAK,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,CAAC;AAClD,UAAI,KAAK;AACT,UAAI,KAAK;AACT,UAAI,KAAK;AACT,UAAI,KAAK;AACT,UAAI,QAAQ;AACZ,eAAS,IAAI,IAAI,IAAI,IAAI,KAAK;AAC5B,iBAAS,IAAI,IAAI,IAAI,IAAI,KAAK;AAC5B,gBAAM,KAAK,IAAI,IAAI,KAAK;AACxB,gBAAM,IAAI,KAAK,IAAI,CAAC;AACpB,gBAAM,KAAK,CAAC,IAAI;AAChB,gBAA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,IACA,YAAY;AAAA;AAAA;AAAA,IAGZ,SAAS;AAAA,MACP,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,SAAS;AAAA,MACT,cAAc;AAAA,MACd,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,aAAa;AAAA,MACb,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,SAASA;AAAA,MACT,SAAS;AAAA,MACT,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAAA,IACA,YAAY,EAAE,SAAS,SAAS,SAAS;AAAA,IACzC,WAAW,EAAE,QAAQ;AAAA,IACrB,UAAU;AAAA,MACR,IAAI,QAAQ,MAAM;AAAA,MAClB,SAAS;AAAA,MACT,iBAAiB;AAAA,IACnB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,QAAQ,cAAc,OAAO,EAAE;AACnD;","names":["ATLAS_PADDING"]}
|
package/dist/profile.d.ts
CHANGED
|
@@ -12,8 +12,10 @@ export declare const COMPILER_PACKAGE_VERSION: string;
|
|
|
12
12
|
export declare const REF_GLYPH_HEIGHT = 64;
|
|
13
13
|
export declare const ATLAS_PADDING = 4;
|
|
14
14
|
export interface BuildProfileOptions {
|
|
15
|
-
/** Raw font bytes (ttf/otf/woff/woff2). */
|
|
15
|
+
/** Raw font bytes (ttf/otf/woff/woff2, or a ttc/otc collection with `face`). */
|
|
16
16
|
font: Uint8Array;
|
|
17
|
+
/** Which face of a font collection: its PostScript name, or its index. Required for a collection. */
|
|
18
|
+
face?: string | number;
|
|
17
19
|
id?: string;
|
|
18
20
|
/** Built-in charset name; default 'ascii'. */
|
|
19
21
|
charset?: string;
|
|
@@ -22,7 +24,7 @@ export interface BuildProfileOptions {
|
|
|
22
24
|
/**
|
|
23
25
|
* Compile shape6-v1 data (ALGORITHM.md §18): 6D glyph vectors, and with
|
|
24
26
|
* `{ lut: true }` the 512KiB dense winner LUT. Opt-in — it grows the profile
|
|
25
|
-
* and only
|
|
27
|
+
* and only an explicit `matchFrameShape6` uses it (spec §5–6).
|
|
26
28
|
*/
|
|
27
29
|
shape6?: boolean | {
|
|
28
30
|
lut?: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ascii-fx/compiler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Build-time compiler for ASCII FX: deterministic font rasterization, glyph atlases, .asciip/.asciif generation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ascii",
|
|
@@ -41,12 +41,12 @@
|
|
|
41
41
|
"access": "public"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
+
"@ascii-fx/core": "0.9.0",
|
|
44
45
|
"fontkit": "^2.0.4",
|
|
45
|
-
"pngjs": "^7.0.0"
|
|
46
|
-
"@ascii-fx/core": "0.8.0"
|
|
46
|
+
"pngjs": "^7.0.0"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@types/node": "^26.
|
|
49
|
+
"@types/node": "^26.6.5",
|
|
50
50
|
"@types/pngjs": "^6.0.5",
|
|
51
51
|
"tsup": "^8.5.1",
|
|
52
52
|
"typescript": "^7.0.2"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/font.ts","../src/raster.ts","../src/profile.ts","../src/frameBuild.ts","../src/png.ts"],"sourcesContent":["import { Buffer } from 'node:buffer'\nimport * as FK from 'fontkit'\nimport type { Font } from 'fontkit'\n\nexport interface LoadedFont {\n font: Font\n unitsPerEm: number\n ascent: number\n descent: number\n lineGap: number\n familyName?: string\n weight?: number\n}\n\nexport function loadFont(bytes: Uint8Array): LoadedFont {\n const create =\n (FK as { create?: typeof FK.create }).create ??\n (FK as { default?: { create: typeof FK.create } }).default?.create\n if (!create) throw new Error('fontkit did not expose create(); incompatible fontkit version.')\n const font = create(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n if (font.fonts && font.fonts.length > 0) {\n throw new Error('Font collections (.ttc/.otc) are not supported; extract a single face first.')\n }\n return {\n font,\n unitsPerEm: font.unitsPerEm,\n ascent: font.ascent,\n descent: font.descent,\n lineGap: font.lineGap,\n familyName: font.familyName ?? font.postscriptName,\n weight: font['OS/2']?.usWeightClass,\n }\n}\n","// raster-v1 (ALGORITHM.md §13): deterministic fixed-point (26.6) scanline\n// rasterizer. No system rasterizer may replace this — profile bytes must be\n// identical across platforms.\n\nimport { fdiv, idiv, rdiv } from '@ascii-fx/core'\nimport type { FontPathCommand } from 'fontkit'\n\nexport const SUPERSAMPLE = 4\nexport const QUAD_SEGMENTS = 16\nexport const CUBIC_SEGMENTS = 24\n\n/** Font-unit → 26.6 pixel-space mappers (y-down). */\nexport interface FxMapping {\n x(v: number): number\n y(v: number): number\n}\n\n/** Flatten outline commands to non-horizontal line segments [x0,y0,x1,y1, ...] in 26.6. */\nexport function flattenCommands(commands: readonly FontPathCommand[], map: FxMapping): number[] {\n const edges: number[] = []\n let curX = 0\n let curY = 0\n let startX = 0\n let startY = 0\n let open = false\n\n const push = (x0: number, y0: number, x1: number, y1: number): void => {\n if (y0 !== y1) edges.push(x0, y0, x1, y1)\n }\n const lineTo = (x: number, y: number): void => {\n push(curX, curY, x, y)\n curX = x\n curY = y\n }\n const close = (): void => {\n if (open && (curX !== startX || curY !== startY)) push(curX, curY, startX, startY)\n open = false\n }\n\n for (const cmd of commands) {\n const a = cmd.args\n switch (cmd.command) {\n case 'moveTo':\n close()\n curX = startX = map.x(a[0])\n curY = startY = map.y(a[1])\n open = true\n break\n case 'lineTo':\n lineTo(map.x(a[0]), map.y(a[1]))\n break\n case 'quadraticCurveTo': {\n const n = QUAD_SEGMENTS\n const x0 = curX\n const y0 = curY\n const cx = map.x(a[0])\n const cy = map.y(a[1])\n const x2 = map.x(a[2])\n const y2 = map.y(a[3])\n for (let i = 1; i <= n; i++) {\n const w0 = (n - i) * (n - i)\n const w1 = 2 * i * (n - i)\n const w2 = i * i\n lineTo(rdiv(w0 * x0 + w1 * cx + w2 * x2, n * n), rdiv(w0 * y0 + w1 * cy + w2 * y2, n * n))\n }\n break\n }\n case 'bezierCurveTo': {\n const n = CUBIC_SEGMENTS\n const x0 = curX\n const y0 = curY\n const c1x = map.x(a[0])\n const c1y = map.y(a[1])\n const c2x = map.x(a[2])\n const c2y = map.y(a[3])\n const x3 = map.x(a[4])\n const y3 = map.y(a[5])\n for (let i = 1; i <= n; i++) {\n const u = n - i\n const w0 = u * u * u\n const w1 = 3 * i * u * u\n const w2 = 3 * i * i * u\n const w3 = i * i * i\n lineTo(\n rdiv(w0 * x0 + w1 * c1x + w2 * c2x + w3 * x3, n * n * n),\n rdiv(w0 * y0 + w1 * c1y + w2 * c2y + w3 * y3, n * n * n),\n )\n }\n break\n }\n case 'closePath':\n close()\n break\n }\n }\n close()\n return edges\n}\n\nexport interface GlyphRaster {\n /** Per-pixel subsample hit counts, cellW·cellH, each 0..SUPERSAMPLE². */\n hits: Uint8Array\n /** Subsample hits per 8×8 mask cell. */\n maskHits: Int32Array\n totalHits: number\n}\n\n/** Subsample totals per 8×8 mask cell — identical for every glyph of a given cell size. */\nexport function maskTotals(cellW: number, cellH: number): Int32Array {\n const S = SUPERSAMPLE\n const subW = cellW * S\n const subH = cellH * S\n const totals = new Int32Array(64)\n for (let sy = 0; sy < subH; sy++) {\n const rowBase = idiv(sy * 8, subH) * 8\n for (let sx = 0; sx < subW; sx++) totals[rowBase + idiv(sx * 8, subW)]++\n }\n return totals\n}\n\n/** Scanline fill (non-zero winding) over subsample centers. */\nexport function rasterizeGlyph(\n edges: readonly number[],\n cellW: number,\n cellH: number,\n): GlyphRaster {\n const S = SUPERSAMPLE\n const step = idiv(64, S) // 26.6 units between subsample centers\n const half = idiv(step, 2)\n const subW = cellW * S\n const subH = cellH * S\n const hits = new Uint8Array(cellW * cellH)\n const maskHits = new Int32Array(64)\n let totalHits = 0\n if (edges.length === 0) return { hits, maskHits, totalHits }\n\n for (let sy = 0; sy < subH; sy++) {\n const y = sy * step + half\n const crossings: Array<[number, number]> = []\n for (let e = 0; e < edges.length; e += 4) {\n const y0 = edges[e + 1]\n const y1 = edges[e + 3]\n const lo = Math.min(y0, y1)\n const hi = Math.max(y0, y1)\n if (y < lo || y >= hi) continue\n const x0 = edges[e]\n const x1 = edges[e + 2]\n crossings.push([x0 + fdiv((x1 - x0) * (y - y0), y1 - y0), y1 > y0 ? 1 : -1])\n }\n if (crossings.length === 0) continue\n crossings.sort((a, b) => a[0] - b[0])\n const mRowBase = idiv(sy * 8, subH) * 8\n const pRow = idiv(sy, S) * cellW\n let ci = 0\n let winding = 0\n for (let sx = 0; sx < subW; sx++) {\n const X = sx * step + half\n while (ci < crossings.length && crossings[ci][0] <= X) {\n winding += crossings[ci][1]\n ci++\n }\n if (winding !== 0) {\n hits[pRow + idiv(sx, S)]++\n maskHits[mRowBase + idiv(sx * 8, subW)]++\n totalHits++\n }\n }\n }\n return { hits, maskHits, totalHits }\n}\n\n/** Mask bit = 1 ⇔ 2·hits ≥ total (tie → ink). Returns 64-bit mask as lo/hi u32. */\nexport function deriveMask(maskHits: Int32Array, totals: Int32Array): { lo: number; hi: number } {\n let lo = 0\n let hi = 0\n for (let m = 0; m < 64; m++) {\n if (2 * maskHits[m] >= totals[m]) {\n if (m < 32) lo |= 1 << m\n else hi |= 1 << (m - 32)\n }\n }\n return { lo: lo >>> 0, hi: hi >>> 0 }\n}\n","import { createHash } from 'node:crypto'\nimport { readFileSync } from 'node:fs'\nimport type { AsciiProfile, Shape6GlyphData } from '@ascii-fx/core'\nimport {\n encodeProfile,\n idiv,\n nextPow2,\n rdiv,\n resolveCharset,\n shape6BucketCenter,\n} from '@ascii-fx/core'\nimport { loadFont } from './font.js'\nimport {\n CUBIC_SEGMENTS,\n QUAD_SEGMENTS,\n SUPERSAMPLE,\n deriveMask,\n flattenCommands,\n maskTotals,\n rasterizeGlyph,\n} from './raster.js'\n\nexport const COMPILER_VERSION = '0.1.0'\n\n/**\n * The @ascii-fx/compiler version actually installed, read from its own manifest so it cannot\n * drift the way a constant can. Every @ascii-fx/* package releases in one fixed group with\n * exact internal pins, so this moves on any release that could change output bytes — which is\n * what makes it a sound build-cache salt (@ascii-fx/vite keys on it). Deliberately separate\n * from COMPILER_VERSION: that string is embedded in profile metadata, where following the\n * package version would change profile bytes and break the golden fixtures on every release.\n */\nexport const COMPILER_PACKAGE_VERSION: string = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8'),\n).version\nexport const REF_GLYPH_HEIGHT = 64\nexport const ATLAS_PADDING = 4\n\nexport interface BuildProfileOptions {\n /** Raw font bytes (ttf/otf/woff/woff2). */\n font: Uint8Array\n id?: string\n /** Built-in charset name; default 'ascii'. */\n charset?: string\n /** Custom characters (overrides charset). */\n characters?: string | readonly string[]\n /**\n * Compile shape6-v1 data (ALGORITHM.md §18): 6D glyph vectors, and with\n * `{ lut: true }` the 512KiB dense winner LUT. Opt-in — it grows the profile\n * and only the explicit `matcher: 'shape6'` uses it (spec §5–6).\n */\n shape6?: boolean | { lut?: boolean }\n}\n\nexport interface BuiltProfile {\n profile: AsciiProfile\n binary: Uint8Array\n}\n\nexport const sha256 = (data: Uint8Array | string): string =>\n createHash('sha256').update(data).digest('hex')\n\n/** Glyph-side shape6 vector (ALGORITHM.md §18): float64 means over mask-cell lumas. */\nfunction glyphShape6(lumas: Float64Array, out: Float32Array, at: number): void {\n let sum = 0\n let top = 0\n let left = 0\n let tl = 0\n let tr = 0\n let bl = 0\n let br = 0\n let center = 0\n for (let m = 0; m < 64; m++) {\n const row = m >> 3\n const col = m & 7\n const v = lumas[m]\n sum += v\n if (row < 4) top += v\n if (col < 4) left += v\n if (row < 4) {\n if (col < 4) tl += v\n else tr += v\n } else if (col < 4) bl += v\n else br += v\n if (row >= 2 && row < 6 && col >= 2 && col < 6) center += v\n }\n const v0 = sum / 64\n out[at] = v0\n out[at + 1] = top / 32 - (sum - top) / 32\n out[at + 2] = left / 32 - (sum - left) / 32\n out[at + 3] = (tl + br - tr - bl) / 32\n out[at + 4] = center / 16 - (sum - center) / 48\n let dev = 0\n for (let m = 0; m < 64; m++) dev += Math.abs(lumas[m] - v0)\n out[at + 5] = dev / 64\n}\n\n/** Build a deterministic .asciip profile (ALGORITHM.md §13–14). */\nexport function buildProfile(options: BuildProfileOptions): BuiltProfile {\n const { name: charsetName, glyphs } = resolveCharset(options.charset, options.characters)\n const lf = loadFont(options.font)\n\n const missing = glyphs.filter((g) => !lf.font.hasGlyphForCodePoint(g.codePointAt(0)!))\n if (missing.length > 0) {\n throw new Error(\n `Font \"${lf.familyName ?? 'unknown'}\" has no glyph for: ${missing\n .map(\n (c) =>\n `${JSON.stringify(c)} (U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')})`,\n )\n .join(', ')}. Remove them from the charset or pick a font that covers them.`,\n )\n }\n\n const fontGlyphs = glyphs.map((g) => lf.font.glyphForCodePoint(g.codePointAt(0)!))\n const advance = fontGlyphs[0].advanceWidth\n const proportional = glyphs.filter((_, i) => fontGlyphs[i].advanceWidth !== advance)\n if (proportional.length > 0) {\n throw new Error(\n `Font \"${lf.familyName ?? 'unknown'}\" is not monospace over this charset — differing advances for: ${proportional\n .slice(0, 8)\n .map((c) => JSON.stringify(c))\n .join(', ')}${proportional.length > 8 ? ', …' : ''}. v1 requires a monospace font.`,\n )\n }\n\n const unitsCell = lf.ascent - lf.descent\n if (!(unitsCell > 0))\n throw new Error('Font reports non-positive ascent−descent; cannot derive a cell box.')\n const cellH = REF_GLYPH_HEIGHT\n const cellW = Math.max(1, rdiv(advance * REF_GLYPH_HEIGHT, unitsCell))\n const baseline = rdiv(lf.ascent * REF_GLYPH_HEIGHT, unitsCell)\n const baselineFx = rdiv(lf.ascent * REF_GLYPH_HEIGHT * 64, unitsCell)\n const map = {\n x: (v: number) => rdiv(v * REF_GLYPH_HEIGHT * 64, unitsCell),\n y: (v: number) => baselineFx - rdiv(v * REF_GLYPH_HEIGHT * 64, unitsCell),\n }\n\n const n = glyphs.length\n const masksLo = new Uint32Array(n)\n const masksHi = new Uint32Array(n)\n const coverage = new Uint16Array(n)\n\n const pitchW = nextPow2(cellW + 2 * ATLAS_PADDING)\n const pitchH = nextPow2(cellH + 2 * ATLAS_PADDING)\n let atlasColumns = 1\n while (atlasColumns * atlasColumns < n) atlasColumns++\n const atlasRows = idiv(n + atlasColumns - 1, atlasColumns)\n const atlasW = atlasColumns * pitchW\n const atlasH = atlasRows * pitchH\n const atlasData = new Uint8Array(atlasW * atlasH)\n\n const totals = maskTotals(cellW, cellH)\n const subsamplesPerCell = cellW * cellH * SUPERSAMPLE * SUPERSAMPLE\n const wantShape6 = options.shape6 !== undefined && options.shape6 !== false\n const cellLumas = wantShape6 ? new Float64Array(n * 64) : undefined\n\n for (let i = 0; i < n; i++) {\n const edges = flattenCommands(fontGlyphs[i].path.commands, map)\n const raster = rasterizeGlyph(edges, cellW, cellH)\n const mask = deriveMask(raster.maskHits, totals)\n masksLo[i] = mask.lo\n masksHi[i] = mask.hi\n coverage[i] = rdiv(raster.totalHits * 65535, subsamplesPerCell)\n if (cellLumas) {\n for (let m = 0; m < 64; m++) cellLumas[i * 64 + m] = (raster.maskHits[m] / totals[m]) * 255\n }\n const tileX = (i % atlasColumns) * pitchW + ATLAS_PADDING\n const tileY = idiv(i, atlasColumns) * pitchH + ATLAS_PADDING\n for (let py = 0; py < cellH; py++) {\n const dst = (tileY + py) * atlasW + tileX\n const src = py * cellW\n for (let px = 0; px < cellW; px++) {\n atlasData[dst + px] = rdiv(raster.hits[src + px] * 255, SUPERSAMPLE * SUPERSAMPLE)\n }\n }\n }\n\n let shape6: Shape6GlyphData | undefined\n if (cellLumas) {\n const vectors6 = new Float32Array(n * 6)\n for (let i = 0; i < n; i++)\n glyphShape6(cellLumas.subarray(i * 64, i * 64 + 64), vectors6, i * 6)\n let lut3: Uint16Array | undefined\n if (typeof options.shape6 === 'object' && options.shape6.lut) {\n lut3 = new Uint16Array(8 ** 6)\n const center = new Float64Array(6)\n for (let idx = 0; idx < lut3.length; idx++) {\n shape6BucketCenter(idx, center)\n let best = 0\n let bestD = Infinity\n for (let g = 0; g < n; g++) {\n let d = 0\n for (let c = 0; c < 6; c++) {\n const e = center[c] - vectors6[g * 6 + c]\n d += e * e\n }\n if (d < bestD) {\n bestD = d\n best = g\n }\n }\n lut3[idx] = best\n }\n }\n shape6 = { vectors6, lut3 }\n }\n\n const fontHash = sha256(options.font)\n const charsetHash = sha256(glyphs.join('\\u0000'))\n const fingerprint = sha256(\n `asciip/1|structural-v1|raster-v1|font:${fontHash}|charset:${charsetHash}` +\n `|H:${REF_GLYPH_HEIGHT}|S:${SUPERSAMPLE}|pad:${ATLAS_PADDING}|quad:${QUAD_SEGMENTS}|cubic:${CUBIC_SEGMENTS}`,\n )\n\n const profile: AsciiProfile = {\n version: 1,\n id: options.id ?? 'default',\n fingerprint,\n charsetHash,\n fontHash,\n glyphs,\n glyphCount: n,\n metrics: {\n unitsPerEm: lf.unitsPerEm,\n ascent: lf.ascent,\n descent: lf.descent,\n lineGap: lf.lineGap,\n advanceUnits: advance,\n cellWidth: cellW,\n cellHeight: cellH,\n baseline,\n },\n atlas: {\n width: atlasW,\n height: atlasH,\n pitchWidth: pitchW,\n pitchHeight: pitchH,\n cellWidth: cellW,\n cellHeight: cellH,\n padding: ATLAS_PADDING,\n columns: atlasColumns,\n data: atlasData,\n },\n structural: { masksLo, masksHi, coverage },\n shape6,\n metadata: {\n id: options.id ?? 'default',\n charset: charsetName,\n fontFamily: lf.familyName,\n fontWeight: lf.weight,\n compilerVersion: COMPILER_VERSION,\n },\n }\n\n return { profile, binary: encodeProfile(profile) }\n}\n","import type { AsciiFrame, AsciiProfile, MatchOptions, RawImage } from '@ascii-fx/core'\nimport { encodeFrame, matchFrame } from '@ascii-fx/core'\n\nexport interface BuildFrameOptions extends Omit<MatchOptions, 'profile'> {\n image: RawImage\n profile: AsciiProfile\n}\n\nexport interface BuiltFrame {\n frame: AsciiFrame\n binary: Uint8Array\n}\n\n/** Build-time static frame: run the exact matcher now so the client never has to. */\nexport function buildFrame(options: BuildFrameOptions): BuiltFrame {\n const { image, ...match } = options\n const frame = matchFrame(image, match)\n return { frame, binary: encodeFrame(frame) }\n}\n","import { Buffer } from 'node:buffer'\nimport { PNG } from 'pngjs'\nimport type { RawImage } from '@ascii-fx/core'\n\nexport function decodePng(bytes: Uint8Array): RawImage {\n const png = PNG.sync.read(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n return {\n width: png.width,\n height: png.height,\n data: new Uint8Array(png.data.buffer, png.data.byteOffset, png.data.length),\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,YAAY,QAAQ;AAab,SAAS,SAAS,OAA+B;AACtD,QAAMA,UACkC,aACa,YAAS;AAC9D,MAAI,CAACA,QAAQ,OAAM,IAAI,MAAM,gEAAgE;AAC7F,QAAM,OAAOA,QAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC;AACjF,MAAI,KAAK,SAAS,KAAK,MAAM,SAAS,GAAG;AACvC,UAAM,IAAI,MAAM,8EAA8E;AAAA,EAChG;AACA,SAAO;AAAA,IACL;AAAA,IACA,YAAY,KAAK;AAAA,IACjB,QAAQ,KAAK;AAAA,IACb,SAAS,KAAK;AAAA,IACd,SAAS,KAAK;AAAA,IACd,YAAY,KAAK,cAAc,KAAK;AAAA,IACpC,QAAQ,KAAK,MAAM,GAAG;AAAA,EACxB;AACF;;;AC5BA,SAAS,MAAM,MAAM,YAAY;AAG1B,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AASvB,SAAS,gBAAgB,UAAsC,KAA0B;AAC9F,QAAM,QAAkB,CAAC;AACzB,MAAI,OAAO;AACX,MAAI,OAAO;AACX,MAAI,SAAS;AACb,MAAI,SAAS;AACb,M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