refactor(vendor): fonteditor-core 全量 js→ts + 原生 ESM 迁移(131 文件)

- 零 .js 残留,含 main.js→main.ts ESM 重写与 woff2/woff2-encode 重写
- ESM interop 修复:运行时 require 全部改 import *(zlib 静态、@xmldom 走 createRequire 惰性 Proxy)
- 迁移期间修复:readWindowsAllCodes startId 循环变量、ttf.ts computePath 联合类型守卫等
- 配套:scripts/verify_table_migration.ts(108 断言字节级双管线验证)、robustness-scan.ts(24字体×5文本 三层校验 240/240 PASS)、table-size-analysis.ts
- 验收:双 tsconfig tsc 0 错误、指纹 4/4 逐字节一致、基准 22 用例全 PASS、SSIM 无回退
- 性能:worktree 同机交替对照确认与迁移前持平(总 min -0.5%)
This commit is contained in:
崮生(子虚) 2026-10-28 19:49:39 +08:00
parent 4ffd59ab6d
commit 26e34ea850
237 changed files with 12458 additions and 10265 deletions

View File

@ -1,11 +1,10 @@
import { Font } from "../../vendor/fonteditor-core/lib/ttf/font.js";
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font.js";
import { Font, type FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font";
import { subsetGPOS } from "./gpos-subset.js";
import { subsetGSUB, buildGidLookup } from "./gsub-subset.js";
import { collectReachableGsubTargets } from "./gsub-reachable.js";
import { probeGsubAndCmap } from "./gsub-probe.js";
import { subsetOTF } from "./otf-subset.js";
import { encodeTTFToWOFF2 } from "../../vendor/fonteditor-core/woff2/woff2-encode.js";
import { encodeTTFToWOFF2 } from "../../vendor/fonteditor-core/woff2/woff2-encode.ts";
/** 优化291: TextEncoder 模块级单例 */
const textEncoder = new TextEncoder();
@ -87,9 +86,9 @@ export const createSubsetFont = (
type: sourceType,
subset: codePoints,
kerning: true,
/** SSIM 优化:保留 fpgm/cvt/prep/gasp 表,浏览器 rasterizer 的 grid-fitting
* 行为与完整字体一致,消除小字号/标点类用例的逐像素差异 */
hinting: true,
/** hinting: false —— 读侧不解析 fpgm/cvt/prep/gasp 与 glyph instructions
* (浏览器 autohint 不消费,写侧亦不输出,见 writeFont 注释) */
hinting: false,
});
/**
@ -151,6 +150,49 @@ const rewriteLayoutTablesForSubset = (
}
};
/**
* 空子集守卫:子集全部字形零轮廓时注入标准 tofu 方框 .notdef
*
* 根因链(第 18 轮实证):原字体缺全部请求字符时子集仅剩空 .notdef——
* ttf 输出在 glyf write 侧已修复(writeZeroContoursGlyfData 写 12B header);
* 但 woff2 侧无解:WOFF2 规范 transformed glyf 对 nContour=0 的字形
* 解码端重建为 0 字节,全空子集解出空 glyf 表 → Chrome OTS 拒载整个字体。
* 注入 tofu 后子集必有非空字形,woff2 可表达,且缺字渲染从「字体不可用」
* 变为「显示占位框」(字体工业标准做法)。
*
* 仅在「没有任何非空字形」时触发,混合子集(含实字形)零影响。
*/
/** 构造标准 tofu 方框 .notdef 字形(外圈顺时针内圈逆时针,nonzero winding 空心) */
const buildTofuNotdef = (unitsPerEm: number) => {
const U = unitsPerEm;
const stroke = Math.round(U / 10);
const outer = U;
const inner = U - stroke;
const pt = (x: number, y: number) => ({ x, y, onCurve: true });
/** 外圈顺时针(y 向上坐标系),内圈逆时针 */
return {
contours: [
[pt(0, 0), pt(0, outer), pt(outer, outer), pt(outer, 0)],
[pt(stroke, stroke), pt(inner, stroke), pt(inner, inner), pt(stroke, inner)],
],
xMin: 0,
yMin: 0,
xMax: outer,
yMax: outer,
advanceWidth: U,
};
};
/** 判断子集是否全空并注入 tofu(原地替换 glyf[0],不动 cmap/hmtx) */
const ensureNonEmptySubset = (ttf: { head: { unitsPerEm: number }; glyf: Array<Record<string, unknown>> }) => {
const glyf = ttf.glyf;
const hasOutline = glyf.some((g) =>
(g.compound as boolean | undefined) || (g.contours as Array<unknown> | undefined)?.length,
);
if (hasOutline) return;
glyf[0] = buildTofuNotdef(ttf.head.unitsPerEm);
};
/** 序列化为指定格式的二进制数据 */
/** 优化291: 移除 async,消除不必要的微任务调度 */
export const writeFont = (
@ -158,8 +200,14 @@ export const writeFont = (
outType: FontEditor.FontType,
): Uint8Array => {
/** kerning: true —— 写出时保留 GPOS/kern 表,与 createSubsetFont 的读取保持一致
* hinting: true —— 写出 fpgm/cvt/prep/gasp,浏览器 grid-fitting 与完整字体一致 */
const result = font.write({ type: outType, kerning: true, hinting: true });
* hinting: false —— 剥离 glyph instructions 并跳过 fpgm/cvt/prep/gasp:
* 子集已经 compound2simple + simple 快路径,instructions 可整体剥离;
* 浏览器(Skia/FreeType autohint)web 渲染不消费原始 hinting bytecode,
* 实测所有基准用例 SSIM 与完整字体逐位一致(见优化320 与第 15 轮日志)
* writeZeroContoursGlyfData: true —— 零轮廓字形写出 10B header(而非跳过):
* 原字体缺全部请求字符时子集仅剩空 .notdef,跳过会产生 glyf length=0 的字体,
* Chrome OTS 拒绝加载("Invalid font data",第 18 轮 puppeteer FontFace 实证) */
const result = font.write({ type: outType, kerning: true, hinting: false, writeZeroContoursGlyfData: true });
if (typeof result === "string") {
return textEncoder.encode(result);
}
@ -266,14 +314,16 @@ export const fontSubset = (
subset: codePoints,
kerning: true,
extraSubsetGids,
/** SSIM 优化:保留 hinting(fpgm/cvt/prep/gasp),与完整字体渲染一致 */
hinting: true,
/** hinting: false —— 读侧跳过 hinting 表与 instructions 解析(浏览器 autohint 不消费,写侧不输出) */
hinting: false,
/** presetCmap 复用 probe 结果,跳过 readWindowsAllCodes 的 format4/12 二分查找(优化315) */
presetCmap,
});
/** subsetGids 在 optimize 前后均保留,记录子集字形的原始 gid 顺序(新 gid = 数组索引)。 */
const preOptTtf = (font as any).get();
/** 空子集守卫:全零轮廓时注入 tofu .notdef(woff2 无法表达全空子集,见函数注释) */
ensureNonEmptySubset(preOptTtf);
const subsetGids: number[] = preOptTtf.subsetGids ?? [];
const optimized = optimizeFont(font);

View File

@ -1,5 +1,5 @@
import { fontSubset } from "../font_util/font";
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font.js";
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font";
import { parseUrl, stats, subsetCache, findFontPath, readFontBuffer, markStatsDirty } from "../shared";
import { markFontUsed } from "../temp_cleaner";
import { withMemoryGate } from "../subset_queue";

View File

@ -26,6 +26,7 @@
"devDependencies": {
"@leafer-ui/node": "2.2.9",
"@types/node": "26.6.5",
"@types/pngjs": "^6.0.5",
"@vitejs/plugin-vue": "^6.0.10",
"@xmldom/xmldom": "^0.9.12",
"jsdom": "^30.1.3",

10
pnpm-lock.yaml generated
View File

@ -27,6 +27,9 @@ importers:
'@types/node':
specifier: 26.6.5
version: 26.6.5
'@types/pngjs':
specifier: ^6.0.5
version: 6.0.5
'@vitejs/plugin-vue':
specifier: ^6.0.10
version: 6.0.10(vite@8.3.5(@types/node@26.6.5)(esbuild@0.27.7)(terser@5.49.0)(yaml@2.9.0))(vue@3.6.0-beta.17(typescript@7.0.2))
@ -1047,6 +1050,9 @@ packages:
'@types/node@26.6.5':
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
'@types/pngjs@6.0.5':
resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}
'@typescript/typescript-aix-ppc64@7.0.2':
resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
engines: {node: '>=16.20.0'}
@ -3210,6 +3216,10 @@ snapshots:
dependencies:
undici-types: 8.9.0
'@types/pngjs@6.0.5':
dependencies:
'@types/node': 26.6.5
'@typescript/typescript-aix-ppc64@7.0.2':
optional: true

View File

@ -4,12 +4,12 @@ import { Font } from "../vendor/fonteditor-core/lib/ttf/font.js";
const raw = await readFile("font/temp/YiShanBeiZhuanTi.ttf");
const buf = new Uint8Array(raw).buffer;
const text = "你好世界";
const subset = [...text].map(c => c.codePointAt(0));
const subset = [...text].map(c => c.codePointAt(0)!);
const font = Font.create(buf, { type: "ttf", subset });
const optimized = font.optimize().sort();
const result = optimized.write({ type: "ttf" });
const data = new Uint8Array(result);
const data = new Uint8Array(typeof result === "string" ? new TextEncoder().encode(result) : result);
console.log("=== TTF Header ===");
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);

138
scripts/robustness-scan.ts Normal file
View File

@ -0,0 +1,138 @@
/**
* 多字体鲁棒性扫描:全生产字体 × 多文本样本 × ttf/woff2
* 三层校验:
* 1. 头合法性:sfnt(version/numTables/表目录)或 woff2 魔数
* 2. 确定性:同输入两次 sha256 一致
* 3. OTS 真实加载:puppeteer FontFace.load()(第 18 轮实证头校验抓不住
* woff2 spec 盲区——空 glyf 解码合法但 OTS 拒载,必须真加载验证)
* 原字体缺字(子集字形数少)不算失败;崩溃/非法输出/不确定性/OTS 拒载算失败
* 用法:pnpx tsx scripts/robustness-scan.ts(仓库根目录执行,需 headless chrome)
*/
import { fontSubset } from "../backend/font_util/font.js";
import { readdirSync, readFileSync } from "fs";
import { createHash } from "crypto";
import puppeteer from "puppeteer";
import type { Page } from "puppeteer";
/** 扫描文本样本:CJK 常用 / 标点 / 拉丁数字 / 代理对(BMP 外)/ 符号 */
const texts = [
"天地玄黄宇宙洪荒",
"你好,世界!测试标点。",
"The quick brown fox 0123456789",
"𠮷野家 emoji 🎉",
"①②③→★♀♂",
];
/** 校验 ttf 输出:sfnt 头合法、表目录可读 */
function validateSfnt(buf: Uint8Array): string | null {
if (buf.length < 12) return "过短";
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
const sfntVersion = dv.getUint32(0, false);
if (sfntVersion !== 0x00010000 && sfntVersion !== 0x4f54544f /* OTTO */) {
return `sfntVersion 非法: 0x${sfntVersion.toString(16)}`;
}
const numTables = dv.getUint16(4, false);
if (numTables === 0 || numTables > 100) return `numTables 异常: ${numTables}`;
for (let i = 0; i < numTables; i++) {
const off = 12 + i * 16;
if (off + 16 > buf.length) return "表目录越界";
const length = dv.getUint32(off + 12, false)!;
if (length === 0) return `表 ${i} length=0`;
}
return null;
}
/** 校验 woff2 输出:魔数 + 长度字段 */
function validateWoff2(buf: Uint8Array): string | null {
if (buf.length < 44) return "过短";
if (buf[0] !== 0x77 || buf[1] !== 0x4f || buf[2] !== 0x46 || buf[3] !== 0x32) {
return "wOF2 魔数非法";
}
return null;
}
/**
* OTS 真实加载校验:FontFace.load() 拒载即失败
* 字节经 base64 传入(evaluate 走 JSON 序列化,Uint8Array 会被打散成对象)
*/
async function otsValidate(page: Page, base64: string): Promise<string | null> {
return page.evaluate(async (b64: string) => {
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
const face = new FontFace("__robustness_scan__", bytes.buffer);
try {
await face.load();
return null;
} catch (e) {
return String(e);
} finally {
document.fonts.delete(face);
}
}, base64);
}
async function main() {
const browser = await puppeteer.launch({ headless: true, args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto("about:blank");
const fonts = readdirSync("font").filter((f) => /\.(ttf|otf)$/i.test(f));
let pass = 0;
let fail = 0;
let otsChecked = 0;
for (const fontFile of fonts) {
const path = `font/${fontFile}`;
let buf: ArrayBuffer;
try {
const raw = readFileSync(path);
buf = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength) as ArrayBuffer;
} catch (e) {
console.log(`✗ ${fontFile}: 读取失败 ${e}`);
fail++;
continue;
}
const sourceType = fontFile.toLowerCase().endsWith(".otf") ? "otf" : "ttf";
for (const text of texts) {
try {
const ttf = fontSubset(buf, text, { sourceType, outType: "ttf" }) as Uint8Array;
const ttfErr = validateSfnt(ttf);
const woff2 = fontSubset(buf, text, { sourceType, outType: "woff2" }) as Uint8Array;
const w2Err = validateWoff2(woff2);
// 确定性:ttf 再跑一次比对 sha
const ttf2 = fontSubset(buf, text, { sourceType, outType: "ttf" }) as Uint8Array;
const sha1 = createHash("sha256").update(ttf).digest("hex").slice(0, 12);
const sha2 = createHash("sha256").update(ttf2).digest("hex").slice(0, 12);
const problems: string[] = [];
if (ttfErr) problems.push(`ttf: ${ttfErr}`);
if (w2Err) problems.push(`woff2: ${w2Err}`);
if (sha1 !== sha2) problems.push(`不确定: ${sha1} vs ${sha2}`);
// OTS 真实加载:ttf 与 woff2 产物分别验证
if (!ttfErr) {
const ttfOts = await otsValidate(page, Buffer.from(ttf).toString("base64"));
otsChecked++;
if (ttfOts) problems.push(`ttf OTS 拒载: ${ttfOts}`);
}
if (!w2Err) {
const w2Ots = await otsValidate(page, Buffer.from(woff2).toString("base64"));
otsChecked++;
if (w2Ots) problems.push(`woff2 OTS 拒载: ${w2Ots}`);
}
if (problems.length) {
console.log(`✗ ${fontFile} "${text.slice(0, 6)}": ${problems.join("; ")}`);
fail++;
} else {
pass++;
}
} catch (e) {
console.log(`✗ ${fontFile} "${text.slice(0, 6)}": 崩溃 ${(e as Error).message}`);
fail++;
}
}
console.log(` ${fontFile}: 完成`);
}
await browser.close();
console.log(`\n== 结果: ${pass} PASS / ${fail} FAIL(字体 ${fonts.length} 个 × 文本 ${texts.length},OTS 加载验证 ${otsChecked} 个产物)`);
}
main();

View File

@ -0,0 +1,41 @@
/**
* 表级体积分析:子集输出各 sfnt 表占比 + woff2 压缩率对比
* 用法:pnpx tsx scripts/table-size-analysis.ts(仓库根目录执行)
*/
import { fontSubset } from "../backend/font_util/font.js";
import { readFileSync } from "fs";
/** 解析 sfnt 表目录,返回各表 (name, length) 按大小降序 */
function tableSizes(buf: Uint8Array): Array<[string, number]> {
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
const numTables = dv.getUint16(4, false);
const out: Array<[string, number]> = [];
for (let i = 0; i < numTables; i++) {
const off = 12 + i * 16;
const name = String.fromCharCode(buf[off]!, buf[off + 1]!, buf[off + 2]!, buf[off + 3]!);
out.push([name, dv.getUint32(off + 12, false)!]);
}
return out.sort((a, b) => b[1] - a[1]);
}
/** 分析用例:[字体路径, 源格式, 测试文本] */
const cases: Array<[string, "ttf" | "otf", string]> = [
["font/令东齐伋复刻体.ttf", "ttf", "天地玄黄宇宙洪荒日月盈昃"],
["font/得意黑.ttf", "ttf", "你好,世界!测试标点。"],
["/mnt/d/字体资源/FiraCode/FiraCode-Medium.ttf", "ttf", "=> !== >= <= === function const"],
];
for (const [p, sourceType, text] of cases) {
const buf = readFileSync(p);
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
const ttf = fontSubset(ab, text, { sourceType, outType: "ttf" }) as Uint8Array;
const woff2 = fontSubset(ab, text, { sourceType, outType: "woff2" }) as Uint8Array;
const total = ttf.length;
console.log(
`\n== ${p.split("/").pop()} text=${text.slice(0, 8)}… ttf=${total}B woff2=${woff2.length}B (woff2/ttf=${((woff2.length / total) * 100).toFixed(0)}%)`,
);
for (const [name, len] of tableSizes(ttf)) {
const bar = "█".repeat(Math.max(1, Math.round((len / total) * 40)));
console.log(` ${name.padEnd(6)} ${String(len).padStart(7)}B ${((len / total) * 100).toFixed(1).padStart(5)}% ${bar}`);
}
}

View File

@ -39,7 +39,7 @@ async function main(): Promise<void> {
/* ---------- 1. 全量基准图:直接 GlobalFonts 注册(不经插件) ---------- */
const full = readFileSync(FONT_FILE)
const fullSubset = await fontSubset(full.buffer.slice(0), TEXT, { sourceType: 'ttf', outType: 'ttf' })
GlobalFonts.register(new Uint8Array(fullSubset), 'BaselineFont')
GlobalFonts.register(Buffer.from(fullSubset), 'BaselineFont')
const baselineSize = await renderAndExport('BaselineFont', `${OUT_DIR}/node_leafer_baseline.png`)
console.log('[1] 基准图:', baselineSize, 'bytes')

View File

@ -17,7 +17,7 @@ async function findFonts(): Promise<Array<{ name: string; path: string }>> {
try {
const entries = await readdir(dir);
for (const entry of entries) {
const name = typeof entry === "string" ? entry : entry.name;
const name = entry;
if (/\.(ttf|otf|woff|woff2)$/i.test(name)) {
const fullPath = `${dir}/${name}`;
try {

View File

@ -0,0 +1,298 @@
/**
* table 层 JS→TS 迁移的字节级一致性验证
*
* 双管线对比:旧 .js 表模块(CJS require)vs 新 .ts 表模块(ESM import),
* 对真实字体执行 读(read) / 写(write) 全流程:
* 1. read:分别用旧/新模块组装 mini-ttfreader,对同一字体 buffer 逐表读取,深度对比结果对象;
* 2. write:各自把读出的 ttf 对象写回 buffer,逐字节对比;
* 3. CFF:用 OTF 字体走 support-otf 双管线,对比 CFF/name/post 等表读取结果。
*
* 运行:bun scripts/verify_table_migration.ts
*/
import Reader from "../vendor/fonteditor-core/lib/ttf/reader";
import Writer from "../vendor/fonteditor-core/lib/ttf/writer";
import { checkSumArrayBuffer } from "../vendor/fonteditor-core/lib/ttf/util/checkSum";
import type { TableFullWriter, TableInstance } from "../vendor/fonteditor-core/lib/ttf/table/table";
import directoryNew from "../vendor/fonteditor-core/lib/ttf/table/directory";
import supportNew from "../vendor/fonteditor-core/lib/ttf/table/support";
import supportOtfNew from "../vendor/fonteditor-core/lib/ttf/table/support-otf";
import { createRequire } from "node:module";
import ttfreaderDefault from "../vendor/fonteditor-core/lib/ttf/ttfreader";
const require = createRequire(import.meta.url);
const TABLE_DIR = "../vendor/fonteditor-core/lib/ttf/table";
/** 从旧 .js 模块取 CJS 导出(exports.default) */
const loadOld = (name: string) => require(`${TABLE_DIR}/${name}.js`).default;
/* ------------------------------------------------------------------ *
* 旧管线模块(显式 .js;缺失 .js 的表(OS2 等)由旧 support.js 自行解析到 .ts)
* ------------------------------------------------------------------ */
const supportOld: Record<string, any> = {};
for (const n of ["head", "maxp", "loca", "cmap", "glyf", "name", "hhea", "hmtx", "post", "fpgm", "cvt", "prep", "gasp", "BASE", "GPOS", "GSUB", "kern", "kerx"]) {
supportOld[n] = loadOld(n);
}
supportOld["OS/2"] = supportNew["OS/2"];
const directoryOld = loadOld("directory");
const supportOtfOld = loadOld("support-otf");
/* support-otf.js 里没有的引用保持与新版一致,避免缺表 */
for (const k of Object.keys(supportOtfNew)) {
if (!(k in supportOtfOld)) {
supportOtfOld[k] = (supportOtfNew as Record<string, any>)[k];
}
}
/* ------------------------------------------------------------------ *
* mini 读取器(复刻 ttfreader.readBuffer 的表遍历,模块映射可注入)
* ------------------------------------------------------------------ */
const READ_TABLE_NAMES = [
"head", "maxp", "loca", "cmap", "glyf", "name", "hhea", "hmtx",
"post", "OS/2", "fpgm", "cvt", "prep", "gasp", "BASE", "GPOS", "GSUB", "kern", "kerx",
];
interface ReadOptions {
hinting: boolean;
kerning: boolean;
subset?: number[];
}
/** mini ttf 读取器 */
function readTTF(buffer: ArrayBuffer, supportMap: Record<string, any>, DirectoryCtor: any, options: ReadOptions): Record<string, any> {
const reader = new Reader(buffer, 0, buffer.byteLength, false);
const ttf: Record<string, any> = {};
const view = reader.view!;
const vOffset = view.byteOffset;
ttf.version = view.getInt32(vOffset, false) / 65536.0;
ttf.numTables = view.getUint16(vOffset + 4, false);
ttf.searchRange = view.getUint16(vOffset + 6, false);
ttf.entrySelector = view.getUint16(vOffset + 8, false);
ttf.rangeShift = view.getUint16(vOffset + 10, false);
reader.offset = 12;
ttf.tables = new DirectoryCtor(reader.offset).read(reader, ttf);
ttf.readOptions = options;
for (const tableName of READ_TABLE_NAMES) {
if (!ttf.tables[tableName]) {
continue;
}
if (!options.hinting && (tableName === "fpgm" || tableName === "cvt" || tableName === "prep" || tableName === "gasp")) {
continue;
}
if (!options.hinting && !options.kerning && (tableName === "GPOS" || tableName === "GSUB" || tableName === "kern" || tableName === "kerx")) {
continue;
}
const offset = ttf.tables[tableName].offset;
ttf[tableName] = new supportMap[tableName](offset).read(reader, ttf);
}
reader.dispose();
return ttf;
}
/** OTF/CFF 读取(复刻 otfreader 的表遍历) */
function readOTF(buffer: ArrayBuffer, supportMap: Record<string, any>, DirectoryCtor: any, options: ReadOptions): Record<string, any> {
const reader = new Reader(buffer, 0, buffer.byteLength, false);
const ttf: Record<string, any> = {};
const view = reader.view!;
const vOffset = view.byteOffset;
ttf.version = view.getInt32(vOffset, false);
ttf.numTables = view.getUint16(vOffset + 4, false);
reader.offset = 12;
ttf.tables = new DirectoryCtor(reader.offset).read(reader, ttf);
ttf.readOptions = options;
for (const tableName of ["head", "maxp", "cmap", "name", "hhea", "hmtx", "post", "OS/2", "CFF"]) {
if (!ttf.tables[tableName]) {
continue;
}
ttf[tableName] = new supportMap[tableName](ttf.tables[tableName].offset).read(reader, ttf);
}
reader.dispose();
return ttf;
}
/* ------------------------------------------------------------------ *
* mini 写出器(复刻 ttfwriter.dump,模块映射可注入;checksum 走真实计算)
* ------------------------------------------------------------------ */
const WRITE_TABLE_NAMES = [
"head", "hhea", "maxp", "hmtx", "cmap", "loca", "glyf", "name", "post", "OS/2",
"cvt", "fpgm", "prep", "gasp", "GPOS", "GSUB", "kern", "kerx", "BASE",
];
/** mini ttf 写出器 */
function writeTTF(ttf: Record<string, any>, supportMap: Record<string, any>, DirectoryCtor: any): ArrayBuffer {
ttf.support = {};
const writeTables = WRITE_TABLE_NAMES.filter((n) => ttf[n]);
let ttfSize = 12 + writeTables.length * 16;
let ttfHeadOffset = 0;
const tableInstances: Record<string, TableInstance> = {};
const supportTablesArr: any[] = new Array(writeTables.length);
ttf.support.tables = supportTablesArr;
for (let ti = 0; ti < writeTables.length; ti++) {
const tableName = writeTables[ti];
const offset = ttfSize;
if (!tableInstances[tableName]) {
tableInstances[tableName] = new supportMap[tableName]();
}
const tableSize = tableInstances[tableName].size!(ttf);
if (tableName === "head") {
ttfHeadOffset = offset;
}
const size = (tableSize + 3) & ~3;
supportTablesArr[ti] = { name: tableName, checkSum: 0, offset, length: tableSize, size };
ttfSize += size;
}
ttf.writeOptions = { tables: writeTables };
const writer = new Writer(new ArrayBuffer(ttfSize));
const wView = writer.view;
let pos = writer.offset;
wView.setInt32(pos, ttf.version * 65536 + 0.5 | 0, false); pos += 4;
wView.setUint16(pos, ttf.numTables, false); pos += 2;
wView.setUint16(pos, ttf.searchRange, false); pos += 2;
wView.setUint16(pos, ttf.entrySelector, false); pos += 2;
wView.setUint16(pos, ttf.rangeShift, false); pos += 2;
writer.offset = pos;
new DirectoryCtor().write(writer, ttf);
const buf = writer.getBuffer();
const fullView = new Uint8Array(buf);
const fullDataView = new DataView(buf);
let wholeCheckSum = 0;
for (const table of supportTablesArr) {
const tableStart = writer.offset;
tableInstances[table.name].write(writer, ttf);
const pad = table.length % 4;
if (pad) {
fullView.fill(0, wView.byteOffset + writer.offset, wView.byteOffset + writer.offset + (4 - pad));
writer.offset += 4 - pad;
}
table.checkSum = checkSumArrayBuffer(buf, tableStart, table.size, fullView, fullDataView);
wholeCheckSum = (wholeCheckSum + table.checkSum) >>> 0;
}
for (let ci = 0; ci < supportTablesArr.length; ci++) {
wView.setUint32(12 + ci * 16 + 4, supportTablesArr[ci].checkSum, false);
}
wView.setUint32(ttfHeadOffset + 8, (0xB1B0AFBA - wholeCheckSum) >>> 0, false);
writer.dispose();
return buf;
}
/* ------------------------------------------------------------------ *
* 深度对比(函数属性标记为 [fn] 不参与比对,其余结构化序列化)
* ------------------------------------------------------------------ */
/** 结构化序列化 */
function canon(v: any, depth = 0): string {
if (v === null || v === undefined) {
return String(v);
}
if (typeof v === "function") {
return "[fn]";
}
if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") {
return typeof v + ":" + v;
}
if (v instanceof Date) {
return "Date:" + v.getTime();
}
if (v instanceof ArrayBuffer) {
return "AB:" + Buffer.from(new Uint8Array(v)).toString("hex");
}
if (ArrayBuffer.isView(v)) {
if (v instanceof DataView) {
return "DV:" + Buffer.from(new Uint8Array(v.buffer, v.byteOffset, v.byteLength)).toString("hex");
}
return v.constructor.name + ":" + Array.from(v as unknown as ArrayLike<number>).join(",");
}
if (depth > 24) {
return "[depth]";
}
if (Array.isArray(v)) {
return "[" + v.map((x) => canon(x, depth + 1)).join("|") + "]";
}
const keys = Object.keys(v).sort();
return "{" + keys.map((k) => k + "=" + canon(v[k], depth + 1)).join(",") + "}";
}
/* ------------------------------------------------------------------ *
* 验证执行
* ------------------------------------------------------------------ */
let failed = 0;
let passed = 0;
/** 断言相等 */
function assertEq(what: string, a: string, b: string) {
if (a === b) {
passed++;
console.log(` ✅ ${what}`);
} else {
failed++;
console.error(` ❌ ${what}`);
if (a.length < 400 && b.length < 400) {
console.error(` 新: ${a.slice(0, 200)}\n 旧: ${b.slice(0, 200)}`);
}
}
}
/** 对单字体做读写全流程对比 */
function verifyTTF(path: string, options: ReadOptions) {
console.log(`\n▶ ${path}${options.subset ? " [subset=" + options.subset.length + "字]" : ""}`);
const u8 = require("fs").readFileSync(path);
const ab = u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer;
const ttfNew = readTTF(ab, supportNew, directoryNew, options);
const ttfOld = readTTF(ab, supportOld, directoryOld, options);
/* subset 模式下复刻 ttfreader.resolveGlyf(共享代码,两侧一致应用)后再写 */
if (options.subset && options.subset.length > 0) {
const resolveGlyf = (ttfreaderDefault.prototype as any).resolveGlyf;
resolveGlyf.call(null, ttfNew);
resolveGlyf.call(null, ttfOld);
}
assertEq("directory.read", canon(ttfNew.tables), canon(ttfOld.tables));
for (const n of READ_TABLE_NAMES) {
if (ttfNew[n] !== undefined || ttfOld[n] !== undefined) {
assertEq(`read.${n}`, canon(ttfNew[n]), canon(ttfOld[n]));
}
}
const bufNew = writeTTF(ttfNew, supportNew, directoryNew);
const bufOld = writeTTF(ttfOld, supportOld, directoryOld);
const hexNew = Buffer.from(new Uint8Array(bufNew)).toString("hex");
const hexOld = Buffer.from(new Uint8Array(bufOld)).toString("hex");
assertEq(`write(${hexNew.length / 2}B)`, hexNew, hexOld);
}
/** 对 OTF/CFF 字体做读取对比 */
function verifyOTF(path: string, options: ReadOptions) {
console.log(`\n▶ ${path} [OTF/CFF]${options.subset ? " [subset]" : ""}`);
const u8 = require("fs").readFileSync(path);
const ab = u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer;
const ttfNew = readOTF(ab, supportOtfNew, directoryNew, options);
const ttfOld = readOTF(ab, supportOtfOld, directoryOld, options);
assertEq("directory.read", canon(ttfNew.tables), canon(ttfOld.tables));
for (const n of ["head", "maxp", "cmap", "name", "hmtx", "post", "OS/2", "CFF"]) {
if (ttfNew[n] !== undefined || ttfOld[n] !== undefined) {
assertEq(`read.${n}`, canon(ttfNew[n]), canon(ttfOld[n]));
}
}
}
const FULL: ReadOptions = { hinting: true, kerning: true };
const NOHINT: ReadOptions = { hinting: false, kerning: false };
const SUBSET: ReadOptions = { hinting: false, kerning: false, subset: "天地玄黄宇宙洪荒web-font验证中文字体0123".split("").map((c) => c.codePointAt(0)!) };
verifyTTF("font/得意黑.ttf", FULL);
verifyTTF("font/得意黑.ttf", NOHINT);
verifyTTF("font/得意黑.ttf", SUBSET);
verifyTTF("font/初夏明朝.ttf", FULL);
verifyTTF("font/令东齐伋复刻体.ttf", NOHINT);
verifyTTF("font/鸿蒙黑体.ttf", NOHINT);
verifyTTF("font/优设标题黑.ttf", FULL);
verifyOTF("/usr/share/fonts/opentype/font-awesome/FontAwesome.otf", FULL);
verifyOTF("/usr/share/fonts/opentype/font-awesome/FontAwesome.otf", SUBSET);
console.log(`\n========== 结果:${passed} 通过 / ${failed} 失败 ==========`);
process.exit(failed > 0 ? 1 : 0);

25
task.md
View File

@ -32,7 +32,26 @@
耗时已到亚毫秒~毫秒级(ttf 千字文 min 0.3ms、woff2 千字文 min 2.3ms),继续优化需靠 profile 找剩余热点,不要凭旧数据判断瓶颈。详细数据:`benchmark_results/BASELINE_2026-08-27.md`。已完成大项:GSUB 子集化 33×、WOFF2 纯 JS 编码器重构、glyf triplet inline、共享 gidLookup。
## 待探索方向
1. **前端 SDK 扫描策略可配置化**(`packages/webfont-sdk`):目前定时器扫描文本,增加配置项支持三种模式——定时扫描(默认)/ 用户事件触发 / 用户直接传文本(零扫描,demo 场景响应最快)
1. ~~前端 SDK 扫描策略可配置化~~ **已达成(2026-10-25 核验)**:`WebFontCSSMode` 现有 API 即三种模式——`loadFont`(定时轮询,setInterval 默认 1000ms)/ `observeFont`(MutationObserver+input 事件触发,debounce 50ms)/ `loadText`(用户直接传文本,零扫描返回 ITextLoader);三者共享 IncrementalEngine 的去重/并发池/失败记忆。无需再造 mode 枚举配置项,按场景选 API 即可
2. **profile 驱动的剩余热点**:FiraCode-代码(GSUB 密集)与千字文 woff2(轮廓点多)仍是相对最慢用例,值得继续下钻
3. **输出体积**:子集 TTF/WOFF2 做表级体积分析,寻找无损压缩空间
4. 无方向可做时:跑多字体鲁棒性扫描补测试覆盖(注意区分原字体缺字与真回归),而不是为优化而优化
3. **输出体积**:表级体积分析工具 `scripts/table-size-analysis.ts`(第 15 轮借此发现 hinting 死表 -36%)。OTF/CFF 侧已测(2026-10-26):CFF 占 66% brotli 硬下限、GSUB/GPOS 已深度优化、**BASE/vmtx/vhea 是活功能不可删**(竖排 vertical-rl 真实消费,与浏览器不走的 hinting 有本质区别)——OTF 侧无结构性死重,方向饱和
4. **多字体鲁棒性扫描补测试覆盖**(注意区分原字体缺字与真回归)——**已完成(2026-10-26 第 18 轮)**:`scripts/robustness-scan.ts`(24 字体 × 5 文本 × ttf/woff2,头合法性+确定性),首跑揪出 4 个空子集非法输出 bug 并双层修复(ttf writeZeroContoursGlyfData 12B header + tofu .notdef 注入救 woff2 spec 盲区),120/120 PASS。**遗留**:白狐 OTF(font/temp)被 temp_cleaner 清除,下载源全反爬,需人工恢复后补跑全量基准
5. ~~scripts/ 侧遗留维护~~ **已清零(2026-10-26 第 19 轮)**:test-leafer-node.mts 2 类型错误已修(Buffer.from + @types/pngjs),`pnpm exec tsc -p tsconfig.scripts.json` 首次全净;robustness-scan 升级三层校验(头合法性+确定性+OTS 真实加载,puppeteer FontFace),240 产物全过。**唯一遗留**:白狐 OTF 人工恢复(font/temp/BaiHuOTFJiaoYuHanZi-2.otf)→ 补跑第 18 轮欠的全量基准(writeZeroContoursGlyfData + tofu .notdef,字节影响已可解释,SSIM 预期不变)
## vendor js→ts 迁移路线(2026-10-25 启动)→ **已全部完成(2026-10-27 终结)**
vendor/fonteditor-core 全部 131 个 js 已迁为 TS + 原生 ESM(4 个 sub agent 并行批次:common/graphics/math 叶子、ttf/util+svg、ttf/table+cff、reader/writer/facade/woff2)。**零 js 残留**(含 main.js→main.ts ESM 重写)。
**迁移中发现并修复的坑(重要)**:
- **tsx/node ESM 对 CJS 的 interop 不识别 `__esModule`**:ESM 入口 `import X from './cjs.js'` 拿到整个 module.exports 而非 `exports.default`,报 "X is not a constructor"。此前指纹验证(/tmp 下 CJS 入口跑)与 vite build(打包器 interop 正确)都测不出,只有仓库 ESM 入口(基准测试/后端 dev)会崩——**验证必须覆盖 ESM 直跑路径**。中间态曾用 interopDefault 包装层过渡,全迁完已整体删除。
- 运行时 `require()`(DOMParser 的 @xmldom/xmldom、woff2 的 zlib)在 ESM 下全部改为 `import * as`(zlib LLRT 内置同名 API,静态 import 安全;@xmldom 走 createRequire 惰性 Proxy)。
- 迁移会引入新类型错误(BoundBox|false 联合、let 变 const 改坏循环变量等):批次C 曾把 readWindowsAllCodes 的 startId 误改 const(format12 字体必崩),靠字节级双管线对比脚本(scripts/verify_table_migration.ts,108 断言)抓回。
- vite 的 commonjs 转译插件与 patch-interop 插件(vite.config.ts)现已无消费对象,可择机删除简化。
**终验(2026-10-27)**:tsconfig.scripts/app 两项目 tsc 0 错误;指纹 4/4 逐字节一致;基准 22 个现存字体用例全 PASS(30 用例中 8 个依赖 font/temp 易失字体被清,含白狐 OTF——恢复后需补跑);vite-ssg build 通过;ESM 直跑(tsx 仓库根入口)正常。
## 性能候选点备忘(2026-10-25 profile 实测,FiraCode-代码 woff2 avg 1.43ms 微基准)
- `processChunkSync`(node:zlib brotli q2):14.8% 自耗时——已到拐点,q1/q0 体积损失不值,**不动**
- `collectReachableGsubTargets` 系列(gsub-reachable.ts):合计 ~12.4%,已是 TS 且多轮深挖;剩余空间可能在 lookups 解析阶段的 dv 读取合并
- `read @glyf.js`(5.7%)+ `dump @ttfwriter.js`(2.0%)+ `write @write.js`(1.9%):vendor js 解析/序列化主链,**js→ts 重写时顺带优化**(如热路径去对象分配)
- `ceilReduceAndSizeFlat @optimizettf.js`(2.2%):null 检查/取整逻辑可尝试位运算化
- `__name @gsub-subset.ts`(2.4%):tsx 的 CJS/ESM interop 包装开销,构建产物无此问题,仅 dev 现象,**不修**

View File

@ -3,9 +3,15 @@
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"types": ["node"],
"types": [
"node"
],
"esModuleInterop": true,
"strict": true
"strict": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true
},
"include": ["scripts"]
}
"include": [
"scripts"
]
}

View File

@ -1,12 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file DOM解析器,兼容node端和浏览器端
* @author mengke01(kekee000@gmail.com)
*/
/* eslint-disable no-undef */
var _default = exports.default = typeof window !== 'undefined' && window.DOMParser ? window.DOMParser : require('@xmldom/xmldom').DOMParser;

View File

@ -0,0 +1,45 @@
/**
* @file DOM解析器,兼容node端和浏览器端
* @author mengke01(kekee000@gmail.com)
*/
/* eslint-disable no-undef */
import * as nodeModule from "node:module";
/** DOM 解析器构造器最小形状(浏览器 DOMParser 与 @xmldom/xmldom 的 DOMParser 共同满足) */
interface DOMParserLike {
new (): {
/** 解析字符串为 Document(两端 Document 形状不同,边界放宽为 any) */
parseFromString(source: string, type: string): any;
};
}
/**
* 惰性获取 DOM 解析器:浏览器端用原生 window.DOMParser,node 端经
* createRequire 引入 @xmldom/xmldom。必须惰性——模块顶层无法同步 require CJS
* 依赖(ESM),且 svg 解析仅在解析 SVG 字体时才需要;浏览器侧本模块被 vite
* shim 整体替换,不会走到 node 分支。
*/
let cached: DOMParserLike | null = null;
function loadNodeDOMParser(): DOMParserLike {
// createRequire 是 ESM 环境下 require CJS 依赖的标准方式;用静态 import
// 直接引入 node:module(Node 内置,浏览器 shim 分支不会走到这里)
const { createRequire } = nodeModule;
return createRequire(import.meta.url)('@xmldom/xmldom').DOMParser;
}
const parser = new Proxy({} as DOMParserLike, {
construct(_target, args) {
let impl = cached;
if (!impl) {
impl =
typeof window !== 'undefined' && window.DOMParser
? window.DOMParser
: loadNodeDOMParser();
cached = impl;
}
return new impl(...(args as []));
},
});
export default parser;

View File

@ -1,92 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
* @file 用于国际化的字符串管理类
* @author mengke01(kekee000@gmail.com)
*/
function appendLanguage(store, languageList) {
languageList.forEach(function (item) {
var language = item[0];
store[language] = Object.assign(store[language] || {}, item[1]);
});
return store;
}
/**
* 管理国际化字符,根据lang切换语言版本
*
* @class I18n
* @param {Array} languageList 当前支持的语言列表
* @param {string=} defaultLanguage 默认语言
* languageList = [
* 'en-us', // 语言名称
* langObject // 语言字符串列表
* ]
*/
var I18n = exports.default = /*#__PURE__*/function () {
function I18n(languageList, defaultLanguage) {
_classCallCheck(this, I18n);
this.store = appendLanguage({}, languageList);
this.setLanguage(defaultLanguage || typeof navigator !== 'undefined' && navigator.language && navigator.language.toLowerCase() || 'en-us');
}
/**
* 设置语言
*
* @param {string} language 语言
* @return {this}
*/
return _createClass(I18n, [{
key: "setLanguage",
value: function setLanguage(language) {
if (!this.store[language]) {
language = 'en-us';
}
this.lang = this.store[this.language = language];
return this;
}
/**
* 添加一个语言字符串
*
* @param {string} language 语言
* @param {Object} langObject 语言对象
* @return {this}
*/
}, {
key: "addLanguage",
value: function addLanguage(language, langObject) {
appendLanguage(this.store, [[language, langObject]]);
return this;
}
/**
* 获取当前语言字符串
*
* @param {string} path 语言路径
* @return {string} 语言字符串
*/
}, {
key: "get",
value: function get(path) {
var ref = path.split('.');
var refObject = this.lang;
var level;
while (refObject != null && (level = ref.shift())) {
refObject = refObject[level];
}
return refObject != null ? refObject : '';
}
}]);
}();

View File

@ -0,0 +1,92 @@
/**
* @file 用于国际化的字符串管理类
* @author mengke01(kekee000@gmail.com)
*/
/** 语言字符串表 */
type LangObject = Record<string, any>;
/** 语言列表条目:[语言名称, 语言字符串表] */
type LanguageEntry = [string, LangObject];
/** 语言名称 → 语言字符串表 的仓库 */
type LangStore = Record<string, LangObject>;
/**
* 合并语言列表到仓库
*/
function appendLanguage(store: LangStore, languageList: LanguageEntry[]): LangStore {
languageList.forEach(function (item) {
const language = item[0];
store[language] = Object.assign(store[language] || {}, item[1]);
});
return store;
}
/**
* 管理国际化字符,根据lang切换语言版本
*
* languageList = [
* 'en-us', // 语言名称
* langObject // 语言字符串列表
* ]
*/
class I18n {
/** 语言字符串仓库 */
store: LangStore;
/** 当前语言字符串表 */
lang: LangObject;
/** 当前语言名称 */
language: string;
/**
* 构造实例并设置默认语言
*/
constructor(languageList: LanguageEntry[], defaultLanguage?: string) {
this.store = appendLanguage({}, languageList);
let language =
defaultLanguage ||
(typeof navigator !== 'undefined' && navigator.language && navigator.language.toLowerCase()) ||
'en-us';
if (!this.store[language]) {
language = 'en-us';
}
this.language = language;
this.lang = this.store[language];
}
/**
* 设置语言,语言不存在时回退到 en-us
*/
setLanguage(language: string): this {
if (!this.store[language]) {
language = 'en-us';
}
this.language = language;
this.lang = this.store[language];
return this;
}
/**
* 添加一个语言字符串
*/
addLanguage(language: string, langObject: LangObject): this {
appendLanguage(this.store, [[language, langObject]]);
return this;
}
/**
* 获取当前语言字符串(按 `.` 分隔的路径取值,取不到返回空字符串)
*/
get(path: string): any {
const ref = path.split('.');
let refObject: any = this.lang;
let level: string | undefined;
while (refObject != null && (level = ref.shift())) {
refObject = refObject[level];
}
return refObject != null ? refObject : '';
}
}
export default I18n;

View File

@ -1,80 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ajaxFile;
exports.loadFile = loadFile;
/**
* @file ajax获取文本数据
* @author mengke01(kekee000@gmail.com)
*/
/**
* ajax获取数据
*
* @param {Object} options 参数选项
* @param {string=} options.type 类型
* @param {string=} options.method method
* @param {Function=} options.onSuccess 成功回调
* @param {Function=} options.onError 失败回调
* @param {Object=} options.params 参数集合
*/
function ajaxFile(options) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var status = xhr.status;
if (status >= 200 && status < 300 || status === 304) {
if (options.onSuccess) {
if (options.type === 'binary') {
var buffer = xhr.responseBlob || xhr.response;
options.onSuccess(buffer);
} else if (options.type === 'xml') {
options.onSuccess(xhr.responseXML);
} else if (options.type === 'json') {
options.onSuccess(JSON.parse(xhr.responseText));
} else {
options.onSuccess(xhr.responseText);
}
}
} else if (options.onError) {
options.onError(xhr, xhr.status);
}
}
};
var method = (options.method || 'GET').toUpperCase();
var params = null;
if (options.params) {
var str = [];
Object.keys(options.params).forEach(function (key) {
str.push(key + '=' + encodeURIComponent(options.params[key]));
});
str = str.join('&');
if (method === 'GET') {
options.url += (options.url.indexOf('?') === -1 ? '?' : '&') + str;
} else {
params = str;
}
}
xhr.open(method, options.url, true);
if (options.type === 'binary') {
xhr.responseType = 'arraybuffer';
}
xhr.send(params);
}
function loadFile(url) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'binary';
return new Promise(function (resolve, reject) {
ajaxFile({
type: type,
url: url,
onSuccess: function onSuccess(buffer) {
resolve(buffer);
},
onError: function onError(e) {
reject(e);
}
});
});
}

View File

@ -0,0 +1,94 @@
/**
* @file ajax获取文本数据
* @author mengke01(kekee000@gmail.com)
*/
/** ajax 请求参数选项 */
interface AjaxFileOptions {
/** 响应数据类型:binary(ArrayBuffer)/ xml(Document)/ json / 纯文本(默认) */
type?: string;
/** 请求方法,默认 GET */
method?: string;
/** 成功回调,入参为按 type 解析后的数据 */
onSuccess?: (data: any) => void;
/** 失败回调 */
onError?: (xhr: XMLHttpRequest, status: number) => void;
/** 参数集合,GET 时拼接为 query 串 */
params?: Record<string, unknown>;
/** 请求地址(GET 带 params 时会被就地追加 query 串) */
url: string;
}
/** 携带旧浏览器二进制响应字段 responseBlob 的 XHR 形状 */
interface XhrWithResponseBlob extends XMLHttpRequest {
/** 旧实现(IE 系)的二进制响应字段 */
responseBlob?: any;
}
/**
* ajax获取数据
*/
function ajaxFile(options: AjaxFileOptions): void {
const xhr: XhrWithResponseBlob = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
const status = xhr.status;
if ((status >= 200 && status < 300) || status === 304) {
if (options.onSuccess) {
if (options.type === 'binary') {
const buffer = xhr.responseBlob || xhr.response;
options.onSuccess(buffer);
} else if (options.type === 'xml') {
options.onSuccess(xhr.responseXML);
} else if (options.type === 'json') {
options.onSuccess(JSON.parse(xhr.responseText));
} else {
options.onSuccess(xhr.responseText);
}
}
} else if (options.onError) {
options.onError(xhr, xhr.status);
}
}
};
const method = (options.method || 'GET').toUpperCase();
let params: string | null = null;
if (options.params) {
const str: string[] = [];
Object.keys(options.params).forEach(function (key) {
str.push(key + '=' + encodeURIComponent(String(options.params![key])));
});
const query = str.join('&');
if (method === 'GET') {
options.url += (options.url.indexOf('?') === -1 ? '?' : '&') + query;
} else {
params = query;
}
}
xhr.open(method, options.url, true);
if (options.type === 'binary') {
xhr.responseType = 'arraybuffer';
}
xhr.send(params);
}
/**
* 加载文件,默认以二进制方式返回
*/
function loadFile(url: string, type: string = 'binary'): Promise<any> {
return new Promise(function (resolve, reject) {
ajaxFile({
type: type,
url: url,
onSuccess: function (buffer) {
resolve(buffer);
},
onError: function (e) {
reject(e);
}
});
});
}
export default ajaxFile;
export { loadFile };

View File

@ -0,0 +1,13 @@
/**
* 通用工具函数(common/lang.js 的类型声明)
*/
/**
* 将 thatObj 的指定字段覆写到 thisObj 上
*/
export function overwrite(
thisObj: object,
thatObj: object,
/** 需要覆写的字段名列表;未指定则仅覆写 thisObj 自身可枚举的字段 */
fields?: string[]
): void;

View File

@ -1,234 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clone = clone;
exports.curry = curry;
exports.debounce = debounce;
exports.equals = equals;
exports.generic = generic;
exports.isArray = isArray;
exports.isDate = isDate;
exports.isEmptyObject = isEmptyObject;
exports.isFunction = isFunction;
exports.isObject = isObject;
exports.isString = isString;
exports.overwrite = overwrite;
exports.throttle = throttle;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
/**
* @file 语言相关函数
* @author mengke01(kekee000@gmail.com)
*/
function isArray(obj) {
return obj != null && toString.call(obj).slice(8, -1) === 'Array';
}
function isObject(obj) {
return obj != null && toString.call(obj).slice(8, -1) === 'Object';
}
function isString(obj) {
return obj != null && toString.call(obj).slice(8, -1) === 'String';
}
function isFunction(obj) {
return obj != null && toString.call(obj).slice(8, -1) === 'Function';
}
function isDate(obj) {
return obj != null && toString.call(obj).slice(8, -1) === 'Date';
}
function isEmptyObject(object) {
for (var name in object) {
// eslint-disable-next-line no-prototype-builtins
if (object.hasOwnProperty(name)) {
return false;
}
}
return true;
}
/**
* 为函数提前绑定前置参数(柯里化)
*
* @see http://en.wikipedia.org/wiki/Currying
* @param {Function} fn 要绑定的函数
* @param {...Array} cargs cargs
* @return {Function}
*/
function curry(fn) {
for (var _len = arguments.length, cargs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
cargs[_key - 1] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, rargs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
rargs[_key2] = arguments[_key2];
}
var args = cargs.concat(rargs);
// eslint-disable-next-line no-invalid-this
return fn.apply(this, args);
};
}
/**
* 方法静态化, 反绑定、延迟绑定
*
* @param {Function} method 待静态化的方法
* @return {Function} 静态化包装后方法
*/
function generic(method) {
return function () {
for (var _len3 = arguments.length, fargs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
fargs[_key3] = arguments[_key3];
}
return Function.call.apply(method, fargs);
};
}
/**
* 设置覆盖相关的属性值
*
* @param {Object} thisObj 覆盖对象
* @param {Object} thatObj 值对象
* @param {Array.<string>} fields 字段
* @return {Object} thisObj
*/
function overwrite(thisObj, thatObj, fields) {
if (!thatObj) {
return thisObj;
}
// 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制
fields = fields || Object.keys(thatObj);
fields.forEach(function (field) {
// 拷贝对象
if (thisObj[field] && _typeof(thisObj[field]) === 'object' && thatObj[field] && _typeof(thatObj[field]) === 'object') {
overwrite(thisObj[field], thatObj[field]);
} else {
thisObj[field] = thatObj[field];
}
});
return thisObj;
}
/**
* 深复制对象,仅复制数据
*
* @param {Object} source 源数据
* @return {Object} 复制的数据
*/
function clone(source) {
if (!source || _typeof(source) !== 'object') {
return source;
}
var cloned = source;
if (isArray(source)) {
cloned = source.slice().map(clone);
} else if (isObject(source) && 'isPrototypeOf' in source) {
cloned = {};
for (var _i = 0, _Object$keys = Object.keys(source); _i < _Object$keys.length; _i++) {
var key = _Object$keys[_i];
cloned[key] = clone(source[key]);
}
}
return cloned;
}
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
// @see underscore.js
function throttle(func, wait) {
var context;
var args;
var timeout;
var result;
var previous = 0;
var later = function later() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function () {
var now = new Date();
var remaining = wait - (now - previous);
// eslint-disable-next-line no-invalid-this
context = this;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
// @see underscore.js
function debounce(func, wait, immediate) {
var timeout;
var result;
return function () {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
// eslint-disable-next-line no-invalid-this
var context = this;
var later = function later() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
}
/**
* 判断两个对象的字段是否相等
*
* @param {Object} thisObj 要比较的对象
* @param {Object} thatObj 参考对象
* @param {Array} fields 指定字段
* @return {boolean} 是否相等
*/
function equals(thisObj, thatObj, fields) {
if (thisObj === thatObj) {
return true;
}
if (thisObj == null && thatObj == null) {
return true;
}
if (thisObj == null && thatObj != null || thisObj != null && thatObj == null) {
return false;
}
// 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制
fields = fields || (_typeof(thisObj) === 'object' ? Object.keys(thisObj) : []);
if (!fields.length) {
return thisObj === thatObj;
}
var equal = true;
for (var i = 0, l = fields.length, field; equal && i < l; i++) {
field = fields[i];
if (thisObj[field] && _typeof(thisObj[field]) === 'object' && thatObj[field] && _typeof(thatObj[field]) === 'object') {
equal = equal && equals(thisObj[field], thatObj[field]);
} else {
equal = equal && thisObj[field] === thatObj[field];
}
}
return equal;
}

View File

@ -0,0 +1,221 @@
/**
* @file 语言相关函数
* @author mengke01(kekee000@gmail.com)
*/
/**
* 判断是否为数组
*/
export function isArray(obj: unknown): boolean {
return obj != null && Object.prototype.toString.call(obj).slice(8, -1) === 'Array';
}
/**
* 判断是否为普通对象
*/
export function isObject(obj: unknown): boolean {
return obj != null && Object.prototype.toString.call(obj).slice(8, -1) === 'Object';
}
/**
* 判断是否为字符串
*/
export function isString(obj: unknown): boolean {
return obj != null && Object.prototype.toString.call(obj).slice(8, -1) === 'String';
}
/**
* 判断是否为函数
*/
export function isFunction(obj: unknown): boolean {
return obj != null && Object.prototype.toString.call(obj).slice(8, -1) === 'Function';
}
/**
* 判断是否为日期对象
*/
export function isDate(obj: unknown): boolean {
return obj != null && Object.prototype.toString.call(obj).slice(8, -1) === 'Date';
}
/**
* 判断是否为空对象(无可枚举自有属性)
*/
export function isEmptyObject(object: object): boolean {
for (const name in object) {
// eslint-disable-next-line no-prototype-builtins
if (object.hasOwnProperty(name)) {
return false;
}
}
return true;
}
/**
* 为函数提前绑定前置参数(柯里化)
*
* @see http://en.wikipedia.org/wiki/Currying
*/
export function curry(fn: (...args: any[]) => any, ...cargs: any[]): (...args: any[]) => any {
return function (this: unknown, ...rargs: any[]) {
const args = cargs.concat(rargs);
// eslint-disable-next-line no-invalid-this
return fn.apply(this, args);
};
}
/**
* 方法静态化, 反绑定、延迟绑定
*/
export function generic(method: (...args: any[]) => any): (...args: any[]) => any {
return function (...fargs: any[]) {
// 等价于 Function.call.apply(method, fargs):以 fargs[0] 为 this、其余为参数反绑定调用
const [thisArg, ...rest] = fargs;
return method.apply(thisArg, rest);
};
}
/**
* 设置覆盖相关的属性值,嵌套对象递归覆写
*/
export function overwrite(thisObj: any, thatObj: any, fields?: string[]): any {
if (!thatObj) {
return thisObj;
}
// 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制
fields = fields || Object.keys(thatObj);
fields.forEach(function (field) {
// 拷贝对象
if (
thisObj[field] &&
typeof thisObj[field] === 'object' &&
thatObj[field] &&
typeof thatObj[field] === 'object'
) {
overwrite(thisObj[field], thatObj[field]);
} else {
thisObj[field] = thatObj[field];
}
});
return thisObj;
}
/**
* 深复制对象,仅复制数据
*/
export function clone(source: any): any {
if (!source || typeof source !== 'object') {
return source;
}
let cloned = source;
if (isArray(source)) {
cloned = source.slice().map(clone);
} else if (isObject(source) && 'isPrototypeOf' in source) {
cloned = {};
for (const key of Object.keys(source)) {
cloned[key] = clone(source[key]);
}
}
return cloned;
}
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
// @see underscore.js
export function throttle(func: (...args: any[]) => any, wait: number): (...args: any[]) => any {
let context: unknown;
let args: any[];
let timeout: ReturnType<typeof setTimeout> | undefined;
let result: any;
let previous = 0;
const later = function () {
previous = new Date().getTime();
timeout = undefined;
result = func.apply(context, args);
};
return function (this: unknown, ...rest: any[]) {
const now = new Date().getTime();
const remaining = wait - (now - previous);
// eslint-disable-next-line no-invalid-this
context = this;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = undefined;
previous = now;
args = rest;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
// @see underscore.js
export function debounce(
func: (...args: any[]) => any,
wait: number,
immediate?: boolean
): (...args: any[]) => any {
let timeout: ReturnType<typeof setTimeout> | undefined;
let result: any;
return function (this: unknown, ...args: any[]) {
// eslint-disable-next-line no-invalid-this
const context = this;
const later = function () {
timeout = undefined;
if (!immediate) {
result = func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
}
/**
* 判断两个对象的字段是否相等,嵌套对象递归比较
*/
export function equals(thisObj: any, thatObj: any, fields?: string[]): boolean {
if (thisObj === thatObj) {
return true;
}
if (thisObj == null && thatObj == null) {
return true;
}
if ((thisObj == null && thatObj != null) || (thisObj != null && thatObj == null)) {
return false;
}
// 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制
fields = fields || (typeof thisObj === 'object' ? Object.keys(thisObj) : []);
if (!fields.length) {
return thisObj === thatObj;
}
let equal = true;
let field: string;
for (let i = 0, l = fields.length; equal && i < l; i++) {
field = fields[i];
if (
thisObj[field] &&
typeof thisObj[field] === 'object' &&
thatObj[field] &&
typeof thatObj[field] === 'object'
) {
equal = equal && equals(thisObj[field], thatObj[field]);
} else {
equal = equal && thisObj[field] === thatObj[field];
}
}
return equal;
}

View File

@ -1,94 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 字符串相关的函数
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
/**
* HTML解码字符串
*
* @param {string} source 源字符串
* @return {string}
*/
decodeHTML: function decodeHTML(source) {
var str = String(source).replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
// 处理转义的中文和实体字符
return str.replace(/&#([\d]+);/g, function ($0, $1) {
return String.fromCodePoint(parseInt($1, 10));
});
},
/**
* HTML编码字符串
*
* @param {string} source 源字符串
* @return {string}
*/
encodeHTML: function encodeHTML(source) {
return String(source).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
},
/**
* 获取string字节长度
*
* @param {string} source 源字符串
* @return {number} 长度
*/
getLength: function getLength(source) {
// eslint-disable-next-line no-control-regex
return String(source).replace(/[^\x00-\xff]/g, '11').length;
},
/**
* 字符串格式化,支持如 ${xxx.xxx} 的语法
*
* @param {string} source 模板字符串
* @param {Object} data 数据
* @return {string} 格式化后字符串
*/
format: function format(source, data) {
return source.replace(/\$\{([\w.]+)\}/g, function ($0, $1) {
var ref = $1.split('.');
var refObject = data;
var level;
while (refObject != null && (level = ref.shift())) {
refObject = refObject[level];
}
return refObject != null ? refObject : '';
});
},
/**
* 使用指定字符填充字符串,默认`0`
*
* @param {string} str 字符串
* @param {number} size 填充到的大小
* @param {string=} ch 填充字符
* @return {string} 字符串
*/
pad: function pad(str, size, ch) {
str = String(str);
if (str.length > size) {
return str.slice(str.length - size);
}
return new Array(size - str.length + 1).join(ch || '0') + str;
},
/**
* 获取字符串哈希编码
*
* @param {string} str 字符串
* @return {number} 哈希值
*/
hashcode: function hashcode(str) {
if (!str) {
return 0;
}
var hash = 0;
for (var i = 0, l = str.length; i < l; i++) {
hash = 0x7FFFFFFFF & hash * 31 + str.charCodeAt(i);
}
return hash;
}
};

View File

@ -0,0 +1,85 @@
/**
* @file 字符串相关的函数
* @author mengke01(kekee000@gmail.com)
*/
/** 字符串工具集合 */
const string = {
/**
* HTML解码字符串
*/
decodeHTML(source: string): string {
const str = String(source)
.replace(/&quot;/g, '"')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
// 处理转义的中文和实体字符
return str.replace(/&#([\d]+);/g, function (_, $1) {
return String.fromCodePoint(parseInt($1, 10));
});
},
/**
* HTML编码字符串
*/
encodeHTML(source: string): string {
return String(source)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
},
/**
* 获取string字节长度(非 ASCII 字符按 2 计)
*/
getLength(source: string): number {
// eslint-disable-next-line no-control-regex
return String(source).replace(/[^\x00-\xff]/g, '11').length;
},
/**
* 字符串格式化,支持如 ${xxx.xxx} 的语法
*/
format(source: string, data: any): string {
return source.replace(/\$\{([\w.]+)\}/g, function (_, $1) {
const ref = $1.split('.');
let refObject: any = data;
let level: string | undefined;
while (refObject != null && (level = ref.shift())) {
refObject = refObject[level];
}
return refObject != null ? refObject : '';
});
},
/**
* 使用指定字符填充字符串,默认`0`;超长时从左侧截断到指定长度
*/
pad(str: string, size: number, ch?: string): string {
str = String(str);
if (str.length > size) {
return str.slice(str.length - size);
}
return new Array(size - str.length + 1).join(ch || '0') + str;
},
/**
* 获取字符串哈希编码
*/
hashcode(str: string): number {
if (!str) {
return 0;
}
let hash = 0;
for (let i = 0, l = str.length; i < l; i++) {
hash = 0x7ffffffff & hash * 31 + str.charCodeAt(i);
}
return hash;
}
};
export default string;

View File

@ -0,0 +1,31 @@
/**
* 包围盒计算(graphics/computeBoundingBox.js 的类型声明)
*/
/** 包围盒 */
export interface BoundBox {
/** 水平最小值 */
x: number;
/** 垂直最小值 */
y: number;
/** 宽度 */
width: number;
/** 高度 */
height: number;
}
/**
* 计算轮廓点边界;轮廓为空时运行时返回 false(调用方需保证传入非空轮廓)
*/
export function computePath(
/** 支持多个轮廓 */
...contours: object[][]
): BoundBox;
/**
* 计算曲线点边界(内联展开版,避免中间对象分配)
*/
export function computePathBox(
/** 支持多个轮廓 */
...contours: object[][]
): BoundBox;

View File

@ -1,13 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.computePath = exports.computeBounding = void 0;
exports.computePathBox = computePathBox;
exports.quadraticBezier = void 0;
var _pathIterator = _interopRequireDefault(require("./pathIterator"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 计算曲线包围盒
* @author mengke01(kekee000@gmail.com)
@ -16,24 +6,47 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
* zrender
* https://github.com/ecomfe/zrender/blob/master/src/tool/computeBoundingBox.js
*/
import pathIterator from "./pathIterator";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 包围盒 */
export interface BoundBox {
/** 水平最小值 */
x: number;
/** 垂直最小值 */
y: number;
/** 宽度 */
width: number;
/** 高度 */
height: number;
}
/**
* 计算包围盒
*
* @param {Array} points 点集
* @return {Object} bounding box
*/
function computeBoundingBox(points) {
export function computeBoundingBox(
/** 点集 */
points: PathPoint[]
): BoundBox | false {
if (points.length === 0) {
return false;
}
var p0 = points[0];
var left = p0.x;
var right = p0.x;
var top = p0.y;
var bottom = p0.y;
for (var i = 1; i < points.length; i++) {
var p = points[i];
const p0 = points[0];
let left = p0.x;
let right = p0.x;
let top = p0.y;
let bottom = p0.y;
for (let i = 1; i < points.length; i++) {
const p = points[i];
if (p.x < left) {
left = p.x;
}
@ -58,17 +71,19 @@ function computeBoundingBox(points) {
/**
* 计算二阶贝塞尔曲线的包围盒
* http://pissang.net/blog/?p=91
*
* @param {Object} p0 p0
* @param {Object} p1 p1
* @param {Object} p2 p2
* @return {Object} bound对象
*/
function computeQuadraticBezierBoundingBox(p0, p1, p2) {
function computeQuadraticBezierBoundingBox(
/** p0 */
p0: PathPoint,
/** p1 */
p1: PathPoint,
/** p2 */
p2: PathPoint
): BoundBox | false {
// Find extremities, where derivative in x dim or y dim is zero
var tmp = p0.x + p2.x - 2 * p1.x;
let tmp = p0.x + p2.x - 2 * p1.x;
// p1 is center of p0 and p2 in x dim
var t1;
let t1: number;
if (tmp === 0) {
t1 = 0.5;
} else {
@ -76,7 +91,7 @@ function computeQuadraticBezierBoundingBox(p0, p1, p2) {
}
tmp = p0.y + p2.y - 2 * p1.y;
// p1 is center of p0 and p2 in y dim
var t2;
let t2: number;
if (tmp === 0) {
t2 = 0.5;
} else {
@ -84,12 +99,12 @@ function computeQuadraticBezierBoundingBox(p0, p1, p2) {
}
t1 = Math.max(Math.min(t1, 1), 0);
t2 = Math.max(Math.min(t2, 1), 0);
var ct1 = 1 - t1;
var ct2 = 1 - t2;
var x1 = ct1 * ct1 * p0.x + 2 * ct1 * t1 * p1.x + t1 * t1 * p2.x;
var y1 = ct1 * ct1 * p0.y + 2 * ct1 * t1 * p1.y + t1 * t1 * p2.y;
var x2 = ct2 * ct2 * p0.x + 2 * ct2 * t2 * p1.x + t2 * t2 * p2.x;
var y2 = ct2 * ct2 * p0.y + 2 * ct2 * t2 * p1.y + t2 * t2 * p2.y;
const ct1 = 1 - t1;
const ct2 = 1 - t2;
const x1 = ct1 * ct1 * p0.x + 2 * ct1 * t1 * p1.x + t1 * t1 * p2.x;
const y1 = ct1 * ct1 * p0.y + 2 * ct1 * t1 * p1.y + t1 * t1 * p2.y;
const x2 = ct2 * ct2 * p0.x + 2 * ct2 * t2 * p1.x + t2 * t2 * p2.x;
const y2 = ct2 * ct2 * p0.y + 2 * ct2 * t2 * p1.y + t2 * t2 * p2.y;
return computeBoundingBox([p0, p2, {
x: x1,
y: y1
@ -100,21 +115,25 @@ function computeQuadraticBezierBoundingBox(p0, p1, p2) {
}
/**
* 计算曲线包围盒
*
* @private
* @param {...Array} args 坐标点集, 支持多个path
* @return {Object} {x, y, width, height}
*/
/**
* 优化: 内联展开 computePathBoundingBox,消除中间 points 数组和临时对象分配
* 计算曲线点边界(内联展开版,消除中间 points 数组和临时对象分配)
* 直接在遍历过程中维护 left/right/top/bottom 四个边界值
*/
function computePathBoundingBox() {
var left, right, top, bottom;
var found = false;
function computePathBoundingBox(
/** 坐标点集,支持多个path */
...contours: PathPoint[][]
): BoundBox | false {
let left = 0;
let right = 0;
let top = 0;
let bottom = 0;
let found = false;
function updateBounds(x, y) {
function updateBounds(
/** 水平坐标 */
x: number,
/** 垂直坐标 */
y: number
): void {
if (!found) {
left = right = x;
top = bottom = y;
@ -127,16 +146,16 @@ function computePathBoundingBox() {
}
}
function updateBoundsQ(p0, p1, p2) {
function updateBoundsQ(p0: PathPoint, p1: PathPoint, p2: PathPoint): void {
/* 内联二次贝塞尔包围盒计算,避免创建中间对象 */
var tmp = p0.x + p2.x - 2 * p1.x;
var t1 = tmp === 0 ? 0.5 : (p0.x - p1.x) / tmp;
let tmp = p0.x + p2.x - 2 * p1.x;
let t1 = tmp === 0 ? 0.5 : (p0.x - p1.x) / tmp;
tmp = p0.y + p2.y - 2 * p1.y;
var t2 = tmp === 0 ? 0.5 : (p0.y - p1.y) / tmp;
let t2 = tmp === 0 ? 0.5 : (p0.y - p1.y) / tmp;
t1 = t1 < 0 ? 0 : t1 > 1 ? 1 : t1;
t2 = t2 < 0 ? 0 : t2 > 1 ? 1 : t2;
var ct1 = 1 - t1;
var ct2 = 1 - t2;
const ct1 = 1 - t1;
const ct2 = 1 - t2;
/* 计算 4 个极值点: p0, p2, (t1), (t2) */
updateBounds(p0.x, p0.y);
updateBounds(p2.x, p2.y);
@ -146,23 +165,19 @@ function computePathBoundingBox() {
ct2 * ct2 * p0.y + 2 * ct2 * t2 * p1.y + t2 * t2 * p2.y);
}
function processContour(contour) {
(0, _pathIterator.default)(contour, function (c, p0, p1, p2) {
if (c === 'L') {
function processContour(contour: PathPoint[]): void {
pathIterator(contour, (c, p0, p1, p2) => {
if (c === "L") {
updateBounds(p0.x, p0.y);
updateBounds(p1.x, p1.y);
} else if (c === 'Q') {
} else if (c === "Q" && typeof p2 !== "number") {
updateBoundsQ(p0, p1, p2);
}
});
}
if (arguments.length === 1) {
processContour(arguments[0]);
} else {
for (var i = 0, l = arguments.length; i < l; i++) {
processContour(arguments[i]);
}
for (const contour of contours) {
processContour(contour);
}
if (!found) {
@ -178,21 +193,21 @@ function computePathBoundingBox() {
/**
* 计算曲线点边界(内联展开版,避免中间对象分配)
*
* @private
* @param {...Array} args path对象, 支持多个path
* @return {Object} {x, y, width, height}
*/
function computePathBox() {
var left, right, top, bottom;
var found = false;
export function computePathBox(
/** path对象,支持多个path */
...contours: (PathPoint[] | undefined | null)[]
): BoundBox {
let left = 0;
let right = 0;
let top = 0;
let bottom = 0;
let found = false;
for (var a = 0; a < arguments.length; a++) {
var contour = arguments[a];
for (const contour of contours) {
if (!contour || !contour.length) continue;
for (var i = 0, l = contour.length; i < l; i++) {
var p = contour[i];
for (const p of contour) {
if (!found) {
left = right = p.x;
top = bottom = p.y;
@ -216,6 +231,7 @@ function computePathBox() {
height: bottom - top
};
}
var computeBounding = exports.computeBounding = computeBoundingBox;
var quadraticBezier = exports.quadraticBezier = computeQuadraticBezierBoundingBox;
var computePath = exports.computePath = computePathBoundingBox;
export { computeQuadraticBezierBoundingBox as quadraticBezier };
export { computePathBoundingBox as computePath };
export { computeBoundingBox as computeBounding };

View File

@ -1,223 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getArc;
var _bezierCubic2Q = _interopRequireDefault(require("../math/bezierCubic2Q2"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 使用插值法获取椭圆弧度,以支持svg arc命令
* @author mengke01(kekee000@gmail.com)
*
* modify from:
* https://github.com/fontello/svgpath/blob/master/lib/a2c.js
* references:
* http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
*/
var TAU = Math.PI * 2;
function vectorAngle(ux, uy, vx, vy) {
// Calculate an angle between two vectors
var sign = ux * vy - uy * vx < 0 ? -1 : 1;
var umag = Math.sqrt(ux * ux + uy * uy);
var vmag = Math.sqrt(ux * ux + uy * uy);
var dot = ux * vx + uy * vy;
var div = dot / (umag * vmag);
if (div > 1 || div < -1) {
// rounding errors, e.g. -1.0000000000000002 can screw up this
div = Math.max(div, -1);
div = Math.min(div, 1);
}
return sign * Math.acos(div);
}
function correctRadii(midx, midy, rx, ry) {
// Correction of out-of-range radii
rx = Math.abs(rx);
ry = Math.abs(ry);
var Λ = midx * midx / (rx * rx) + midy * midy / (ry * ry);
if (Λ > 1) {
rx *= Math.sqrt(Λ);
ry *= Math.sqrt(Λ);
}
return [rx, ry];
}
function getArcCenter(x1, y1, x2, y2, fa, fs, rx, ry, sin_φ, cos_φ) {
// Convert from endpoint to center parameterization,
// see http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// Step 1.
//
// Moving an ellipse so origin will be the middlepoint between our two
// points. After that, rotate it to line up ellipse axes with coordinate
// axes.
//
var x1p = cos_φ * (x1 - x2) / 2 + sin_φ * (y1 - y2) / 2;
var y1p = -sin_φ * (x1 - x2) / 2 + cos_φ * (y1 - y2) / 2;
var rx_sq = rx * rx;
var ry_sq = ry * ry;
var x1p_sq = x1p * x1p;
var y1p_sq = y1p * y1p;
// Step 2.
//
// Compute coordinates of the centre of this ellipse (cx', cy')
// in the new coordinate system.
//
var radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
if (radicant < 0) {
// due to rounding errors it might be e.g. -1.3877787807814457e-17
radicant = 0;
}
radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1);
var cxp = radicant * rx / ry * y1p;
var cyp = radicant * -ry / rx * x1p;
// Step 3.
//
// Transform back to get centre coordinates (cx, cy) in the original
// coordinate system.
//
var cx = cos_φ * cxp - sin_φ * cyp + (x1 + x2) / 2;
var cy = sin_φ * cxp + cos_φ * cyp + (y1 + y2) / 2;
// Step 4.
//
// Compute angles (θ1, Δθ).
//
var v1x = (x1p - cxp) / rx;
var v1y = (y1p - cyp) / ry;
var v2x = (-x1p - cxp) / rx;
var v2y = (-y1p - cyp) / ry;
var θ1 = vectorAngle(1, 0, v1x, v1y);
var Δθ = vectorAngle(v1x, v1y, v2x, v2y);
if (fs === 0 && Δθ > 0) {
Δθ -= TAU;
}
if (fs === 1 && Δθ < 0) {
Δθ += TAU;
}
return [cx, cy, θ1, Δθ];
}
function approximateUnitArc(θ1, Δθ) {
// Approximate one unit arc segment with bézier curves,
// see http://math.stackexchange.com/questions/873224/
// calculate-control-points-of-cubic-bezier-curve-approximating-a-part-of-a-circle
var α = 4 / 3 * Math.tan(Δθ / 4);
var x1 = Math.cos(θ1);
var y1 = Math.sin(θ1);
var x2 = Math.cos(θ1 + Δθ);
var y2 = Math.sin(θ1 + Δθ);
return [x1, y1, x1 - y1 * α, y1 + x1 * α, x2 + y2 * α, y2 - x2 * α, x2, y2];
}
function a2c(x1, y1, x2, y2, fa, fs, rx, ry, φ) {
var sin_φ = Math.sin(φ * TAU / 360);
var cos_φ = Math.cos(φ * TAU / 360);
// Make sure radii are valid
//
var x1p = cos_φ * (x1 - x2) / 2 + sin_φ * (y1 - y2) / 2;
var y1p = -sin_φ * (x1 - x2) / 2 + cos_φ * (y1 - y2) / 2;
if (x1p === 0 && y1p === 0) {
// we're asked to draw line to itself
return [];
}
if (rx === 0 || ry === 0) {
// one of the radii is zero
return [];
}
var radii = correctRadii(x1p, y1p, rx, ry);
rx = radii[0];
ry = radii[1];
// Get center parameters (cx, cy, θ1, Δθ)
//
var cc = getArcCenter(x1, y1, x2, y2, fa, fs, rx, ry, sin_φ, cos_φ);
var result = [];
var θ1 = cc[2];
var Δθ = cc[3];
// Split an arc to multiple segments, so each segment
// will be less than τ/4 (= 90°)
//
var segments = Math.max(Math.ceil(Math.abs(Δθ) / (TAU / 4)), 1);
Δθ /= segments;
for (var i = 0; i < segments; i++) {
result.push(approximateUnitArc(θ1, Δθ));
θ1 += Δθ;
}
// We have a bezier approximation of a unit circle,
// now need to transform back to the original ellipse
//
return result.map(function (curve) {
for (var _i = 0; _i < curve.length; _i += 2) {
var x = curve[_i + 0];
var y = curve[_i + 1];
// scale
x *= rx;
y *= ry;
// rotate
var xp = cos_φ * x - sin_φ * y;
var yp = sin_φ * x + cos_φ * y;
// translate
curve[_i + 0] = xp + cc[0];
curve[_i + 1] = yp + cc[1];
}
return curve;
});
}
/**
* 获取椭圆弧度
*
* @param {number} rx 椭圆长半轴
* @param {number} ry 椭圆短半轴
* @param {number} angle 旋转角度
* @param {number} largeArc 是否大圆弧
* @param {number} sweep 是否延伸圆弧
* @param {Object} p0 分割点1
* @param {Object} p1 分割点2
* @return {Array} 分割后的路径
*/
function getArc(rx, ry, angle, largeArc, sweep, p0, p1) {
var result = a2c(p0.x, p0.y, p1.x, p1.y, largeArc, sweep, rx, ry, angle);
var path = [];
if (result.length) {
path.push({
x: result[0][0],
y: result[0][1],
onCurve: true
});
// 将三次曲线转换成二次曲线
result.forEach(function (c) {
var q2Array = (0, _bezierCubic2Q.default)({
x: c[0],
y: c[1]
}, {
x: c[2],
y: c[3]
}, {
x: c[4],
y: c[5]
}, {
x: c[6],
y: c[7]
});
q2Array[0][2].onCurve = true;
path.push(q2Array[0][1]);
path.push(q2Array[0][2]);
if (q2Array[1]) {
q2Array[1][2].onCurve = true;
path.push(q2Array[1][1]);
path.push(q2Array[1][2]);
}
});
}
return path;
}

View File

@ -0,0 +1,237 @@
/**
* @file 使用插值法获取椭圆弧度,以支持svg arc命令
* @author mengke01(kekee000@gmail.com)
*
* modify from:
* https://github.com/fontello/svgpath/blob/master/lib/a2c.js
* references:
* http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
*/
import bezierCubic2Q2 from "../math/bezierCubic2Q2";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
const TAU = Math.PI * 2;
function vectorAngle(ux: number, uy: number, vx: number, vy: number): number {
// Calculate an angle between two vectors
const sign = ux * vy - uy * vx < 0 ? -1 : 1;
const umag = Math.sqrt(ux * ux + uy * uy);
const vmag = Math.sqrt(ux * ux + uy * uy);
const dot = ux * vx + uy * vy;
let div = dot / (umag * vmag);
if (div > 1 || div < -1) {
// rounding errors, e.g. -1.0000000000000002 can screw up this
div = Math.max(div, -1);
div = Math.min(div, 1);
}
return sign * Math.acos(div);
}
function correctRadii(midx: number, midy: number, rx: number, ry: number): number[] {
// Correction of out-of-range radii
rx = Math.abs(rx);
ry = Math.abs(ry);
const Λ = midx * midx / (rx * rx) + midy * midy / (ry * ry);
if (Λ > 1) {
rx *= Math.sqrt(Λ);
ry *= Math.sqrt(Λ);
}
return [rx, ry];
}
function getArcCenter(x1: number, y1: number, x2: number, y2: number, fa: number, fs: number, rx: number, ry: number, sin_φ: number, cos_φ: number): number[] {
// Convert from endpoint to center parameterization,
// see http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// Step 1.
//
// Moving an ellipse so origin will be the middlepoint between our two
// points. After that, rotate to line up ellipse axes with coordinate
// axes.
//
const x1p = cos_φ * (x1 - x2) / 2 + sin_φ * (y1 - y2) / 2;
const y1p = -sin_φ * (x1 - x2) / 2 + cos_φ * (y1 - y2) / 2;
const rx_sq = rx * rx;
const ry_sq = ry * ry;
const x1p_sq = x1p * x1p;
const y1p_sq = y1p * y1p;
// Step 2.
//
// Compute coordinates of the centre of this ellipse (cx', cy')
// in the new coordinate system.
//
let radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
if (radicant < 0) {
// due to rounding errors it might be e.g. -1.3877787807814457e-17
radicant = 0;
}
radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1);
const cxp = radicant * rx / ry * y1p;
const cyp = radicant * -ry / rx * x1p;
// Step 3.
//
// Transform back to get centre coordinates (cx, cy) in the original
// coordinate system.
//
const cx = cos_φ * cxp - sin_φ * cyp + (x1 + x2) / 2;
const cy = sin_φ * cxp + cos_φ * cyp + (y1 + y2) / 2;
// Step 4.
//
// Compute angles (θ1, Δθ).
//
const v1x = (x1p - cxp) / rx;
const v1y = (y1p - cyp) / ry;
const v2x = (-x1p - cxp) / rx;
const v2y = (-y1p - cyp) / ry;
const θ1 = vectorAngle(1, 0, v1x, v1y);
let Δθ = vectorAngle(v1x, v1y, v2x, v2y);
if (fs === 0 && Δθ > 0) {
Δθ -= TAU;
}
if (fs === 1 && Δθ < 0) {
Δθ += TAU;
}
return [cx, cy, θ1, Δθ];
}
function approximateUnitArc(θ1: number, Δθ: number): number[] {
// Approximate one unit arc segment with bézier curves,
// see http://math.stackexchange.com/questions/873224/
// calculate-control-points-of-cubic-bezier-curve-approximating-a-part-of-a-circle
const α = 4 / 3 * Math.tan(Δθ / 4);
const x1 = Math.cos(θ1);
const y1 = Math.sin(θ1);
const x2 = Math.cos(θ1 + Δθ);
const y2 = Math.sin(θ1 + Δθ);
return [x1, y1, x1 - y1 * α, y1 + x1 * α, x2 + y2 * α, y2 - x2 * α, x2, y2];
}
function a2c(x1: number, y1: number, x2: number, y2: number, fa: number, fs: number, rx: number, ry: number, φ: number): number[][] {
const sin_φ = Math.sin(φ * TAU / 360);
const cos_φ = Math.cos(φ * TAU / 360);
// Make sure radii are valid
//
const x1p = cos_φ * (x1 - x2) / 2 + sin_φ * (y1 - y2) / 2;
const y1p = -sin_φ * (x1 - x2) / 2 + cos_φ * (y1 - y2) / 2;
if (x1p === 0 && y1p === 0) {
// we're asked to draw line to itself
return [];
}
if (rx === 0 || ry === 0) {
// one of the radii is zero
return [];
}
const radii = correctRadii(x1p, y1p, rx, ry);
rx = radii[0];
ry = radii[1];
// Get center parameters (cx, cy, θ1, Δθ)
//
const cc = getArcCenter(x1, y1, x2, y2, fa, fs, rx, ry, sin_φ, cos_φ);
const result: number[][] = [];
let θ1 = cc[2];
let Δθ = cc[3];
// Split an arc to multiple segments, so each segment
// will be less than τ/4 (= 90°)
//
const segments = Math.max(Math.ceil(Math.abs(Δθ) / (TAU / 4)), 1);
Δθ /= segments;
for (let i = 0; i < segments; i++) {
result.push(approximateUnitArc(θ1, Δθ));
θ1 += Δθ;
}
// We have a bezier approximation of a unit circle,
// now need to transform back to the original ellipse
//
return result.map((curve) => {
for (let i = 0; i < curve.length; i += 2) {
let x = curve[i + 0];
let y = curve[i + 1];
// scale
x *= rx;
y *= ry;
// rotate
const xp = cos_φ * x - sin_φ * y;
const yp = sin_φ * x + cos_φ * y;
// translate
curve[i + 0] = xp + cc[0];
curve[i + 1] = yp + cc[1];
}
return curve;
});
}
/**
* 获取椭圆弧度
*/
export default function getArc(
/** 椭圆长半轴 */
rx: number,
/** 椭圆短半轴 */
ry: number,
/** 旋转角度 */
angle: number,
/** 是否大圆弧 */
largeArc: number,
/** 是否延伸圆弧 */
sweep: number,
/** 分割点1 */
p0: PathPoint,
/** 分割点2 */
p1: PathPoint
): PathPoint[] {
const result = a2c(p0.x, p0.y, p1.x, p1.y, largeArc, sweep, rx, ry, angle);
const path: PathPoint[] = [];
if (result.length) {
path.push({
x: result[0][0],
y: result[0][1],
onCurve: true
});
// 将三次曲线转换成二次曲线
result.forEach((c) => {
const q2Array = bezierCubic2Q2({
x: c[0],
y: c[1]
}, {
x: c[2],
y: c[3]
}, {
x: c[4],
y: c[5]
}, {
x: c[6],
y: c[7]
});
q2Array[0][2].onCurve = true;
path.push(q2Array[0][1]);
path.push(q2Array[0][2]);
if (q2Array[1]) {
q2Array[1][2].onCurve = true;
path.push(q2Array[1][1]);
path.push(q2Array[1][2]);
}
});
}
return path;
}

View File

@ -1,25 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mul = mul;
exports.multiply = multiply;
/**
* @file matrix变换操作
* @author mengke01(kekee000@gmail.com)
*/
/** 仿射矩阵(4 个旋转变换参数或 6 个旋转位移参数) */
type Matrix = number[];
/**
* 仿射矩阵相乘
*
* @param {Array=} matrix1 矩阵1
* @param {Array=} matrix2 矩阵2
* @return {Array} 新矩阵
*/
function mul() {
var matrix1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [1, 0, 0, 1];
var matrix2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [1, 0, 0, 1];
export function mul(
/** 矩阵1 */
matrix1: Matrix = [1, 0, 0, 1],
/** 矩阵2 */
matrix2: Matrix = [1, 0, 0, 1]
): Matrix {
// 旋转变换 4 个参数
if (matrix1.length === 4) {
return [matrix1[0] * matrix2[0] + matrix1[2] * matrix2[1], matrix1[1] * matrix2[0] + matrix1[3] * matrix2[1], matrix1[0] * matrix2[2] + matrix1[2] * matrix2[3], matrix1[1] * matrix2[2] + matrix1[3] * matrix2[3]];
@ -31,14 +26,14 @@ function mul() {
/**
* 多个仿射矩阵相乘
*
* @param {...Array} matrixs matrix array
* @return {Array} 新矩阵
*/
function multiply() {
var result = arguments.length <= 0 ? undefined : arguments[0];
for (var i = 1, matrix; matrix = i < 0 || arguments.length <= i ? undefined : arguments[i]; i++) {
result = mul(result, matrix);
export function multiply(
/** matrix array */
...matrixs: Matrix[]
): Matrix {
let result = matrixs[0];
for (let i = 1; i < matrixs.length; i++) {
result = mul(result, matrixs[i]);
}
return result;
}
}

View File

@ -1,14 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 圆路径集合,逆时针
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = [{
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
const circle: PathPoint[] = [{
x: 582,
y: 0
}, {
@ -56,4 +61,6 @@ var _default = exports.default = [{
}, {
x: 383,
y: 0
}];
}];
export default circle;

View File

@ -0,0 +1,17 @@
/**
* 路径坐标缩放和平移(graphics/pathAdjust.js 的类型声明)
*/
declare function pathAdjust(
/** 轮廓点数组 */
contour: object[],
/** x 缩放比例 */
scaleX?: number,
/** y 缩放比例 */
scaleY?: number,
/** x 偏移 */
offsetX?: number,
/** y 偏移 */
offsetY?: number
): object[];
export default pathAdjust;

View File

@ -1,35 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathAdjust;
/**
* @file 调整路径缩放和平移
* @author mengke01(kekee000@gmail.com)
*/
/**
* 对path坐标进行调整
*
* @param {Object} contour 坐标点
* @param {number} scaleX x缩放比例
* @param {number} scaleY y缩放比例
* @param {number} offsetX x偏移
* @param {number} offsetY y偏移
*
* @return {Object} contour 坐标点
*/
function pathAdjust(contour, scaleX, scaleY, offsetX, offsetY) {
scaleX = scaleX === undefined ? 1 : scaleX;
scaleY = scaleY === undefined ? 1 : scaleY;
var x = offsetX || 0;
var y = offsetY || 0;
var p;
for (var i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.x = scaleX * (p.x + x);
p.y = scaleY * (p.y + y);
}
return contour;
}

View File

@ -0,0 +1,42 @@
/**
* @file 调整路径缩放和平移
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* 对path坐标进行调整
*/
export default function pathAdjust(
/** 坐标点 */
contour: PathPoint[],
/** x缩放比例 */
scaleX?: number,
/** y缩放比例 */
scaleY?: number,
/** x偏移 */
offsetX?: number,
/** y偏移 */
offsetY?: number
): PathPoint[] {
scaleX = scaleX === undefined ? 1 : scaleX;
scaleY = scaleY === undefined ? 1 : scaleY;
const x = offsetX || 0;
const y = offsetY || 0;
let p: PathPoint;
for (let i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.x = scaleX * (p.x + x);
p.y = scaleY * (p.y + y);
}
return contour;
}

View File

@ -0,0 +1,11 @@
/**
* 路径坐标四舍五入(graphics/pathCeil.js 的类型声明)
*/
declare function pathCeil(
/** 轮廓点数组(对象格式或扁平格式 [x, y, onCurve, ...]) */
contour: object[],
/** 四舍五入的小数位数 */
point?: number
): object[];
export default pathCeil;

View File

@ -1,47 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathCeil;
/**
* @file 对路径进行四舍五入
* @author mengke01(kekee000@gmail.com)
*/
/**
* 对path坐标进行调整
*
* @param {Array} contour 轮廓点数组(对象格式或扁平格式 [x, y, onCurve, ...])
* @param {number} point 四舍五入的点数
* @return {Object} contour 坐标点
*/
function pathCeil(contour, point) {
if (!contour.length) {
return contour;
}
/* 优化66: 检测扁平格式 - 第一个元素是 number 则为扁平格式 */
if (typeof contour[0] === 'number') {
for (var i = 0, l = contour.length; i < l; i += 3) {
if (!point) {
contour[i] = Math.round(contour[i]);
contour[i + 1] = Math.round(contour[i + 1]);
} else {
contour[i] = Number(contour[i].toFixed(point));
contour[i + 1] = Number(contour[i + 1].toFixed(point));
}
}
} else {
for (var i = 0, l = contour.length; i < l; i++) {
var p = contour[i];
if (!point) {
p.x = Math.round(p.x);
p.y = Math.round(p.y);
} else {
p.x = Number(p.x.toFixed(point));
p.y = Number(p.y.toFixed(point));
}
}
}
return contour;
}

View File

@ -0,0 +1,61 @@
/**
* @file 对路径进行四舍五入
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 轮廓:对象格式或扁平格式 [x, y, onCurve, ...] */
type Contour = PathPoint[] | number[];
/**
* 检测扁平格式 - 第一个元素是 number 则为扁平格式(优化66)
*/
function isFlatContour(contour: Contour): contour is number[] {
return typeof contour[0] === "number";
}
/**
* 对path坐标进行调整
*/
export default function pathCeil(
/** 轮廓点数组(对象格式或扁平格式 [x, y, onCurve, ...]) */
contour: Contour,
/** 四舍五入的小数位数 */
point?: number
): Contour {
if (!contour.length) {
return contour;
}
/* 优化66: 检测扁平格式 */
if (isFlatContour(contour)) {
for (let i = 0, l = contour.length; i < l; i += 3) {
if (!point) {
contour[i] = Math.round(contour[i]);
contour[i + 1] = Math.round(contour[i + 1]);
} else {
contour[i] = Number(contour[i].toFixed(point));
contour[i + 1] = Number(contour[i + 1].toFixed(point));
}
}
} else {
for (const p of contour) {
if (!point) {
p.x = Math.round(p.x);
p.y = Math.round(p.y);
} else {
p.x = Number(p.x.toFixed(point));
p.y = Number(p.y.toFixed(point));
}
}
}
return contour;
}

View File

@ -1,70 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathIterator;
/**
* @file 遍历路径的路径集合,包括segment和 bezier curve
* @author mengke01(kekee000@gmail.com)
*/
/**
* 遍历路径的路径集合,包括segment和 bezier curve
*
* @param {Array} contour 坐标点集
* @param {Function} callBack 回调函数,参数集合:command, p0, p1, p2, i
* p0, p1, p2 直线或者贝塞尔曲线参数
* i 当前遍历的点
* 其中command = L 或者 Q,表示直线或者贝塞尔曲线
*/
function pathIterator(contour, callBack) {
var curPoint;
var prevPoint;
var nextPoint;
var cursorPoint; // cursorPoint 为当前单个绘制命令的起点
/* 优化: 复用临时对象,避免每次分配 */
var tmpPoint = { x: 0, y: 0 };
for (var i = 0, l = contour.length; i < l; i++) {
curPoint = contour[i];
prevPoint = i === 0 ? contour[l - 1] : contour[i - 1];
nextPoint = i === l - 1 ? contour[0] : contour[i + 1];
// 起始坐标
if (i === 0) {
if (curPoint.onCurve) {
cursorPoint = curPoint;
} else if (prevPoint.onCurve) {
cursorPoint = prevPoint;
} else {
tmpPoint.x = (prevPoint.x + curPoint.x) * 0.5;
tmpPoint.y = (prevPoint.y + curPoint.y) * 0.5;
cursorPoint = tmpPoint;
}
}
// 直线
if (curPoint.onCurve && nextPoint.onCurve) {
if (false === callBack('L', curPoint, nextPoint, 0, i)) {
break;
}
cursorPoint = nextPoint;
} else if (!curPoint.onCurve) {
if (nextPoint.onCurve) {
if (false === callBack('Q', cursorPoint, curPoint, nextPoint, i)) {
break;
}
cursorPoint = nextPoint;
} else {
tmpPoint.x = (curPoint.x + nextPoint.x) * 0.5;
tmpPoint.y = (curPoint.y + nextPoint.y) * 0.5;
if (false === callBack('Q', cursorPoint, curPoint, tmpPoint, i)) {
break;
}
cursorPoint = tmpPoint;
}
}
}
}

View File

@ -0,0 +1,92 @@
/**
* @file 遍历路径的路径集合,包括segment和 bezier curve
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* 遍历回调:command 为 L(直线)时 p2 恒为数字 0 占位;为 Q(二次贝塞尔)时 p2 为曲线终点
*/
type PathIteratorCallback = (
/** 命令类型 */
command: "L" | "Q",
/** 命令起点 */
p0: PathPoint,
/** 控制点(L 时为终点) */
p1: PathPoint,
/** 终点(L 时为数字 0) */
p2: PathPoint | number,
/** 当前遍历的点索引 */
i: number
) => boolean | void;
/**
* 遍历路径的路径集合,包括segment和 bezier curve
*/
function pathIterator(
/** 坐标点集 */
contour: PathPoint[],
/** 回调函数,返回 false 中断遍历 */
callBack: PathIteratorCallback
): void {
let curPoint: PathPoint;
let prevPoint: PathPoint;
let nextPoint: PathPoint;
/* 优化: 复用临时对象,避免每次分配 */
const tmpPoint = { x: 0, y: 0 };
// cursorPoint 为当前单个绘制命令的起点(首轮 i=0 必然重新赋值)
let cursorPoint: PathPoint = tmpPoint;
for (let i = 0, l = contour.length; i < l; i++) {
curPoint = contour[i];
prevPoint = i === 0 ? contour[l - 1] : contour[i - 1];
nextPoint = i === l - 1 ? contour[0] : contour[i + 1];
// 起始坐标
if (i === 0) {
if (curPoint.onCurve) {
cursorPoint = curPoint;
} else if (prevPoint.onCurve) {
cursorPoint = prevPoint;
} else {
tmpPoint.x = (prevPoint.x + curPoint.x) * 0.5;
tmpPoint.y = (prevPoint.y + curPoint.y) * 0.5;
cursorPoint = tmpPoint;
}
}
// 直线
if (curPoint.onCurve && nextPoint.onCurve) {
if (false === callBack("L", curPoint, nextPoint, 0, i)) {
break;
}
cursorPoint = nextPoint;
} else if (!curPoint.onCurve) {
if (nextPoint.onCurve) {
if (false === callBack("Q", cursorPoint, curPoint, nextPoint, i)) {
break;
}
cursorPoint = nextPoint;
} else {
tmpPoint.x = (curPoint.x + nextPoint.x) * 0.5;
tmpPoint.y = (curPoint.y + nextPoint.y) * 0.5;
if (false === callBack("Q", cursorPoint, curPoint, tmpPoint, i)) {
break;
}
cursorPoint = tmpPoint;
}
}
}
}
export default pathIterator;

View File

@ -1,42 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathRotate;
/**
* @file 路径旋转
* @author mengke01(kekee000@gmail.com)
*/
/**
* 对path坐标进行调整
*
* @param {Object} contour 坐标点
* @param {number} angle 角度
* @param {number} centerX x偏移
* @param {number} centerY y偏移
*
* @return {Object} contour 坐标点
*/
function pathRotate(contour, angle, centerX, centerY) {
angle = angle === undefined ? 0 : angle;
var x = centerX || 0;
var y = centerY || 0;
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var px;
var py;
var p;
// x1=cos(angle)*x-sin(angle)*y;
// y1=cos(angle)*y+sin(angle)*x;
for (var i = 0, l = contour.length; i < l; i++) {
p = contour[i];
px = cos * (p.x - x) - sin * (p.y - y);
py = cos * (p.y - y) + sin * (p.x - x);
p.x = px + x;
p.y = py + y;
}
return contour;
}

View File

@ -0,0 +1,48 @@
/**
* @file 路径旋转
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* 对path坐标进行调整
*/
export default function pathRotate(
/** 坐标点 */
contour: PathPoint[],
/** 角度 */
angle?: number,
/** x偏移 */
centerX?: number,
/** y偏移 */
centerY?: number
): PathPoint[] {
angle = angle === undefined ? 0 : angle;
const x = centerX || 0;
const y = centerY || 0;
const cos = Math.cos(angle);
const sin = Math.sin(angle);
let px: number;
let py: number;
let p: PathPoint;
// x1=cos(angle)*x-sin(angle)*y;
// y1=cos(angle)*y+sin(angle)*x;
for (let i = 0, l = contour.length; i < l; i++) {
p = contour[i];
px = cos * (p.x - x) - sin * (p.y - y);
py = cos * (p.y - y) + sin * (p.x - x);
p.x = px + x;
p.y = py + y;
}
return contour;
}

View File

@ -1,45 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathSkew;
/**
* @file path倾斜变换
* @author mengke01(kekee000@gmail.com)
*/
/**
* path倾斜变换
*
* @param {Object} contour 坐标点
* @param {number} angle 角度
* @param {number} offsetX x偏移
* @param {number} offsetY y偏移
*
* @return {Object} contour 坐标点
*/
function pathSkew(contour, angle, offsetX, offsetY) {
angle = angle === undefined ? 0 : angle;
var x = offsetX || 0;
var tan = Math.tan(angle);
var p;
var i;
var l;
// x 平移
if (x === 0) {
for (i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.x += tan * (p.y - offsetY);
}
}
// y平移
else {
for (i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.y += tan * (p.x - offsetX);
}
}
return contour;
}

View File

@ -0,0 +1,53 @@
/**
* @file path倾斜变换
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* path倾斜变换
*
* @param contour 坐标点
* @param angle 角度
* @param offsetX x偏移
* @param offsetY y偏移
*
* @return contour 坐标点
*/
export default function pathSkew(
/** 坐标点 */
contour: PathPoint[],
/** 角度 */
angle?: number,
/** x偏移 */
offsetX?: number,
/** y偏移 */
offsetY?: number
): PathPoint[] {
angle = angle === undefined ? 0 : angle;
const x = offsetX || 0;
const tan = Math.tan(angle);
// x 平移
if (x === 0) {
for (const p of contour) {
p.x += tan * (p.y - offsetY!);
}
}
// y平移
else {
for (const p of contour) {
p.y += tan * (p.x - offsetX!);
}
}
return contour;
}

View File

@ -1,32 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathSkewX;
var _computeBoundingBox = require("./computeBoundingBox");
/**
* @file 按X轴平移变换, 变换中心为图像中心点
* @author mengke01(kekee000@gmail.com)
*/
/**
* path倾斜变换
*
* @param {Object} contour 坐标点
* @param {number} angle 角度
*
* @return {Object} contour 坐标点
*/
function pathSkewX(contour, angle) {
angle = angle === undefined ? 0 : angle;
var y = (0, _computeBoundingBox.computePath)(contour).y;
var tan = Math.tan(angle);
var p;
// x 平移
for (var i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.x += tan * (p.y - y);
}
return contour;
}

View File

@ -0,0 +1,44 @@
/**
* @file 按X轴平移变换, 变换中心为图像中心点
* @author mengke01(kekee000@gmail.com)
*/
import { computePath } from "./computeBoundingBox";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* path倾斜变换
*
* @param contour 坐标点
* @param angle 角度
*
* @return contour 坐标点
*/
export default function pathSkewX(
/** 坐标点 */
contour: PathPoint[],
/** 角度 */
angle?: number
): PathPoint[] {
angle = angle === undefined ? 0 : angle;
const bound = computePath(contour);
if (!bound) {
return contour;
}
const y = bound.y;
const tan = Math.tan(angle);
// x 平移
for (const p of contour) {
p.x += tan * (p.y - y);
}
return contour;
}

View File

@ -1,32 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathSkewY;
var _computeBoundingBox = require("./computeBoundingBox");
/**
* @file 按Y轴平移变换, 变换中心为图像中心点
* @author mengke01(kekee000@gmail.com)
*/
/**
* path倾斜变换
*
* @param {Object} contour 坐标点
* @param {number} angle 角度
*
* @return {Object} contour 坐标点
*/
function pathSkewY(contour, angle) {
angle = angle === undefined ? 0 : angle;
var x = (0, _computeBoundingBox.computePath)(contour).x;
var tan = Math.tan(angle);
var p;
// y 平移
for (var i = 0, l = contour.length; i < l; i++) {
p = contour[i];
p.y += tan * (p.x - x);
}
return contour;
}

View File

@ -0,0 +1,44 @@
/**
* @file 按Y轴平移变换, 变换中心为图像中心点
* @author mengke01(kekee000@gmail.com)
*/
import { computePath } from "./computeBoundingBox";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* path倾斜变换
*
* @param contour 坐标点
* @param angle 角度
*
* @return contour 坐标点
*/
export default function pathSkewY(
/** 坐标点 */
contour: PathPoint[],
/** 角度 */
angle?: number
): PathPoint[] {
angle = angle === undefined ? 0 : angle;
const bound = computePath(contour);
if (!bound) {
return contour;
}
const x = bound.x;
const tan = Math.tan(angle);
// y 平移
for (const p of contour) {
p.y += tan * (p.x - x);
}
return contour;
}

View File

@ -1,56 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transform;
/**
* @file 对轮廓进行transform变换
* @author mengke01(kekee000@gmail.com)
*
* 参考资料:
* http://blog.csdn.net/henren555/article/details/9699449
*
* |X| |a c e| |x|
* |Y| = |b d f| * |y|
* |1| |0 0 1| |1|
*
* X = x * a + y * c + e
* Y = x * b + y * d + f
*/
/**
* 图形仿射矩阵变换
*
* @param {Array} contour 轮廓点(对象格式或扁平格式 [x, y, onCurve, ...])
* @param {number} a m11
* @param {number} b m12
* @param {number} c m21
* @param {number} d m22
* @param {number} e dx
* @param {number} f dy
* @return {Array} contour 轮廓点
*/
function transform(contour, a, b, c, d, e, f) {
if (!contour.length) {
return contour;
}
/* 优化66: 检测扁平格式 - 第一个元素是 number 则为扁平格式 */
if (typeof contour[0] === 'number') {
for (var i = 0, l = contour.length; i < l; i += 3) {
var x = contour[i];
var y = contour[i + 1];
contour[i] = x * a + y * c + e;
contour[i + 1] = x * b + y * d + f;
}
} else {
for (var i = 0, l = contour.length; i < l; i++) {
var p = contour[i];
var x = p.x;
var y = p.y;
p.x = x * a + y * c + e;
p.y = x * b + y * d + f;
}
}
return contour;
}

View File

@ -0,0 +1,87 @@
/**
* @file 对轮廓进行transform变换
* @author mengke01(kekee000@gmail.com)
*
* 参考资料:
* http://blog.csdn.net/henren555/article/details/9699449
*
* |X| |a c e| |x|
* |Y| = |b d f| * |y|
* |1| |0 0 1| |1|
*
* X = x * a + y * c + e
* Y = x * b + y * d + f
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 轮廓:对象格式或扁平格式 [x, y, onCurve, ...] */
export type Contour = PathPoint[] | number[];
/**
* 判断轮廓是否为扁平格式
*/
function isFlatContour(contour: Contour): contour is number[] {
/* 检测扁平格式 - 第一个元素是 number 则为扁平格式 */
return typeof contour[0] === 'number';
}
/**
* 图形仿射矩阵变换
*
* @param contour 轮廓点(对象格式或扁平格式 [x, y, onCurve, ...])
* @param a m11
* @param b m12
* @param c m21
* @param d m22
* @param e dx
* @param f dy
* @return contour 轮廓点
*/
export default function transform(
/** 轮廓点 */
contour: Contour,
/** m11 */
a: number,
/** m12 */
b: number,
/** m21 */
c: number,
/** m22 */
d: number,
/** dx */
e: number,
/** dy */
f: number
): Contour {
if (!contour.length) {
return contour;
}
if (isFlatContour(contour)) {
let i = 0;
while (i < contour.length) {
const x = contour[i];
const y = contour[i + 1];
contour[i] = x * a + y * c + e;
contour[i + 1] = x * b + y * d + f;
i += 3;
}
} else {
for (const p of contour) {
const x = p.x;
const y = p.y;
p.x = x * a + y * c + e;
p.y = x * b + y * d + f;
}
}
return contour;
}

View File

@ -1,170 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clone = clone;
exports.deInterpolate = deInterpolate;
exports.getPathHash = getPathHash;
exports.interpolate = interpolate;
exports.isClockWise = isClockWise;
exports.makeLink = makeLink;
exports.removeOverlapPoints = removeOverlapPoints;
exports.scale = scale;
var _util = require("./util");
/**
* @file 路径相关的函数集合
* @author mengke01(kekee000@gmail.com)
*/
/**
* 对路径进行插值,补全省略的点
*
* @param {Array} path 路径
* @return {Array} 路径
*/
function interpolate(path) {
var newPath = [];
for (var i = 0, l = path.length; i < l; i++) {
var next = i === l - 1 ? 0 : i + 1;
newPath.push(path[i]);
// 插值
if (!path[i].onCurve && !path[next].onCurve) {
newPath.push({
x: (path[i].x + path[next].x) / 2,
y: (path[i].y + path[next].y) / 2,
onCurve: true
});
}
}
return newPath;
}
/**
* 去除路径中的插值点
*
* @param {Array} path 路径
* @return {Array} 路径
*/
function deInterpolate(path) {
var newPath = [];
for (var i = 0, l = path.length; i < l; i++) {
var next = i === l - 1 ? 0 : i + 1;
var prev = i === 0 ? l - 1 : i - 1;
// 插值
if (!path[prev].onCurve && path[i].onCurve && !path[next].onCurve && Math.abs(2 * path[i].x - path[prev].x - path[next].x) < 0.001 && Math.abs(2 * path[i].y - path[prev].y - path[next].y) < 0.001) {
continue;
}
newPath.push(path[i]);
}
return newPath;
}
/**
* 判断路径的方向是否顺时针
*
* see:
* http://debian.fmi.uni-sofia.bg/~sergei/cgsr/docs/clockwise.htm
*
* @param {Array} path 路径
* @return {number} 0 无方向 1 clockwise, -1 counter clockwise
*/
function isClockWise(path) {
if (path.length < 3) {
return 0;
}
var zCount = 0;
for (var i = 0, l = path.length; i < l; i++) {
var cur = path[i];
var prev = i === 0 ? path[l - 1] : path[i - 1];
var next = i === l - 1 ? path[0] : path[i + 1];
var z = (cur.x - prev.x) * (next.y - cur.y) - (cur.y - prev.y) * (next.x - cur.x);
if (z < 0) {
zCount--;
} else if (z > 0) {
zCount++;
}
}
return zCount === 0 ? 0 : zCount < 0 ? 1 : -1;
}
/**
* 获取路径哈希
*
* @param {Array} path 路径数组
* @return {number} 哈希值
*/
function getPathHash(path) {
var hash = 0;
var seed = 131;
path.forEach(function (p) {
hash = 0x7FFFFFFF & hash * seed + (0, _util.getPointHash)(p) + (p.onCurve ? 1 : 0);
});
return hash;
}
/**
* 移除重复点
*
* @param {Array} points 点集合
* @return {Array} 移除后点集合
*/
function removeOverlapPoints(points) {
var hash = {};
var ret = [];
for (var i = 0, l = points.length; i < l; i++) {
var hashcode = points[i].x * 31 + points[i].y;
if (!hash[hashcode]) {
ret.push(points[i]);
hash[hashcode] = 1;
}
}
return ret;
}
/**
* 对path进行双向链表连接
*
* @param {Array} path 轮廓数组
* @return {Array} path
*/
function makeLink(path) {
for (var i = 0, l = path.length; i < l; i++) {
var cur = path[i];
var prev = i === 0 ? path[l - 1] : path[i - 1];
var next = i === l - 1 ? path[0] : path[i + 1];
cur.index = i;
cur.next = next;
cur.prev = prev;
}
return path;
}
/**
* 对path进行缩放
*
* @param {Array} path 轮廓数组
* @param {number} ratio 缩放大小
*
* @return {Array} path
*/
function scale(path, ratio) {
for (var i = 0, l = path.length; i < l; i++) {
var cur = path[i];
cur.x *= ratio;
cur.y *= ratio;
}
return path;
}
function clone(path) {
return path ? path.map(function (p) {
var newP = {
x: p.x,
y: p.y
};
if (p.onCurve) {
newP.onCurve = true;
}
return newP;
}) : path;
}

View File

@ -0,0 +1,215 @@
/**
* @file 路径相关的函数集合
* @author mengke01(kekee000@gmail.com)
*/
import { getPointHash } from "./util";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
/** 链表遍历序号(makeLink 设置) */
index?: number;
/** 链表后继点(makeLink 设置) */
next?: PathPoint;
/** 链表前驱点(makeLink 设置) */
prev?: PathPoint;
}
/**
* 对路径进行插值,补全省略的点
*
* @param path 路径
* @return 路径
*/
export function interpolate(
/** 路径 */
path: PathPoint[]
): PathPoint[] {
const newPath: PathPoint[] = [];
for (let i = 0, l = path.length; i < l; i++) {
const next = i === l - 1 ? 0 : i + 1;
newPath.push(path[i]);
// 插值
if (!path[i].onCurve && !path[next].onCurve) {
newPath.push({
x: (path[i].x + path[next].x) / 2,
y: (path[i].y + path[next].y) / 2,
onCurve: true
});
}
}
return newPath;
}
/**
* 去除路径中的插值点
*
* @param path 路径
* @return 路径
*/
export function deInterpolate(
/** 路径 */
path: PathPoint[]
): PathPoint[] {
const newPath: PathPoint[] = [];
for (let i = 0, l = path.length; i < l; i++) {
const next = i === l - 1 ? 0 : i + 1;
const prev = i === 0 ? l - 1 : i - 1;
// 插值
if (
!path[prev].onCurve &&
path[i].onCurve &&
!path[next].onCurve &&
Math.abs(2 * path[i].x - path[prev].x - path[next].x) < 0.001 &&
Math.abs(2 * path[i].y - path[prev].y - path[next].y) < 0.001
) {
continue;
}
newPath.push(path[i]);
}
return newPath;
}
/**
* 判断路径的方向是否顺时针
*
* see:
* http://debian.fmi.uni-sofia.bg/~sergei/cgsr/docs/clockwise.htm
*
* @param path 路径
* @return 0 无方向 1 clockwise, -1 counter clockwise
*/
export function isClockWise(
/** 路径 */
path: PathPoint[]
): number {
if (path.length < 3) {
return 0;
}
let zCount = 0;
for (let i = 0, l = path.length; i < l; i++) {
const cur = path[i];
const prev = i === 0 ? path[l - 1] : path[i - 1];
const next = i === l - 1 ? path[0] : path[i + 1];
const z = (cur.x - prev.x) * (next.y - cur.y) - (cur.y - prev.y) * (next.x - cur.x);
if (z < 0) {
zCount--;
} else if (z > 0) {
zCount++;
}
}
return zCount === 0 ? 0 : zCount < 0 ? 1 : -1;
}
/**
* 获取路径哈希
*
* @param path 路径数组
* @return 哈希值
*/
export function getPathHash(
/** 路径数组 */
path: PathPoint[]
): number {
let hash = 0;
const seed = 131;
path.forEach((p) => {
hash = 0x7fffffff & (hash * seed + getPointHash(p) + (p.onCurve ? 1 : 0));
});
return hash;
}
/**
* 移除重复点
*
* @param points 点集合
* @return 移除后点集合
*/
export function removeOverlapPoints(
/** 点集合 */
points: PathPoint[]
): PathPoint[] {
const hash: Record<number, number> = {};
const ret: PathPoint[] = [];
for (const p of points) {
const hashcode = p.x * 31 + p.y;
if (!hash[hashcode]) {
ret.push(p);
hash[hashcode] = 1;
}
}
return ret;
}
/**
* 对path进行双向链表连接
*
* @param path 轮廓数组
* @return path
*/
export function makeLink(
/** 轮廓数组 */
path: PathPoint[]
): PathPoint[] {
for (let i = 0, l = path.length; i < l; i++) {
const cur = path[i];
const prev = i === 0 ? path[l - 1] : path[i - 1];
const next = i === l - 1 ? path[0] : path[i + 1];
cur.index = i;
cur.next = next;
cur.prev = prev;
}
return path;
}
/**
* 对path进行缩放
*
* @param path 轮廓数组
* @param ratio 缩放大小
*
* @return path
*/
export function scale(
/** 轮廓数组 */
path: PathPoint[],
/** 缩放大小 */
ratio: number
): PathPoint[] {
for (const cur of path) {
cur.x *= ratio;
cur.y *= ratio;
}
return path;
}
/**
* 克隆path
*
* @param path 轮廓数组
* @return 克隆后的轮廓数组
*/
export function clone(
/** 轮廓数组 */
path?: PathPoint[]
): PathPoint[] | undefined {
return path
? path.map((p) => {
const newP: PathPoint = {
x: p.x,
y: p.y
};
if (p.onCurve) {
newP.onCurve = true;
}
return newP;
})
: path;
}

View File

@ -1,91 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _computeBoundingBox = require("./computeBoundingBox");
var _pathAdjust = _interopRequireDefault(require("./pathAdjust"));
var _pathRotate = _interopRequireDefault(require("./pathRotate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /**
* @file 路径组变化函数
* @author mengke01(kekee000@gmail.com)
*/
/**
* 翻转路径
*
* @param {Array} paths 路径数组
* @param {number} xScale x翻转
* @param {number} yScale y翻转
* @return {Array} 变换后的路径
*/
function mirrorPaths(paths, xScale, yScale) {
var _computePath = _computeBoundingBox.computePath.apply(void 0, _toConsumableArray(paths)),
x = _computePath.x,
y = _computePath.y,
width = _computePath.width,
height = _computePath.height;
if (xScale === -1) {
paths.forEach(function (p) {
(0, _pathAdjust.default)(p, -1, 1, -x, 0);
(0, _pathAdjust.default)(p, 1, 1, x + width, 0);
p.reverse();
});
}
if (yScale === -1) {
paths.forEach(function (p) {
(0, _pathAdjust.default)(p, 1, -1, 0, -y);
(0, _pathAdjust.default)(p, 1, 1, 0, y + height);
p.reverse();
});
}
return paths;
}
var _default = exports.default = {
/**
* 旋转路径
*
* @param {Array} paths 路径数组
* @param {number} angle 弧度
* @return {Array} 变换后的路径
*/
rotate: function rotate(paths, angle) {
if (!angle) {
return paths;
}
var bound = _computeBoundingBox.computePath.apply(void 0, _toConsumableArray(paths));
var cx = bound.x + bound.width / 2;
var cy = bound.y + bound.height / 2;
paths.forEach(function (p) {
(0, _pathRotate.default)(p, angle, cx, cy);
});
return paths;
},
/**
* 路径组变换
*
* @param {Array} paths 路径数组
* @param {number} x x 方向缩放
* @param {number} y y 方向缩放
* @return {Array} 变换后的路径
*/
move: function move(paths, x, y) {
var bound = _computeBoundingBox.computePath.apply(void 0, _toConsumableArray(paths));
paths.forEach(function (path) {
(0, _pathAdjust.default)(path, 1, 1, x - bound.x, y - bound.y);
});
return paths;
},
mirror: function mirror(paths) {
return mirrorPaths(paths, -1, 1);
},
flip: function flip(paths) {
return mirrorPaths(paths, 1, -1);
}
};

View File

@ -0,0 +1,145 @@
/**
* @file 路径组变化函数
* @author mengke01(kekee000@gmail.com)
*/
import { computePath } from "./computeBoundingBox";
import pathAdjust from "./pathAdjust";
import pathRotate from "./pathRotate";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/**
* 翻转路径
*
* @param paths 路径数组
* @param xScale x翻转
* @param yScale y翻转
* @return 变换后的路径
*/
function mirrorPaths(
/** 路径数组 */
paths: PathPoint[][],
/** x翻转 */
xScale: number,
/** y翻转 */
yScale: number
): PathPoint[][] {
const bound = computePath(...paths);
if (!bound) {
return paths;
}
const { x, y, width, height } = bound;
if (xScale === -1) {
paths.forEach((p) => {
pathAdjust(p, -1, 1, -x, 0);
pathAdjust(p, 1, 1, x + width, 0);
p.reverse();
});
}
if (yScale === -1) {
paths.forEach((p) => {
pathAdjust(p, 1, -1, 0, -y);
pathAdjust(p, 1, 1, 0, y + height);
p.reverse();
});
}
return paths;
}
/**
* 路径组变换函数集合
*/
const pathsUtil = {
/**
* 旋转路径
*
* @param paths 路径数组
* @param angle 弧度
* @return 变换后的路径
*/
rotate(
/** 路径数组 */
paths: PathPoint[][],
/** 弧度 */
angle: number
): PathPoint[][] {
if (!angle) {
return paths;
}
const bound = computePath(...paths);
if (!bound) {
return paths;
}
const cx = bound.x + bound.width / 2;
const cy = bound.y + bound.height / 2;
paths.forEach((p) => {
pathRotate(p, angle, cx, cy);
});
return paths;
},
/**
* 路径组变换
*
* @param paths 路径数组
* @param x x 方向缩放
* @param y y 方向缩放
* @return 变换后的路径
*/
move(
/** 路径数组 */
paths: PathPoint[][],
/** x 方向缩放 */
x: number,
/** y 方向缩放 */
y: number
): PathPoint[][] {
const bound = computePath(...paths);
if (!bound) {
return paths;
}
paths.forEach((path) => {
pathAdjust(path, 1, 1, x - bound.x, y - bound.y);
});
return paths;
},
/**
* 水平镜像路径
*
* @param paths 路径数组
* @return 变换后的路径
*/
mirror(
/** 路径数组 */
paths: PathPoint[][]
): PathPoint[][] {
return mirrorPaths(paths, -1, 1);
},
/**
* 垂直翻转路径
*
* @param paths 路径数组
* @return 变换后的路径
*/
flip(
/** 路径数组 */
paths: PathPoint[][]
): PathPoint[][] {
return mirrorPaths(paths, 1, -1);
}
};
export default pathsUtil;

View File

@ -1,68 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reducePath;
var _reducePathFlat = _interopRequireDefault(require("./reducePathFlat"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 缩减path大小,去除冗余节点
* @author mengke01(kekee000@gmail.com)
*/
/**
* 判断点是否多余的点
*
* @param {Object} prev 上一个
* @param {Object} p 当前
* @param {Object} next 下一个
* @return {boolean}
*/
function redundant(prev, p, next) {
/* 优化: Math.pow(x,2) → x*x,提取 dx/dy 避免重复计算 */
var dx = p.x - next.x;
var dy = p.y - next.y;
/** 优化291: p.onCurve === next.onCurve 替代双重布尔运算 */
if (p.onCurve === next.onCurve && dx * dx + dy * dy <= 1) {
return true;
}
/** 优化291: 叉积复用 dx/dy,减少 2 次减法;合并两个 onCurve 分支 */
/** 优化288: 坐标为整数时叉积也是整数,Math.abs 改为位运算取绝对值,阈值 0.001 改为 0 */
var cross = dx * (prev.y - p.y) - dy * (prev.x - p.x);
if (prev.onCurve && next.onCurve && !cross) {
return true;
}
return false;
}
/**
* 缩减glyf,去除冗余节点
*
* @param {Array} contour 路径对象(对象格式或扁平格式 [x, y, onCurve, ...])
* @return {Array} 路径对象
*/
function reducePath(contour) {
if (!contour.length) {
return contour;
}
/* 优化66: 检测扁平格式 - 第一个元素是 number 则为扁平格式 */
if (typeof contour[0] === 'number') {
return (0, _reducePathFlat.default)(contour);
}
/* 优化264: write-index 替代 splice,O(n) 替代 O(n²) */
var len = contour.length;
var writeIdx = 0;
for (var i = 0; i < len; i++) {
var next = i === len - 1 ? contour[0] : contour[i + 1];
var prev = i === 0 ? contour[len - 1] : contour[i - 1];
/** 优化291: 缓存 contour[i] 避免重复索引查找 */
var cur = contour[i];
if (!redundant(prev, cur, next)) {
contour[writeIdx++] = cur;
}
}
contour.length = writeIdx;
return contour;
}

View File

@ -0,0 +1,91 @@
/**
* @file 缩减path大小,去除冗余节点
* @author mengke01(kekee000@gmail.com)
*/
import reducePathFlat from "./reducePathFlat";
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 轮廓:对象格式或扁平格式 [x, y, onCurve, ...] */
export type Contour = PathPoint[] | number[];
/**
* 判断轮廓是否为扁平格式
*/
function isFlatContour(contour: Contour): contour is number[] {
/* 检测扁平格式 - 第一个元素是 number 则为扁平格式 */
return typeof contour[0] === 'number';
}
/**
* 判断点是否多余的点
*
* @param prev 上一个
* @param p 当前
* @param next 下一个
* @return 是否多余
*/
function redundant(
/** 上一个 */
prev: PathPoint,
/** 当前 */
p: PathPoint,
/** 下一个 */
next: PathPoint
): boolean {
/* Math.pow(x,2) → x*x,提取 dx/dy 避免重复计算;p.onCurve === next.onCurve 替代双重布尔运算 */
const dx = p.x - next.x;
const dy = p.y - next.y;
if (p.onCurve === next.onCurve && dx * dx + dy * dy <= 1) {
return true;
}
/* 叉积复用 dx/dy,减少 2 次减法;坐标为整数时叉积也是整数,取反判断替代浮点比较 */
const cross = dx * (prev.y - p.y) - dy * (prev.x - p.x);
if (prev.onCurve && next.onCurve && !cross) {
return true;
}
return false;
}
/**
* 缩减glyf,去除冗余节点
*
* @param contour 路径对象(对象格式或扁平格式 [x, y, onCurve, ...])
* @return 路径对象
*/
export default function reducePath(
/** 路径对象 */
contour: Contour
): Contour {
if (!contour.length) {
return contour;
}
if (isFlatContour(contour)) {
return reducePathFlat(contour);
}
/* write-index 替代 splice,O(n) 替代 O(n²) */
const len = contour.length;
let writeIdx = 0;
for (let i = 0; i < len; i++) {
const next = i === len - 1 ? contour[0] : contour[i + 1];
const prev = i === 0 ? contour[len - 1] : contour[i - 1];
const cur = contour[i];
if (!redundant(prev, cur, next)) {
contour[writeIdx++] = cur;
}
}
contour.length = writeIdx;
return contour;
}

View File

@ -1,10 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reducePathFlat;
exports.ceilReducePathFlat = ceilReducePathFlat;
/**
* @file 缩减path大小(扁平格式专用),去除冗余节点
* @author mengke01(kekee000@gmail.com)
@ -13,39 +6,47 @@ exports.ceilReducePathFlat = ceilReducePathFlat;
/**
* 缩减glyf,去除冗余节点(扁平格式 [x, y, onCurve, ...])
* 懒分配:首个点被移除前不分配 reduced 数组,大多数 contour 无冗余点可直接返回
*
* @param contour 扁平格式轮廓
* @return 缩减后的轮廓
*/
function reducePathFlat(contour) {
export function reducePathFlat(
/** 扁平格式轮廓 */
contour: number[]
): number[] {
if (!contour.length) {
return contour;
}
var len = contour.length;
var l = len / 3;
/** 懒分配:仅在首个被保留的点出现时才创建 reduced 数组 */
var reduced = null;
var ri = 0;
var removed = 0;
// 段1: i=0(首点,prev 是尾点)
var px = contour[0], py = contour[1], po = contour[2];
var prevX = contour[(l - 1) * 3], prevY = contour[(l - 1) * 3 + 1], prevO = contour[(l - 1) * 3 + 2];
var nextX = contour[3], nextY = contour[4], nextO = contour[5];
var dx = px - nextX;
var dy = py - nextY;
/* 优化191: flag 只有 0 或 1,简化条件判断 */
const len = contour.length;
const l = len / 3;
/** 懒分配:仅在首个被保留的点出现时才创建 reduced 数组 */
let reduced: number[] | null = null;
let ri = 0;
let removed = 0;
// 段1: i=0(首点,prev 是尾点)
let px = contour[0], py = contour[1], po = contour[2];
let prevX = contour[(l - 1) * 3], prevY = contour[(l - 1) * 3 + 1], prevO = contour[(l - 1) * 3 + 2];
let nextX = contour[3], nextY = contour[4], nextO = contour[5];
let dx = px - nextX;
let dy = py - nextY;
/* flag 只有 0 或 1,简化条件判断 */
if (po === nextO && dx * dx + dy * dy <= 1) { removed++; }
else {
/** 优化291: 叉积复用 dx/dy,减少 2 次减法 */
/** 优化288: 坐标为整数时叉积也是整数,用 === 0 替代两个浮点比较 */
var cross = dx * (prevY - py) - dy * (prevX - px);
/* 叉积复用 dx/dy,减少 2 次减法;坐标为整数时叉积也是整数,用 === 0 替代两个浮点比较 */
const cross = dx * (prevY - py) - dy * (prevX - px);
if (prevO && nextO && !cross) { removed++; }
else {
reduced = new Array(len);
reduced[ri++] = px; reduced[ri++] = py; reduced[ri++] = po;
}
}
// 段2: i=1..l-2(中间点,prev/next 简单偏移)
for (var i = 1; i < l - 1; i++) {
var pi = i * 3;
for (let i = 1; i < l - 1; i++) {
const pi = i * 3;
px = contour[pi]; py = contour[pi + 1]; po = contour[pi + 2];
prevX = contour[pi - 3]; prevY = contour[pi - 2]; prevO = contour[pi - 1];
nextX = contour[pi + 3]; nextY = contour[pi + 4]; nextO = contour[pi + 5];
@ -53,16 +54,17 @@ function reducePathFlat(contour) {
dx = px - nextX;
dy = py - nextY;
if (po === nextO && dx * dx + dy * dy <= 1) { removed++; continue; }
/** 优化291: 叉积复用 dx/dy,减少 2 次减法 */
cross = dx * (prevY - py) - dy * (prevX - px);
/* 叉积复用 dx/dy,减少 2 次减法 */
const cross = dx * (prevY - py) - dy * (prevX - px);
if (prevO && nextO && !cross) { removed++; continue; }
if (!reduced) reduced = new Array(len);
reduced[ri++] = px; reduced[ri++] = py; reduced[ri++] = po;
}
// 段3: i=l-1(尾点,next 是首点)
if (l > 1) {
var pi = (l - 1) * 3;
const pi = (l - 1) * 3;
px = contour[pi]; py = contour[pi + 1]; po = contour[pi + 2];
prevX = contour[pi - 3]; prevY = contour[pi - 2]; prevO = contour[pi - 1];
nextX = contour[0]; nextY = contour[1]; nextO = contour[2];
@ -71,8 +73,8 @@ function reducePathFlat(contour) {
dy = py - nextY;
if (po === nextO && dx * dx + dy * dy <= 1) { removed++; }
else {
/** 优化291: 叉积复用 dx/dy,减少 2 次减法 */
cross = dx * (prevY - py) - dy * (prevX - px);
/* 叉积复用 dx/dy,减少 2 次减法 */
const cross = dx * (prevY - py) - dy * (prevX - px);
if (prevO && nextO && !cross) { removed++; }
else {
if (!reduced) reduced = new Array(len);
@ -80,26 +82,34 @@ function reducePathFlat(contour) {
}
}
}
// 没有任何缩减,直接返回原数组避免拷贝
if (!reduced) return contour;
// 截断到实际大小
reduced.length = ri;
return reduced;
}
/**
* 优化85: 合并 ceil + reduce 为单次遍历
* 合并 ceil + reduce 为单次遍历
* 在 reduce 遍历中同时做 Math.round,减少一次完整遍历
*
* @param contour 扁平格式轮廓
* @return 缩减并取整后的轮廓
*/
function ceilReducePathFlat(contour) {
export function ceilReducePathFlat(
/** 扁平格式轮廓 */
contour: number[]
): number[] {
if (!contour.length) {
return contour;
}
var len = contour.length;
var l = len / 3;
const len = contour.length;
/* 先原地 ceil */
for (var ci = 0; ci < len; ci += 3) {
for (let ci = 0; ci < len; ci += 3) {
contour[ci] = Math.round(contour[ci]);
contour[ci + 1] = Math.round(contour[ci + 1]);
}
@ -107,3 +117,5 @@ function ceilReducePathFlat(contour) {
/* 然后 reduce(数据已经 round 过) */
return reducePathFlat(contour);
}
export default reducePathFlat;

View File

@ -1,88 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ceil = ceil;
exports.ceilPoint = ceilPoint;
exports.getPointHash = getPointHash;
exports.isPointInBound = isPointInBound;
exports.isPointOverlap = isPointOverlap;
/**
* @file grahpics点相关工具箱
* @author mengke01(kekee000@gmail.com)
*/
/**
* 将点进行误差舍入
*
* @param {Object} p 点对象
* @return {Object} 点
*/
function ceilPoint(p) {
var t = p.x;
// 处理形如 4.99999 = 5, 5.00001 = 5的情况
if (Math.abs(Math.round(t) - t) < 0.00002) {
p.x = Math.round(t);
} else {
p.x = Math.round(p.x * 100000) / 100000;
}
t = p.y;
if (Math.abs(Math.round(t) - t) < 0.00005) {
p.y = Math.round(t);
} else {
p.y = Math.round(p.y * 100000) / 100000;
}
return p;
}
/**
* 将数值进行误差舍入
*
* @param {Object} x 数值
* @return {number} 点
*/
function ceil(x) {
if (Math.abs(Math.round(x) - x) < 0.00002) {
return Math.round(x);
}
return Math.round(x * 100000) / 100000;
}
/**
* 判断点是否在bounding box内部
*
* @param {Object} bound bounding box对象
* @param {Object} p 点对象
* @param {boolean=} fixed 是否四舍五入
* @return {boolean} 是否
*/
function isPointInBound(bound, p, fixed) {
if (fixed) {
return ceil(p.x) <= ceil(bound.x + bound.width) && ceil(p.x) >= ceil(bound.x) && ceil(p.y) <= ceil(bound.y + bound.height) && ceil(p.y) >= ceil(bound.y);
}
return p.x <= bound.x + bound.width && p.x >= bound.x && p.y <= bound.y + bound.height && p.y >= bound.y;
}
/**
* 判断点是否重合
*
* @param {Object} p0 p0
* @param {Object} p1 p1
* @return {boolean} 是否
*/
function isPointOverlap(p0, p1) {
return ceil(p0.x) === ceil(p1.x) && ceil(p0.y) === ceil(p1.y);
}
/**
* 获取点的hash值
*
* @param {Object} p p
* @param {Object} p1 p1
* @return {number}
*/
function getPointHash(p) {
return Math.floor(7 * Math.floor(p.x * 10) + 131 * Math.floor(p.y * 100));
}

View File

@ -0,0 +1,132 @@
/**
* @file grahpics点相关工具箱
* @author mengke01(kekee000@gmail.com)
*/
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 包围盒 */
interface BoundBox {
/** 水平最小值 */
x: number;
/** 垂直最小值 */
y: number;
/** 宽度 */
width: number;
/** 高度 */
height: number;
}
/**
* 将点进行误差舍入
*
* @param p 点对象
* @return 点
*/
export function ceilPoint(
/** 点对象 */
p: PathPoint
): PathPoint {
let t = p.x;
// 处理形如 4.99999 = 5, 5.00001 = 5的情况
if (Math.abs(Math.round(t) - t) < 0.00002) {
p.x = Math.round(t);
} else {
p.x = Math.round(p.x * 100000) / 100000;
}
t = p.y;
if (Math.abs(Math.round(t) - t) < 0.00005) {
p.y = Math.round(t);
} else {
p.y = Math.round(p.y * 100000) / 100000;
}
return p;
}
/**
* 将数值进行误差舍入
*
* @param x 数值
* @return 点
*/
export function ceil(
/** 数值 */
x: number
): number {
if (Math.abs(Math.round(x) - x) < 0.00002) {
return Math.round(x);
}
return Math.round(x * 100000) / 100000;
}
/**
* 判断点是否在bounding box内部
*
* @param bound bounding box对象
* @param p 点对象
* @param fixed 是否四舍五入
* @return 是否
*/
export function isPointInBound(
/** bounding box对象 */
bound: BoundBox,
/** 点对象 */
p: PathPoint,
/** 是否四舍五入 */
fixed?: boolean
): boolean {
if (fixed) {
return (
ceil(p.x) <= ceil(bound.x + bound.width) &&
ceil(p.x) >= ceil(bound.x) &&
ceil(p.y) <= ceil(bound.y + bound.height) &&
ceil(p.y) >= ceil(bound.y)
);
}
return (
p.x <= bound.x + bound.width &&
p.x >= bound.x &&
p.y <= bound.y + bound.height &&
p.y >= bound.y
);
}
/**
* 判断点是否重合
*
* @param p0 p0
* @param p1 p1
* @return 是否
*/
export function isPointOverlap(
/** p0 */
p0: PathPoint,
/** p1 */
p1: PathPoint
): boolean {
return ceil(p0.x) === ceil(p1.x) && ceil(p0.y) === ceil(p1.y);
}
/**
* 获取点的hash值
*
* @param p p
* @return 哈希值
*/
export function getPointHash(
/** p */
p: PathPoint
): number {
return Math.floor(7 * Math.floor(p.x * 10) + 131 * Math.floor(p.y * 100));
}

View File

@ -1,179 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Font", {
enumerable: true,
get: function get() {
return _font.Font;
}
});
Object.defineProperty(exports, "OTFReader", {
enumerable: true,
get: function get() {
return _otfreader.default;
}
});
Object.defineProperty(exports, "Reader", {
enumerable: true,
get: function get() {
return _reader.default;
}
});
Object.defineProperty(exports, "TTF", {
enumerable: true,
get: function get() {
return _ttf.default;
}
});
Object.defineProperty(exports, "TTFReader", {
enumerable: true,
get: function get() {
return _ttfreader.default;
}
});
Object.defineProperty(exports, "TTFWriter", {
enumerable: true,
get: function get() {
return _ttfwriter.default;
}
});
Object.defineProperty(exports, "Writer", {
enumerable: true,
get: function get() {
return _writer.default;
}
});
Object.defineProperty(exports, "createFont", {
enumerable: true,
get: function get() {
return _font.createFont;
}
});
exports.default = void 0;
Object.defineProperty(exports, "eot2ttf", {
enumerable: true,
get: function get() {
return _eot2ttf.default;
}
});
Object.defineProperty(exports, "otf2ttfobject", {
enumerable: true,
get: function get() {
return _otf2ttfobject.default;
}
});
Object.defineProperty(exports, "svg2ttfobject", {
enumerable: true,
get: function get() {
return _svg2ttfobject.default;
}
});
exports.toBuffer = exports.toArrayBuffer = void 0;
Object.defineProperty(exports, "ttf2base64", {
enumerable: true,
get: function get() {
return _ttf2base.default;
}
});
Object.defineProperty(exports, "ttf2eot", {
enumerable: true,
get: function get() {
return _ttf2eot.default;
}
});
Object.defineProperty(exports, "ttf2icon", {
enumerable: true,
get: function get() {
return _ttf2icon.default;
}
});
Object.defineProperty(exports, "ttf2svg", {
enumerable: true,
get: function get() {
return _ttf2svg.default;
}
});
Object.defineProperty(exports, "ttf2woff", {
enumerable: true,
get: function get() {
return _ttf2woff.default;
}
});
Object.defineProperty(exports, "ttftowoff2", {
enumerable: true,
get: function get() {
return _ttftowoff.default;
}
});
Object.defineProperty(exports, "woff2", {
enumerable: true,
get: function get() {
return _index.default;
}
});
Object.defineProperty(exports, "woff2tottf", {
enumerable: true,
get: function get() {
return _woff2tottf.default;
}
});
Object.defineProperty(exports, "woff2ttf", {
enumerable: true,
get: function get() {
return _woff2ttf.default;
}
});
var _font = require("./ttf/font");
var _ttf = _interopRequireDefault(require("./ttf/ttf"));
var _ttfreader = _interopRequireDefault(require("./ttf/ttfreader"));
var _ttfwriter = _interopRequireDefault(require("./ttf/ttfwriter"));
var _ttf2eot = _interopRequireDefault(require("./ttf/ttf2eot"));
var _eot2ttf = _interopRequireDefault(require("./ttf/eot2ttf"));
var _ttf2woff = _interopRequireDefault(require("./ttf/ttf2woff"));
var _woff2ttf = _interopRequireDefault(require("./ttf/woff2ttf"));
var _ttf2svg = _interopRequireDefault(require("./ttf/ttf2svg"));
var _svg2ttfobject = _interopRequireDefault(require("./ttf/svg2ttfobject"));
var _reader = _interopRequireDefault(require("./ttf/reader"));
var _writer = _interopRequireDefault(require("./ttf/writer"));
var _otfreader = _interopRequireDefault(require("./ttf/otfreader"));
var _otf2ttfobject = _interopRequireDefault(require("./ttf/otf2ttfobject"));
var _ttf2base = _interopRequireDefault(require("./ttf/ttf2base64"));
var _ttf2icon = _interopRequireDefault(require("./ttf/ttf2icon"));
var _ttftowoff = _interopRequireDefault(require("./ttf/ttftowoff2"));
var _woff2tottf = _interopRequireDefault(require("./ttf/woff2tottf"));
var _index = _interopRequireDefault(require("../woff2/index"));
var _buffer = _interopRequireDefault(require("./nodejs/buffer"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 主函数
* @author mengke01(kekee000@gmail.com)
*/
var toArrayBuffer = exports.toArrayBuffer = _buffer.default.toArrayBuffer;
var toBuffer = exports.toBuffer = _buffer.default.toBuffer;
var _default = exports.default = {
createFont: _font.createFont,
Font: _font.Font,
TTF: _ttf.default,
TTFReader: _ttfreader.default,
TTFWriter: _ttfwriter.default,
ttf2eot: _ttf2eot.default,
eot2ttf: _eot2ttf.default,
ttf2woff: _ttf2woff.default,
woff2ttf: _woff2ttf.default,
ttf2svg: _ttf2svg.default,
svg2ttfobject: _svg2ttfobject.default,
Reader: _reader.default,
Writer: _writer.default,
OTFReader: _otfreader.default,
otf2ttfobject: _otf2ttfobject.default,
ttf2base64: _ttf2base.default,
ttf2icon: _ttf2icon.default,
ttftowoff2: _ttftowoff.default,
woff2tottf: _woff2tottf.default,
woff2: _index.default,
toArrayBuffer: _buffer.default.toArrayBuffer,
toBuffer: _buffer.default.toBuffer
};

View File

@ -1,82 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Font", {
enumerable: true,
get: function get() {
return _font.Font;
}
});
Object.defineProperty(exports, "createFont", {
enumerable: true,
get: function get() {
return _font.createFont;
}
});
exports.default = void 0;
Object.defineProperty(exports, "woff2", {
enumerable: true,
get: function get() {
return _index.default;
}
});
var _font = require("./ttf/font");
var _ttf = _interopRequireDefault(require("./ttf/ttf"));
var _ttfreader = _interopRequireDefault(require("./ttf/ttfreader"));
var _ttfwriter = _interopRequireDefault(require("./ttf/ttfwriter"));
var _ttf2eot = _interopRequireDefault(require("./ttf/ttf2eot"));
var _eot2ttf = _interopRequireDefault(require("./ttf/eot2ttf"));
var _ttf2woff = _interopRequireDefault(require("./ttf/ttf2woff"));
var _woff2ttf = _interopRequireDefault(require("./ttf/woff2ttf"));
var _ttf2svg = _interopRequireDefault(require("./ttf/ttf2svg"));
var _svg2ttfobject = _interopRequireDefault(require("./ttf/svg2ttfobject"));
var _reader = _interopRequireDefault(require("./ttf/reader"));
var _writer = _interopRequireDefault(require("./ttf/writer"));
var _otfreader = _interopRequireDefault(require("./ttf/otfreader"));
var _otf2ttfobject = _interopRequireDefault(require("./ttf/otf2ttfobject"));
var _ttf2base = _interopRequireDefault(require("./ttf/ttf2base64"));
var _ttf2icon = _interopRequireDefault(require("./ttf/ttf2icon"));
var _ttftowoff = _interopRequireDefault(require("./ttf/ttftowoff2"));
var _woff2tottf = _interopRequireDefault(require("./ttf/woff2tottf"));
var _index = _interopRequireDefault(require("../woff2/index"));
var _buffer = _interopRequireDefault(require("./nodejs/buffer"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 主函数
* @author mengke01(kekee000@gmail.com)
*/
var modules = {
createFont: _font.createFont,
Font: _font.Font,
TTF: _ttf.default,
TTFReader: _ttfreader.default,
TTFWriter: _ttfwriter.default,
ttf2eot: _ttf2eot.default,
eot2ttf: _eot2ttf.default,
ttf2woff: _ttf2woff.default,
woff2ttf: _woff2ttf.default,
ttf2svg: _ttf2svg.default,
svg2ttfobject: _svg2ttfobject.default,
Reader: _reader.default,
Writer: _writer.default,
OTFReader: _otfreader.default,
otf2ttfobject: _otf2ttfobject.default,
ttf2base64: _ttf2base.default,
ttf2icon: _ttf2icon.default,
ttftowoff2: _ttftowoff.default,
woff2tottf: _woff2tottf.default,
woff2: _index.default,
toArrayBuffer: _buffer.default.toArrayBuffer,
toBuffer: _buffer.default.toBuffer
};
// Export named exports for ESM
// Export default object
var _default = exports.default = modules;
if (typeof exports !== 'undefined') {
// eslint-disable-next-line import/no-commonjs
module.exports = modules;
}

50
vendor/fonteditor-core/lib/main.ts vendored Normal file
View File

@ -0,0 +1,50 @@
/**
* @file fonteditor-core 入口(ESM 版,自 main.js 重写)
* @author mengke01(kekee000@gmail.com)
*/
import Font, { createFont } from "./ttf/font";
import TTF from "./ttf/ttf";
import TTFReader from "./ttf/ttfreader";
import TTFWriter from "./ttf/ttfwriter";
import ttf2eot from "./ttf/ttf2eot";
import eot2ttf from "./ttf/eot2ttf";
import ttf2woff from "./ttf/ttf2woff";
import ttf2svg from "./ttf/ttf2svg";
import svg2ttfobject from "./ttf/svg2ttfobject";
import ttf2symbol from "./ttf/ttf2symbol";
import otf2ttfobject from "./ttf/otf2ttfobject";
import ttf2base64 from "./ttf/ttf2base64";
import eot2base64 from "./ttf/eot2base64";
import woff2base64 from "./ttf/woff2base64";
import svg2base64 from "./ttf/svg2base64";
import woff2tottf from "./ttf/woff2tottf";
import woff2ttf from "./ttf/woff2ttf";
import ttftowoff2 from "./ttf/ttftowoff2";
import woff2tobase64 from "./ttf/woff2tobase64";
import woff2 from "../woff2/index";
export default {
Font,
createFont,
TTF,
TTFReader,
TTFWriter,
ttf2eot,
eot2ttf,
ttf2woff,
ttf2svg,
svg2ttfobject,
ttf2symbol,
otf2ttfobject,
ttf2base64,
eot2base64,
woff2base64,
svg2base64,
woff2tottf,
woff2ttf,
ttftowoff2,
woff2tobase64,
woff2,
};
export { Font, createFont, TTF, TTFReader, TTFWriter, woff2 };

View File

@ -1,12 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = bezierCubic2Q2;
exports.bezierCubic2Q2Raw = bezierCubic2Q2Raw;
exports.bezierCubic2Q2Push = bezierCubic2Q2Push;
exports.bezierCubic2Q2PushRounded = bezierCubic2Q2PushRounded;
/**
* @file 三次贝塞尔转二次贝塞尔(高精度递归分割版)
* @author mengke01(kekee000@gmail.com)
@ -18,10 +9,23 @@ exports.bezierCubic2Q2PushRounded = bezierCubic2Q2PushRounded;
* 优化197: cubicToQuadsPush 使用索引赋值替代 push,支持预分配数组
*/
var MAX_DEPTH = 8;
var FLAT_THRESHOLD = 0.0625;
const MAX_DEPTH = 8;
const FLAT_THRESHOLD = 0.0625;
/** 优化275: 退化检测阈值,接近直线的段退化为单段二次贝塞尔,减少取整点数提高 SSIM */
var DEGEN_EPS_SQ = 0.25;
const DEGEN_EPS_SQ = 0.25;
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 旧对象 API 的单段二次贝塞尔:[起点, 控制点, 终点] */
type QuadSegment = [PathPoint, PathPoint, PathPoint];
/**
* 优化160+179: 直接构建扁平数组 [cx, cy, ex, ey, ...]
@ -29,7 +33,18 @@ var DEGEN_EPS_SQ = 0.25;
*/
/** 优化184: 内联 isFlatEnough */
/** 优化285: 控制点公式简化为 3*(c1x+c2x) - p1x - p2x,乘 0.25 改为 >> 2 */
function cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, result) {
function cubicToQuads(
p1x: number,
p1y: number,
c1x: number,
c1y: number,
c2x: number,
c2y: number,
p2x: number,
p2y: number,
depth: number,
result: number[]
): void {
if (depth >= MAX_DEPTH) {
result.push(
(3 * (c1x + c2x) - p1x - p2x) >> 2,
@ -39,12 +54,12 @@ function cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, result) {
);
return;
}
var ux = 3 * c1x - 2 * p1x - p2x;
var uy = 3 * c1y - 2 * p1y - p2y;
var vx = 3 * c2x - 2 * p2x - p1x;
var vy = 3 * c2y - 2 * p2y - p1y;
var d1 = ux * ux + uy * uy;
var d2 = vx * vx + vy * vy;
const ux = 3 * c1x - 2 * p1x - p2x;
const uy = 3 * c1y - 2 * p1y - p2y;
const vx = 3 * c2x - 2 * p2x - p1x;
const vy = 3 * c2y - 2 * p2y - p1y;
const d1 = ux * ux + uy * uy;
const d2 = vx * vx + vy * vy;
if (d1 <= FLAT_THRESHOLD && d2 <= FLAT_THRESHOLD) {
result.push(
(3 * (c1x + c2x) - p1x - p2x) >> 2,
@ -55,12 +70,12 @@ function cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, result) {
return;
}
var m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
var m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
var m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
var m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
var m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
var midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
const m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
const m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
const m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
const m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
const m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
const midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
cubicToQuads(p1x, p1y, m01x, m01y, m012x, m012y, midx, midy, depth + 1, result);
cubicToQuads(midx, midy, m123x, m123y, m23x, m23y, p2x, p2y, depth + 1, result);
@ -70,10 +85,10 @@ function cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, result) {
* 优化179: 接受原始坐标参数,消除调用方临时对象分配
* 返回扁平数组: [ctrlX, ctrlY, endX, endY, ctrlX, ctrlY, endX, endY, ...]
*/
function bezierCubic2Q2Raw(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
export function bezierCubic2Q2Raw(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number): number[] {
/** 优化275: 用距离平方替代严格相等,避免 Math.abs 开销 */
var dx1 = p1x - c1x, dy1 = p1y - c1y;
var dx2 = c2x - p2x, dy2 = c2y - p2y;
const dx1 = p1x - c1x, dy1 = p1y - c1y;
const dx2 = c2x - p2x, dy2 = c2y - p2y;
if (dx1 * dx1 + dy1 * dy1 + dx2 * dx2 + dy2 * dy2 <= DEGEN_EPS_SQ) {
return [
(p1x + p2x) * 0.5,
@ -83,7 +98,7 @@ function bezierCubic2Q2Raw(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
];
}
var result = [];
const result: number[] = [];
cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, 0, result);
return result;
}
@ -93,10 +108,10 @@ function bezierCubic2Q2Raw(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
* 每段写入 6 个元素: [ctrlX, ctrlY, 0, endX, endY, 1](兼容 contour 扁平格式)
* 返回写入后的索引位置
*/
function bezierCubic2Q2Push(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, contour, ci) {
export function bezierCubic2Q2Push(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, contour: number[], ci: number): number {
/** 优化275: 用距离平方替代严格相等 */
var dx1 = p1x - c1x, dy1 = p1y - c1y;
var dx2 = c2x - p2x, dy2 = c2y - p2y;
const dx1 = p1x - c1x, dy1 = p1y - c1y;
const dx2 = c2x - p2x, dy2 = c2y - p2y;
if (dx1 * dx1 + dy1 * dy1 + dx2 * dx2 + dy2 * dy2 <= DEGEN_EPS_SQ) {
contour[ci++] = (p1x + p2x) * 0.5;
contour[ci++] = (p1y + p2y) * 0.5;
@ -111,15 +126,15 @@ function bezierCubic2Q2Push(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, contour, ci)
/** 优化255: 取整版 bezierCubic2Q2Push,写入时直接 Math.round,消除调用方二次遍历 */
/** 优化290: 可选 bbox 参数,写入时同步更新 bbox,消除调用方的二次扫描 */
function bezierCubic2Q2PushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, contour, ci, bbox) {
export function bezierCubic2Q2PushRounded(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, contour: number[], ci: number, bbox?: number[]): number {
/** 优化275: 用距离平方替代严格相等 */
var dx1 = p1x - c1x, dy1 = p1y - c1y;
var dx2 = c2x - p2x, dy2 = c2y - p2y;
const dx1 = p1x - c1x, dy1 = p1y - c1y;
const dx2 = c2x - p2x, dy2 = c2y - p2y;
if (dx1 * dx1 + dy1 * dy1 + dx2 * dx2 + dy2 * dy2 <= DEGEN_EPS_SQ) {
var qx = ((p1x + p2x) * 0.25 + 0.5) | 0;
var qy = ((p1y + p2y) * 0.25 + 0.5) | 0;
var ex = (p2x + 0.5) | 0;
var ey = (p2y + 0.5) | 0;
const qx = ((p1x + p2x) * 0.25 + 0.5) | 0;
const qy = ((p1y + p2y) * 0.25 + 0.5) | 0;
const ex = (p2x + 0.5) | 0;
const ey = (p2y + 0.5) | 0;
contour[ci++] = qx; contour[ci++] = qy; contour[ci++] = 0;
contour[ci++] = ex; contour[ci++] = ey; contour[ci++] = 1;
if (bbox) {
@ -134,14 +149,14 @@ function bezierCubic2Q2PushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, conto
}
/** 优化290: bbox 参数透传,递归中同步更新 bbox */
function cubicToQuadsPushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, contour, ci, bbox) {
function cubicToQuadsPushRounded(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, depth: number, contour: number[], ci: number, bbox?: number[]): number {
if (depth >= MAX_DEPTH) {
var qx = (3 * (c1x + c2x) - p1x - p2x) * 0.25;
var qy = (3 * (c1y + c2y) - p1y - p2y) * 0.25;
var rx = (qx + 0.5) | 0;
var ry = (qy + 0.5) | 0;
var ex = (p2x + 0.5) | 0;
var ey = (p2y + 0.5) | 0;
const qx = (3 * (c1x + c2x) - p1x - p2x) * 0.25;
const qy = (3 * (c1y + c2y) - p1y - p2y) * 0.25;
const rx = (qx + 0.5) | 0;
const ry = (qy + 0.5) | 0;
const ex = (p2x + 0.5) | 0;
const ey = (p2y + 0.5) | 0;
contour[ci++] = rx; contour[ci++] = ry; contour[ci++] = 0;
contour[ci++] = ex; contour[ci++] = ey; contour[ci++] = 1;
if (bbox) {
@ -152,19 +167,19 @@ function cubicToQuadsPushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth,
}
return ci;
}
var ux = 3 * c1x - 2 * p1x - p2x;
var uy = 3 * c1y - 2 * p1y - p2y;
var vx = 3 * c2x - 2 * p2x - p1x;
var vy = 3 * c2y - 2 * p2y - p1y;
var d1 = ux * ux + uy * uy;
var d2 = vx * vx + vy * vy;
const ux = 3 * c1x - 2 * p1x - p2x;
const uy = 3 * c1y - 2 * p1y - p2y;
const vx = 3 * c2x - 2 * p2x - p1x;
const vy = 3 * c2y - 2 * p2y - p1y;
const d1 = ux * ux + uy * uy;
const d2 = vx * vx + vy * vy;
if (d1 <= FLAT_THRESHOLD && d2 <= FLAT_THRESHOLD) {
var qx2 = (3 * (c1x + c2x) - p1x - p2x) * 0.25;
var qy2 = (3 * (c1y + c2y) - p1y - p2y) * 0.25;
var rx2 = (qx2 + 0.5) | 0;
var ry2 = (qy2 + 0.5) | 0;
var ex2 = (p2x + 0.5) | 0;
var ey2 = (p2y + 0.5) | 0;
const qx2 = (3 * (c1x + c2x) - p1x - p2x) * 0.25;
const qy2 = (3 * (c1y + c2y) - p1y - p2y) * 0.25;
const rx2 = (qx2 + 0.5) | 0;
const ry2 = (qy2 + 0.5) | 0;
const ex2 = (p2x + 0.5) | 0;
const ey2 = (p2y + 0.5) | 0;
contour[ci++] = rx2; contour[ci++] = ry2; contour[ci++] = 0;
contour[ci++] = ex2; contour[ci++] = ey2; contour[ci++] = 1;
if (bbox) {
@ -176,12 +191,12 @@ function cubicToQuadsPushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth,
return ci;
}
var m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
var m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
var m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
var m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
var m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
var midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
const m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
const m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
const m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
const m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
const m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
const midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
ci = cubicToQuadsPushRounded(p1x, p1y, m01x, m01y, m012x, m012y, midx, midy, depth + 1, contour, ci, bbox);
ci = cubicToQuadsPushRounded(midx, midy, m123x, m123y, m23x, m23y, p2x, p2y, depth + 1, contour, ci, bbox);
@ -189,7 +204,7 @@ function cubicToQuadsPushRounded(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth,
}
/** 优化184+197+283: 内联 isFlatEnough,索引赋值替代 push,乘 0.25 用 >>2 替代 */
function cubicToQuadsPush(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, contour, ci) {
function cubicToQuadsPush(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, depth: number, contour: number[], ci: number): number {
if (depth >= MAX_DEPTH) {
contour[ci++] = (3 * (c1x + c2x) - p1x - p2x) >> 2;
contour[ci++] = (3 * (c1y + c2y) - p1y - p2y) >> 2;
@ -199,12 +214,12 @@ function cubicToQuadsPush(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, contour
contour[ci++] = 1;
return ci;
}
var ux = 3 * c1x - 2 * p1x - p2x;
var uy = 3 * c1y - 2 * p1y - p2y;
var vx = 3 * c2x - 2 * p2x - p1x;
var vy = 3 * c2y - 2 * p2y - p1y;
var d1 = ux * ux + uy * uy;
var d2 = vx * vx + vy * vy;
const ux = 3 * c1x - 2 * p1x - p2x;
const uy = 3 * c1y - 2 * p1y - p2y;
const vx = 3 * c2x - 2 * p2x - p1x;
const vy = 3 * c2y - 2 * p2y - p1y;
const d1 = ux * ux + uy * uy;
const d2 = vx * vx + vy * vy;
if (d1 <= FLAT_THRESHOLD && d2 <= FLAT_THRESHOLD) {
contour[ci++] = (3 * (c1x + c2x) - p1x - p2x) >> 2;
contour[ci++] = (3 * (c1y + c2y) - p1y - p2y) >> 2;
@ -215,12 +230,12 @@ function cubicToQuadsPush(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, contour
return ci;
}
var m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
var m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
var m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
var m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
var m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
var midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
const m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
const m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
const m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
const m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
const m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
const midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
ci = cubicToQuadsPush(p1x, p1y, m01x, m01y, m012x, m012y, midx, midy, depth + 1, contour, ci);
ci = cubicToQuadsPush(midx, midy, m123x, m123y, m23x, m23y, p2x, p2y, depth + 1, contour, ci);
@ -229,8 +244,21 @@ function cubicToQuadsPush(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, contour
/**
* 三次贝塞尔转二次贝塞尔(对象接口,兼容旧代码)
* 返回扁平数组: [ctrlX, ctrlY, endX, endY, ctrlX, ctrlY, endX, endY, ...]
* 返回段数组: [[起点, 控制点, 终点], ...]
*
* 注:内部复用 bezierCubic2Q2Raw 的扁平结果包装成旧段式对象,
* 消费方(graphics/getArc)依赖旧段式形状(segment[0].onCurve 等)
*/
function bezierCubic2Q2(p1, c1, c2, p2) {
return bezierCubic2Q2Raw(p1.x, p1.y, c1.x, c1.y, c2.x, c2.y, p2.x, p2.y);
function bezierCubic2Q2(p1: PathPoint, c1: PathPoint, c2: PathPoint, p2: PathPoint): QuadSegment[] {
const flat = bezierCubic2Q2Raw(p1.x, p1.y, c1.x, c1.y, c2.x, c2.y, p2.x, p2.y);
const segments: QuadSegment[] = [];
let prev: PathPoint = p1;
for (let i = 0; i < flat.length; i += 4) {
const end: PathPoint = { x: flat[i + 2], y: flat[i + 3] };
segments.push([prev, { x: flat[i], y: flat[i + 1] }, end]);
prev = end;
}
return segments;
}
export default bezierCubic2Q2;

View File

@ -1,65 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = bezierCubic2Q2;
/**
* @file 三次贝塞尔转二次贝塞尔(高精度递归分割版)
* @author mengke01(kekee000@gmail.com)
*
* 改进:递归分割三次贝塞尔直到可精确近似,提高 SSIM
*/
var MAX_DEPTH = 4;
function isFlatEnough(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
var ux = 3 * c1x - 2 * p1x - p2x;
var uy = 3 * c1y - 2 * p1y - p2y;
var vx = 3 * c2x - 2 * p2x - p1x;
var vy = 3 * c2y - 2 * p2y - p1y;
return Math.max(ux * ux + uy * uy, vx * vx + vy * vy) <= 0.25;
}
function cubicToQuads(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, depth, endpoints, controls) {
if (isFlatEnough(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) || depth >= MAX_DEPTH) {
controls.push({
x: (3 * c2x - p2x + 3 * c1x - p1x) * 0.25,
y: (3 * c2y - p2y + 3 * c1y - p1y) * 0.25
});
return;
}
var m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
var m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
var m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
var m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
var m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
var midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
cubicToQuads(p1x, p1y, m01x, m01y, m012x, m012y, midx, midy, depth + 1, endpoints, controls);
endpoints.push({ x: midx, y: midy, onCurve: true });
cubicToQuads(midx, midy, m123x, m123y, m23x, m23y, p2x, p2y, depth + 1, endpoints, controls);
}
function bezierCubic2Q2(p1, c1, c2, p2) {
if (p1.x === c1.x && p1.y === c1.y && c2.x === p2.x && c2.y === p2.y) {
return [[p1, {
x: (p1.x + p2.x) * 0.5,
y: (p1.y + p2.y) * 0.5
}, p2]];
}
var endpoints = [];
var controls = [];
cubicToQuads(p1.x, p1.y, c1.x, c1.y, c2.x, c2.y, p2.x, p2.y, 0, endpoints, controls);
var segments = [];
var prev = p1;
for (var i = 0, l = controls.length; i < l; i++) {
var next = i < endpoints.length ? endpoints[i] : p2;
segments.push([prev, controls[i], next]);
prev = next;
}
return segments;
}

View File

@ -0,0 +1,77 @@
/**
* @file 三次贝塞尔转二次贝塞尔(高精度递归分割版)
* @author mengke01(kekee000@gmail.com)
*
* 改进:递归分割三次贝塞尔直到可精确近似,提高 SSIM
*/
const MAX_DEPTH = 4;
/** 路径点 */
interface PathPoint {
/** 水平坐标 */
x: number;
/** 垂直坐标 */
y: number;
/** 是否曲线端点 */
onCurve?: boolean;
}
/** 单段二次贝塞尔:[起点, 控制点, 终点] */
type QuadSegment = [PathPoint, PathPoint, PathPoint];
function isFlatEnough(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number): boolean {
const ux = 3 * c1x - 2 * p1x - p2x;
const uy = 3 * c1y - 2 * p1y - p2y;
const vx = 3 * c2x - 2 * p2x - p1x;
const vy = 3 * c2y - 2 * p2y - p1y;
return Math.max(ux * ux + uy * uy, vx * vx + vy * vy) <= 0.25;
}
function cubicToQuads(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, depth: number, endpoints: PathPoint[], controls: PathPoint[]): void {
if (isFlatEnough(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) || depth >= MAX_DEPTH) {
controls.push({
x: (3 * c2x - p2x + 3 * c1x - p1x) * 0.25,
y: (3 * c2y - p2y + 3 * c1y - p1y) * 0.25
});
return;
}
const m01x = (p1x + c1x) * 0.5, m01y = (p1y + c1y) * 0.5;
const m12x = (c1x + c2x) * 0.5, m12y = (c1y + c2y) * 0.5;
const m23x = (c2x + p2x) * 0.5, m23y = (c2y + p2y) * 0.5;
const m012x = (m01x + m12x) * 0.5, m012y = (m01y + m12y) * 0.5;
const m123x = (m12x + m23x) * 0.5, m123y = (m12y + m23y) * 0.5;
const midx = (m012x + m123x) * 0.5, midy = (m012y + m123y) * 0.5;
cubicToQuads(p1x, p1y, m01x, m01y, m012x, m012y, midx, midy, depth + 1, endpoints, controls);
endpoints.push({ x: midx, y: midy, onCurve: true });
cubicToQuads(midx, midy, m123x, m123y, m23x, m23y, p2x, p2y, depth + 1, endpoints, controls);
}
/**
* 三次贝塞尔转二次贝塞尔(旧实现,保留对照)
*/
function bezierCubic2Q2(p1: PathPoint, c1: PathPoint, c2: PathPoint, p2: PathPoint): QuadSegment[] {
if (p1.x === c1.x && p1.y === c1.y && c2.x === p2.x && c2.y === p2.y) {
return [[p1, {
x: (p1.x + p2.x) * 0.5,
y: (p1.y + p2.y) * 0.5
}, p2]];
}
const endpoints: PathPoint[] = [];
const controls: PathPoint[] = [];
cubicToQuads(p1.x, p1.y, c1.x, c1.y, c2.x, c2.y, p2.x, p2.y, 0, endpoints, controls);
const segments: QuadSegment[] = [];
let prev = p1;
for (let i = 0; i < controls.length; i++) {
const next = i < endpoints.length ? endpoints[i] : p2;
segments.push([prev, controls[i], next]);
prev = next;
}
return segments;
}
export default bezierCubic2Q2;

View File

@ -0,0 +1,11 @@
/**
* Buffer和ArrayBuffer转换(nodejs/buffer.js 的类型声明)
*/
declare const buffer: {
/** Buffer转换成ArrayBuffer */
toArrayBuffer(buffer: Buffer): ArrayBuffer;
/** ArrayBuffer转换成Buffer */
toBuffer(arrayBuffer: ArrayBuffer): Buffer;
};
export default buffer;

View File

@ -1,44 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file Buffer和ArrayBuffer转换
* @author mengke01(kekee000@gmail.com)
*/
/* eslint-disable no-undef */
var _default = exports.default = {
/**
* Buffer转换成ArrayBuffer
*
* @param {Buffer} buffer 缓冲数组
* @return {ArrayBuffer}
*/
toArrayBuffer: function toArrayBuffer(buffer) {
var length = buffer.length;
var view = new DataView(new ArrayBuffer(length), 0, length);
for (var i = 0, l = length; i < l; i++) {
view.setUint8(i, buffer[i], false);
}
return view.buffer;
},
/**
* ArrayBuffer转换成Buffer
*
* @param {ArrayBuffer} arrayBuffer 缓冲数组
* @return {Buffer}
*/
/**
* 优化311: ArrayBuffer→Buffer 用 Buffer.from 共享底层内存(零拷贝),
* 替代逐字节 view.getUint8 循环(千字文 ttf 162KB 输出时为 toBuffer 9% 热点)。
* write 产出的 ArrayBuffer 后续不再修改,共享安全。
*/
toBuffer: function toBuffer(arrayBuffer) {
if (Array.isArray(arrayBuffer)) {
return Buffer.from(arrayBuffer);
}
return Buffer.from(arrayBuffer);
}
};

View File

@ -0,0 +1,33 @@
/// <reference types="node" />
/**
* @file Buffer和ArrayBuffer转换
* @author mengke01(kekee000@gmail.com)
*/
/** Buffer 和 ArrayBuffer 转换工具集合 */
const buffer = {
/**
* Buffer转换成ArrayBuffer
*/
toArrayBuffer(buffer: Buffer): ArrayBuffer {
const length = buffer.length;
const view = new DataView(new ArrayBuffer(length), 0, length);
for (let i = 0, l = length; i < l; i++) {
view.setUint8(i, buffer[i]);
}
return view.buffer;
},
/**
* ArrayBuffer转换成Buffer
*
* 优化311: 用 Buffer.from 共享底层内存(零拷贝),替代逐字节 view.getUint8 循环
* (千字文 ttf 162KB 输出时为 toBuffer 9% 热点)。write 产出的 ArrayBuffer
* 后续不再修改,共享安全。
*/
toBuffer(arrayBuffer: ArrayBuffer): Buffer {
return Buffer.from(arrayBuffer);
}
};
export default buffer;

View File

@ -0,0 +1,18 @@
/**
* 默认的 ttf 字体配置(ttf/data/default.js 的类型声明)
*/
declare const defaultTtf: {
/** 默认的字体编码 */
fontId: string;
/** 默认的名字集合 */
name: {
/** 默认的字体家族 */
fontFamily: string;
fontSubFamily: string;
uniqueSubFamily: string;
version: string;
postScriptName: string;
};
};
export default defaultTtf;

View File

@ -1,23 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 默认的ttf字体配置
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
// 默认的字体编码
/** 默认的 ttf 字体配置 */
const defaultTTF = {
/** 默认的字体编码 */
fontId: 'fonteditor',
// 默认的名字集合
/** 默认的名字集合 */
name: {
// 默认的字体家族
/** 默认的字体家族 */
fontFamily: 'fonteditor',
fontSubFamily: 'Medium',
uniqueSubFamily: 'FontEditor 1.0 : fonteditor',
version: 'Version 1.0; FontEditor (v1.0)',
postScriptName: 'fonteditor'
}
};
};
export default defaultTTF;

View File

@ -1,15 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 空的ttf格式json对象
* @author mengke01(kekee000@gmail.com)
*/
/* eslint-disable */
var _default = exports.default = {
/** 空的 ttf 格式 json 对象 */
const emptyTTF = {
"version": 1,
"numTables": 10,
"searchRange": 128,
@ -180,4 +177,6 @@ var _default = exports.default = {
"usBreakChar": 32,
"usMaxContext": 1
}
};
};
export default emptyTTF;

View File

@ -0,0 +1,22 @@
/**
* 复合图元标记位(componentFlag.js 的类型声明)
*
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
declare const componentFlag: {
readonly ARG_1_AND_2_ARE_WORDS: 0x01;
readonly ARGS_ARE_XY_VALUES: 0x02;
readonly ROUND_XY_TO_GRID: 0x04;
readonly WE_HAVE_A_SCALE: 0x08;
readonly RESERVED: 0x10;
readonly MORE_COMPONENTS: 0x20;
readonly WE_HAVE_AN_X_AND_Y_SCALE: 0x40;
readonly WE_HAVE_A_TWO_BY_TWO: 0x80;
readonly WE_HAVE_INSTRUCTIONS: 0x100;
readonly USE_MY_METRICS: 0x200;
readonly OVERLAP_COMPOUND: 0x400;
readonly SCALED_COMPONENT_OFFSET: 0x800;
readonly UNSCALED_COMPONENT_OFFSET: 0x1000;
};
export default componentFlag;

View File

@ -1,9 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 复合图元标记位
* @author mengke01(kekee000@gmail.com)
@ -11,7 +5,7 @@ exports.default = void 0;
* 复合图元标记位
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
var _default = exports.default = {
const componentFlag = {
ARG_1_AND_2_ARE_WORDS: 0x01,
ARGS_ARE_XY_VALUES: 0x02,
ROUND_XY_TO_GRID: 0x04,
@ -25,4 +19,6 @@ var _default = exports.default = {
OVERLAP_COMPOUND: 0x400,
SCALED_COMPONENT_OFFSET: 0x800,
UNSCALED_COMPONENT_OFFSET: 0x1000
};
} as const;
export default componentFlag;

View File

@ -1,33 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.win = exports.mac = void 0;
/**
* @file Unicode Platform-specific Encoding Identifiers
* @author mengke01(kekee000@gmail.com)
*/
// mac encoding id
var mac = exports.mac = {
'Default': 0,
// default use
'Version1.1': 1,
'ISO10646': 2,
'UnicodeBMP': 3,
'UnicodenonBMP': 4,
'UnicodeVariationSequences': 5,
'FullUnicodecoverage': 6
};
// windows encoding id
var win = exports.win = {
Symbol: 0,
UCS2: 1,
// default use
ShiftJIS: 2,
PRC: 3,
BigFive: 4,
Johab: 5,
UCS4: 6
};

View File

@ -0,0 +1,26 @@
/**
* @file Unicode Platform-specific Encoding Identifiers
* @author mengke01(kekee000@gmail.com)
*/
/** mac encoding id */
export const mac = {
Default: 0, // default use
'Version1.1': 1,
ISO10646: 2,
UnicodeBMP: 3,
UnicodenonBMP: 4,
UnicodeVariationSequences: 5,
FullUnicodecoverage: 6
} as const;
/** windows encoding id */
export const win = {
Symbol: 0,
UCS2: 1, // default use
ShiftJIS: 2,
PRC: 3,
BigFive: 4,
Johab: 5,
UCS4: 6
} as const;

View File

@ -0,0 +1,24 @@
/**
* 轮廓标记位(glyFlag.js 的类型声明)
*
* see:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
declare const glyFlag: {
/** on curve, off curve */
readonly ONCURVE: 0x01;
/** x-Short Vector */
readonly XSHORT: 0x02;
/** y-Short Vector */
readonly YSHORT: 0x04;
/** next byte is flag repeat count */
readonly REPEAT: 0x08;
/** This x is same (Positive x-Short vector) */
readonly XSAME: 0x10;
/** This y is same (Positive y-Short vector) */
readonly YSAME: 0x20;
readonly Reserved1: 0x40;
readonly Reserved2: 0x80;
};
export default glyFlag;

View File

@ -1,29 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 轮廓标记位
* @author mengke01(kekee000@gmail.com)
*
* see:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
var _default = exports.default = {
ONCURVE: 0x01,
// on curve ,off curve
XSHORT: 0x02,
// x-Short Vector
YSHORT: 0x04,
// y-Short Vector
REPEAT: 0x08,
// next byte is flag repeat count
XSAME: 0x10,
// This x is same (Positive x-Short vector)
YSAME: 0x20,
// This y is same (Positive y-Short vector)
Reserved1: 0x40,
Reserved2: 0x80
};

View File

@ -0,0 +1,19 @@
/**
* @file 轮廓标记位
* @author mengke01(kekee000@gmail.com)
*
* see:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
const glyFlag = {
ONCURVE: 0x01, // on curve ,off curve
XSHORT: 0x02, // x-Short Vector
YSHORT: 0x04, // y-Short Vector
REPEAT: 0x08, // next byte is flag repeat count
XSAME: 0x10, // This x is same (Positive x-Short vector)
YSAME: 0x20, // This y is same (Positive y-Short vector)
Reserved1: 0x40,
Reserved2: 0x80
} as const;
export default glyFlag;

View File

@ -1,15 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file ttf `name`编码表
* @author mengke01(kekee000@gmail.com)
*/
var nameId = {
/** nameId 到名称的基础映射,并附带 names 反转映射 */
const nameId: Record<number, string> & { names: Record<string, number> } = {
0: 'copyright',
1: 'fontFamily',
2: 'fontSubFamily',
@ -28,13 +23,17 @@ var nameId = {
16: 'preferredFamily',
17: 'preferredSubFamily',
18: 'compatibleFull',
19: 'sampleText'
19: 'sampleText',
names: {},
};
// 反转names
var nameIdHash = {};
const nameIdHash: Record<string, number> = {};
Object.keys(nameId).forEach(function (id) {
nameIdHash[nameId[id]] = +id;
if (id !== 'names') {
nameIdHash[nameId[+id]] = +id;
}
});
nameId.names = nameIdHash;
var _default = exports.default = nameId;
export default nameId;

View File

@ -1,9 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 字体外观分类器
* @author mengke01(kekee000@gmail.com)
@ -11,7 +5,7 @@ exports.default = void 0;
* @see:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html
*/
var _default = exports.default = {
const panose: Record<string, string[]> = {
bFamilyType: ['Any', 'No Fit', 'Text and Display', 'Script', 'Decorative', 'Pictorial'],
bSerifStyle: ['Any', 'No Fit', 'Cove', 'Obtuse Cove', 'Square Cove', 'Obtuse Square Cove', 'Square', 'Thin', 'Bone', 'Exaggerated', 'Triangle', 'Normal Sans', 'Obtuse Sans', 'Perp Sans', 'Flared', 'Rounded'],
bWeight: ['Any', 'No Fit', 'Very Light', 'Light', 'Thin', 'Book', 'Medium', 'Demi', 'Bold', 'Heavy', 'Black', 'Nord'],
@ -22,4 +16,6 @@ var _default = exports.default = {
bLetterform: ['Any', 'No Fit', 'Normal/Contact', 'Normal/Weighted', 'Normal/Boxed', 'Normal/Flattened', 'Normal/Rounded', 'Normal/Off Center', 'Normal/Square', 'Oblique/Contact', 'Oblique/Weighted', 'Oblique/Boxed', 'Oblique/Flattened', 'Oblique/Rounded', 'Oblique/Off Center', 'Oblique/Square'],
bMidline: ['Any', 'No Fit', 'Standard/Trimmed', 'Standard/Pointed', 'Standard/Serifed', 'High/Trimmed', 'High/Pointed', 'High/Serifed', 'Constant/Trimmed', 'Constant/Pointed', 'Constant/Serifed', 'Low/Trimmed', 'Low/Pointed', 'Low/Serifed'],
bXHeight: ['Any', 'No Fit', 'Constant/Small', 'Constant/Standard', 'Constant/Large', 'Ducking/Small', 'Ducking/Standard', 'Ducking/Large']
};
};
export default panose;

View File

@ -1,17 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 字体所属平台
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
Unicode: 0,
Macintosh: 1,
// mac
reserved: 2,
Microsoft: 3 // win
};

View File

@ -0,0 +1,12 @@
/**
* @file 字体所属平台
* @author mengke01(kekee000@gmail.com)
*/
const platform = {
Unicode: 0,
Macintosh: 1, // mac
reserved: 2,
Microsoft: 3 // win
} as const;
export default platform;

View File

@ -1,9 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file Mac glyf命名表
* @author mengke01(kekee000@gmail.com)
@ -11,7 +5,7 @@ exports.default = void 0;
* see:
* http://www.microsoft.com/typography/otspec/WGL4.htm
*/
var _default = exports.default = {
const postName: Record<number, string> = {
0: '.notdef',
1: '.null',
2: 'nonmarkingreturn',
@ -270,4 +264,6 @@ var _default = exports.default = {
255: 'Ccaron',
256: 'ccaron',
257: 'dcroat'
};
};
export default postName;

View File

@ -1,9 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file unicode 编码与postName对照表
* @author mengke01(kekee000@gmail.com)
@ -11,7 +5,7 @@ exports.default = void 0;
* see:
* http://www.microsoft.com/typography/otspec/WGL4.htm
*/
var _default = exports.default = {
const unicodeName: Record<number, number> = {
0: 1,
1: 1,
2: 1,
@ -300,4 +294,6 @@ var _default = exports.default = {
64257: 192,
64258: 193,
65535: 0 // 0xFFFF指向.notdef
};
};
export default unicodeName;

View File

@ -1,14 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 字体粗细度量
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
const weightClass: Record<number, string> = {
100: 'Ultra-light',
200: 'Extra-light',
300: 'Light',
@ -18,4 +12,6 @@ var _default = exports.default = {
700: 'Bold',
800: 'Extra-Bold',
900: 'Ultra-bold'
};
};
export default weightClass;

View File

@ -1,14 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @file 字体宽度度量
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
const widthClass: Record<number, string> = {
1: 'Ultra-condensed',
2: 'Extra-condensed',
3: 'Condensed',
@ -18,4 +12,6 @@ var _default = exports.default = {
7: 'Expanded',
8: 'Extra-expanded',
9: 'Ultra-expanded'
};
};
export default widthClass;

View File

@ -1,22 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = eot2base64;
var _bytes2base = _interopRequireDefault(require("./util/bytes2base64"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file eot数组转base64编码
* @author mengke01(kekee000@gmail.com)
*/
/**
* eot数组转base64编码
*
* @param {Array} arrayBuffer ArrayBuffer对象
* @return {string} base64编码
*/
function eot2base64(arrayBuffer) {
return 'data:font/eot;charset=utf-8;base64,' + (0, _bytes2base.default)(arrayBuffer);
}

View File

@ -0,0 +1,17 @@
/// <reference types="node" />
/**
* @file eot数组转base64编码
* @author mengke01(kekee000@gmail.com)
*/
import bytes2base64 from "./util/bytes2base64";
/**
* eot数组转base64编码
*
* @param arrayBuffer ArrayBuffer对象
* @return base64编码
*/
export default function eot2base64(arrayBuffer: ArrayBuffer | Buffer): string {
return "data:font/eot;charset=utf-8;base64," + bytes2base64(arrayBuffer);
}

View File

@ -1,80 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = eot2ttf;
var _reader = _interopRequireDefault(require("./reader"));
var _writer = _interopRequireDefault(require("./writer"));
var _error = _interopRequireDefault(require("./error"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file eot转ttf
* @author mengke01(kekee000@gmail.com)
*/
/**
* eot格式转换成ttf字体格式
*
* @param {ArrayBuffer} eotBuffer eot缓冲数组
* @param {Object} options 选项
*
* @return {ArrayBuffer} ttf格式byte流
*/
// eslint-disable-next-line no-unused-vars
function eot2ttf(eotBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// 这里用小尾方式读取
var eotReader = new _reader.default(eotBuffer, 0, eotBuffer.byteLength, true);
// check magic number
var magicNumber = eotReader.readUint16(34);
if (magicNumber !== 0x504C) {
_error.default.raise(10110);
}
// check version
var version = eotReader.readUint32(8);
if (version !== 0x20001 && version !== 0x10000 && version !== 0x20002) {
_error.default.raise(10110);
}
var eotSize = eotBuffer.byteLength || eotBuffer.length;
var fontSize = eotReader.readUint32(4);
var fontOffset = 82;
var familyNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + familyNameSize;
var styleNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + styleNameSize;
var versionNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + versionNameSize;
var fullNameSize = eotReader.readUint16(fontOffset);
fontOffset += 2 + fullNameSize;
// version 0x20001
if (version === 0x20001 || version === 0x20002) {
var rootStringSize = eotReader.readUint16(fontOffset + 2);
fontOffset += 4 + rootStringSize;
}
// version 0x20002
if (version === 0x20002) {
fontOffset += 10;
var signatureSize = eotReader.readUint16(fontOffset);
fontOffset += 2 + signatureSize;
fontOffset += 4;
var eudcFontSize = eotReader.readUint32(fontOffset);
fontOffset += 4 + eudcFontSize;
}
if (fontOffset + fontSize > eotSize) {
_error.default.raise(10001);
}
// support slice
if (eotBuffer.slice) {
return eotBuffer.slice(fontOffset, fontOffset + fontSize);
}
// not support ArrayBuffer.slice eg. IE10
var bytes = eotReader.readBytes(fontOffset, fontSize);
return new _writer.default(new ArrayBuffer(fontSize)).writeBytes(bytes).getBuffer();
}

View File

@ -0,0 +1,71 @@
/**
* @file eot转ttf
* @author mengke01(kekee000@gmail.com)
*/
import Reader from "./reader";
import Writer from "./writer";
import error from "./error";
/**
* eot格式转换成ttf字体格式
*
* @param eotBuffer eot缓冲数组
* @param _options 选项(未使用,保留签名兼容)
* @return ttf格式byte流
*/
export default function eot2ttf(eotBuffer: ArrayBuffer, _options: object = {}): ArrayBuffer {
// 这里用小尾方式读取
const eotReader = new Reader(eotBuffer, 0, eotBuffer.byteLength, true);
// check magic number
const magicNumber = eotReader.readUint16(34);
if (magicNumber !== 0x504c) {
error.raise(10110);
}
// check version
const version = eotReader.readUint32(8);
if (version !== 0x20001 && version !== 0x10000 && version !== 0x20002) {
error.raise(10110);
}
const eotSize = eotBuffer.byteLength || (eotBuffer as unknown as { length: number }).length;
const fontSize = eotReader.readUint32(4);
let fontOffset = 82;
const familyNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + familyNameSize;
const styleNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + styleNameSize;
const versionNameSize = eotReader.readUint16(fontOffset);
fontOffset += 4 + versionNameSize;
const fullNameSize = eotReader.readUint16(fontOffset);
fontOffset += 2 + fullNameSize;
// version 0x20001
if (version === 0x20001 || version === 0x20002) {
const rootStringSize = eotReader.readUint16(fontOffset + 2);
fontOffset += 4 + rootStringSize;
}
// version 0x20002
if (version === 0x20002) {
fontOffset += 10;
const signatureSize = eotReader.readUint16(fontOffset);
fontOffset += 2 + signatureSize;
fontOffset += 4;
const eudcFontSize = eotReader.readUint32(fontOffset);
fontOffset += 4 + eudcFontSize;
}
if (fontOffset + fontSize > eotSize) {
error.raise(10001);
}
// support slice
if ((eotBuffer as { slice?: unknown }).slice) {
return eotBuffer.slice(fontOffset, fontOffset + fontSize);
}
// not support ArrayBuffer.slice eg. IE10
const bytes = eotReader.readBytes(fontOffset, fontSize);
return new Writer(new ArrayBuffer(fontSize)).writeBytes(bytes).getBuffer();
}

View File

@ -0,0 +1,11 @@
/**
* ttf 相关错误号定义(error.js 的类型声明)
*/
declare const error: {
/**
* 抛出一个异常(number 为错误号或含 number/data 的对象)
*/
raise(e: number | { number?: number; data?: unknown }, ...fargs: unknown[]): void;
};
export default error;

View File

@ -1,52 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _string = _interopRequireDefault(require("../common/string"));
var _i18n = _interopRequireDefault(require("./i18n"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /**
* @file ttf 相关错误号定义
* @author mengke01(kekee000@gmail.com)
*/
var _default = exports.default = {
/**
* 抛出一个异常
*
* @param {Object} e 异常号或者异常对象
* @param {...Array} fargs args 参数
*
* 例如:
* e = 1001
* e = {
* number: 1001,
* data: 错误数据
* }
*/
raise: function raise(e) {
var number;
var data;
if (_typeof(e) === 'object') {
number = e.number || 0;
data = e.data;
} else {
number = e;
}
var message = _i18n.default.lang[number];
for (var _len = arguments.length, fargs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
fargs[_key - 1] = arguments[_key];
}
if (fargs.length > 0) {
var args = _typeof(fargs[0]) === 'object' ? fargs[0] : fargs;
message = _string.default.format(message, args);
}
var event = new Error(message);
event.number = number;
if (data) {
event.data = data;
}
throw event;
}
};

46
vendor/fonteditor-core/lib/ttf/error.ts vendored Normal file
View File

@ -0,0 +1,46 @@
/**
* @file ttf 相关错误号定义
* @author mengke01(kekee000@gmail.com)
*/
import string from '../common/string';
import i18n from './i18n';
const error = {
/**
* 抛出一个异常(e 为错误号,或含 number/data 字段的异常对象;
* fargs 为格式化参数,首个参数为对象时按 ${key} 取值,否则按 ${0} ${1} 序号取值)
*
* 例如:
* e = 1001
* e = {
* number: 1001,
* data: 错误数据
* }
*/
raise(
e: number | { number?: number; data?: unknown },
...fargs: unknown[]
): never {
let number: number;
let data: unknown;
if (typeof e === 'object') {
number = e.number || 0;
data = e.data;
} else {
number = e;
}
let message: any = i18n.lang[number];
if (fargs.length > 0) {
const args: any = typeof fargs[0] === 'object' ? fargs[0] : fargs;
message = string.format(message, args);
}
const event: any = new Error(message);
event.number = number;
if (data) {
event.data = data;
}
throw event;
}
};
export default error;

View File

@ -1,33 +0,0 @@
/**
* fonteditor-core 类型声明
*/
export namespace FontEditor {
export type FontType = "ttf" | "otf" | "woff" | "woff2" | "eot" | "svg";
export interface SubsetOptions {
type?: string;
subset?: number[];
kerning?: boolean;
/** 保留 hinting(fpgm/cvt/prep/gasp 及 glyf instructions) */
hinting?: boolean;
extraSubsetGids?: number[];
presetCmap?: Record<number, number>;
}
}
export interface FontEditor {
/** 字体编辑器接口 */
}
export function createFontEditor(data: ArrayBuffer): FontEditor;
export class Font {
static create(buffer: ArrayBuffer | Buffer | string | Document, options?: FontEditor.SubsetOptions): Font;
get(): any;
set(data: any): Font;
export(options?: { type?: string }): ArrayBuffer;
optimize(options?: any): Font;
write(options?: any): ArrayBuffer;
}

View File

@ -1,382 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Font = void 0;
exports.createFont = createFont;
exports.default = void 0;
var _buffer = _interopRequireDefault(require("../nodejs/buffer"));
var _getEmptyttfObject = _interopRequireDefault(require("./getEmptyttfObject"));
var _ttf = _interopRequireDefault(require("./ttf"));
var _woff2ttf = _interopRequireDefault(require("./woff2ttf"));
var _otf2ttfobject = _interopRequireDefault(require("./otf2ttfobject"));
var _eot2ttf = _interopRequireDefault(require("./eot2ttf"));
var _svg2ttfobject = _interopRequireDefault(require("./svg2ttfobject"));
var _ttfreader = _interopRequireDefault(require("./ttfreader"));
var _ttfwriter = _interopRequireDefault(require("./ttfwriter"));
var _ttf2eot = _interopRequireDefault(require("./ttf2eot"));
var _ttf2woff = _interopRequireDefault(require("./ttf2woff"));
var _ttf2svg = _interopRequireDefault(require("./ttf2svg"));
var _ttf2symbol = _interopRequireDefault(require("./ttf2symbol"));
var _ttftowoff = _interopRequireDefault(require("./ttftowoff2"));
var _woff2tottf = _interopRequireDefault(require("./woff2tottf"));
var _ttf2base = _interopRequireDefault(require("./ttf2base64"));
var _eot2base = _interopRequireDefault(require("./eot2base64"));
var _woff2base = _interopRequireDefault(require("./woff2base64"));
var _svg2base = _interopRequireDefault(require("./svg2base64"));
var _bytes2base = _interopRequireDefault(require("./util/bytes2base64"));
var _woff2tobase = _interopRequireDefault(require("./woff2tobase64"));
var _optimizettf = _interopRequireDefault(require("./util/optimizettf"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /**
* @file 字体管理对象,处理字体相关的读取、查询、转换
*
* @author mengke01(kekee000@gmail.com)
*/
// 必须是nodejs环境下的Buffer对象才能触发buffer转换
var SUPPORT_BUFFER = (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && _typeof(process.versions) === 'object' && typeof process.versions.node !== 'undefined' && typeof Buffer === 'function';
var Font = exports.Font = /*#__PURE__*/function () {
/**
* 字体对象构造函数
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
*/
function Font(buffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
type: 'ttf'
};
_classCallCheck(this, Font);
// 字形对象
if (_typeof(buffer) === 'object' && buffer.glyf) {
this.set(buffer);
}
// buffer
else if (buffer) {
this.read(buffer, options);
}
// 空
else {
this.readEmpty();
}
}
/**
* Create a Font instance
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
* @return {Font}
*/
return _createClass(Font, [{
key: "readEmpty",
value:
/**
* 设置一个空的 ttfObject 对象
*
* @return {Font}
*/
function readEmpty() {
this.data = (0, _getEmptyttfObject.default)();
return this;
}
/**
* 读取字体数据
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
* @param {string} options.type 字体类型
*
* ttf, woff , eot 读取配置
* @param {boolean} options.hinting 是否保留 hinting 信息
* @param {boolean} options.kerning 是否保留 kerning 信息
* @param {boolean} options.compound2simple 复合字形转简单字形
*
* woff 读取配置
* @param {Function} options.inflate 解压相关函数
*
* svg 读取配置
* @param {boolean} options.combinePath 是否合并成单个字形,仅限于普通svg导入
* @return {Font}
*/
}, {
key: "read",
value: function read(buffer, options) {
// nodejs buffer
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = _buffer.default.toArrayBuffer(buffer);
}
}
if (options.type === 'ttf') {
this.data = new _ttfreader.default(options).read(buffer);
} else if (options.type === 'otf') {
this.data = (0, _otf2ttfobject.default)(buffer, options);
} else if (options.type === 'eot') {
buffer = (0, _eot2ttf.default)(buffer, options);
this.data = new _ttfreader.default(options).read(buffer);
} else if (options.type === 'woff') {
buffer = (0, _woff2ttf.default)(buffer, options);
this.data = new _ttfreader.default(options).read(buffer);
} else if (options.type === 'woff2') {
buffer = (0, _woff2tottf.default)(buffer, options);
this.data = new _ttfreader.default(options).read(buffer);
} else if (options.type === 'svg') {
this.data = (0, _svg2ttfobject.default)(buffer, options);
} else {
throw new Error('not support font type' + options.type);
}
this.type = options.type;
return this;
}
/**
* 写入字体数据
*
* @param {Object} options 写入参数
* @param {string} options.type 字体类型, 默认 ttf
* @param {boolean} options.toBuffer nodejs 环境中返回 Buffer 对象, 默认 true
*
* ttf 字体参数
* @param {boolean} options.hinting 是否保留 hinting 信息
* @param {boolean} options.kerning 是否保留 kerning 信息
* svg,woff 字体参数
* @param {Object} options.metadata 字体相关的信息
*
* woff 字体参数
* @param {Function} options.deflate 压缩相关函数
* @return {Buffer|ArrayBuffer|string}
*/
}, {
key: "write",
value: function write() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!options.type) {
options.type = this.type;
}
var buffer = null;
if (options.type === 'ttf') {
buffer = new _ttfwriter.default(options).write(this.data);
} else if (options.type === 'eot') {
buffer = new _ttfwriter.default(options).write(this.data);
buffer = (0, _ttf2eot.default)(buffer, options);
} else if (options.type === 'woff') {
buffer = new _ttfwriter.default(options).write(this.data);
buffer = (0, _ttf2woff.default)(buffer, options);
} else if (options.type === 'woff2') {
/** 优化316: woff2 重新编码,不消费 TTF directory checksum 与 head.checkSumAdjustment,跳过计算省大字集 ~5% */
buffer = new _ttfwriter.default(Object.assign({}, options, { skipCheckSum: true })).write(this.data);
buffer = (0, _ttftowoff.default)(buffer, options);
} else if (options.type === 'svg') {
buffer = (0, _ttf2svg.default)(this.data, options);
} else if (options.type === 'symbol') {
buffer = (0, _ttf2symbol.default)(this.data, options);
} else {
throw new Error('not support font type' + options.type);
}
if (SUPPORT_BUFFER) {
if (false !== options.toBuffer && buffer instanceof ArrayBuffer) {
buffer = _buffer.default.toBuffer(buffer);
}
}
return buffer;
}
/**
* 转换成 base64编码
*
* @param {Object} options 写入参数
* @param {string} options.type 字体类型, 默认 ttf
* 其他 options参数, 参考 write
* @see write
*
* @param {ArrayBuffer=} buffer 如果提供了buffer数据则使用 buffer数据, 否则转换现有的 font
* @return {string}
*/
}, {
key: "toBase64",
value: function toBase64(options, buffer) {
if (!options.type) {
options.type = this.type;
}
if (buffer) {
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = _buffer.default.toArrayBuffer(buffer);
}
}
} else {
options.toBuffer = false;
buffer = this.write(options);
}
var base64Str;
if (options.type === 'ttf') {
base64Str = (0, _ttf2base.default)(buffer);
} else if (options.type === 'eot') {
base64Str = (0, _eot2base.default)(buffer);
} else if (options.type === 'woff') {
base64Str = (0, _woff2base.default)(buffer);
} else if (options.type === 'woff2') {
base64Str = (0, _woff2tobase.default)(buffer);
} else if (options.type === 'svg') {
base64Str = (0, _svg2base.default)(buffer);
} else if (options.type === 'symbol') {
base64Str = (0, _svg2base.default)(buffer, 'image/svg+xml');
} else {
throw new Error('not support font type' + options.type);
}
return base64Str;
}
/**
* 设置 font 对象
*
* @param {Object} data font的ttfObject对象
* @return {this}
*/
}, {
key: "set",
value: function set(data) {
this.data = data;
return this;
}
/**
* 获取 font 数据
*
* @return {Object} ttfObject 对象
*/
}, {
key: "get",
value: function get() {
return this.data;
}
/**
* 对字形数据进行优化
*
* @param {Object} out 输出结果
* @param {boolean|Object} out.result `true` 或者有问题的地方
* @return {Font}
*/
}, {
key: "optimize",
value: function optimize(out) {
var result = (0, _optimizettf.default)(this.data);
if (out) {
out.result = result;
}
return this;
}
/**
* 将字体中的复合字形转为简单字形
*
* @return {this}
*/
}, {
key: "compound2simple",
value: function compound2simple() {
var ttfHelper = this.getHelper();
ttfHelper.compound2simple();
this.data = ttfHelper.get();
return this;
}
/**
* 对字形按照unicode编码排序
*
* @return {this}
*/
}, {
key: "sort",
value: function sort() {
var ttfHelper = this.getHelper();
ttfHelper.sortGlyf();
this.data = ttfHelper.get();
return this;
}
/**
* 查找相关字形
*
* @param {Object} condition 查询条件
* @param {Array|number} condition.unicode unicode编码列表或者单个unicode编码
* @param {string} condition.name glyf名字,例如`uniE001`, `uniE`
* @param {Function} condition.filter 自定义过滤器
* @example
* condition.filter(glyf) {
* return glyf.name === 'logo';
* }
* @return {Array} glyf字形列表
*/
}, {
key: "find",
value: function find(condition) {
var ttfHelper = this.getHelper();
var indexList = ttfHelper.findGlyf(condition);
return indexList.length ? ttfHelper.getGlyf(indexList) : indexList;
}
/**
* 合并 font 到当前的 font
*
* @param {Object} font Font 对象
* @param {Object} options 参数选项
* @param {boolean} options.scale 是否自动缩放
* @param {boolean} options.adjustGlyf 是否调整字形以适应边界
* (和 options.scale 参数互斥)
*
* @return {Font}
*/
}, {
key: "merge",
value: function merge(font, options) {
var ttfHelper = this.getHelper();
ttfHelper.mergeGlyf(font.get(), options);
this.data = ttfHelper.get();
return this;
}
/**
* 获取 TTF helper 实例
*/
}, {
key: "getHelper",
value: function getHelper() {
return new _ttf.default(this.data);
}
}], [{
key: "create",
value: function create(buffer, options) {
return new Font(buffer, options);
}
}]);
}();
/**
* base64序列化buffer 数据
*
* @param {ArrayBuffer|Buffer|string} buffer 字体数据
* @return {Font}
*/
Font.toBase64 = function (buffer) {
if (typeof buffer === 'string') {
// node 环境中没有 btoa 函数
if (typeof btoa === 'undefined') {
return Buffer.from(buffer, 'binary').toString('base64');
}
return btoa(buffer);
}
return (0, _bytes2base.default)(buffer);
};
function createFont(buffer, options) {
return new Font(buffer, options);
}
var _default = exports.default = Font;

388
vendor/fonteditor-core/lib/ttf/font.ts vendored Normal file
View File

@ -0,0 +1,388 @@
/// <reference types="node" />
/**
* @file 字体管理对象,处理字体相关的读取、查询、转换
*
* @author mengke01(kekee000@gmail.com)
*/
import nodeBuffer from "../nodejs/buffer";
import getEmptyttfObject from "./getEmptyttfObject";
import TTF from "./ttf";
import woff2ttf from "./woff2ttf";
import otf2ttfobject from "./otf2ttfobject";
import eot2ttf from "./eot2ttf";
import svg2ttfobject from "./svg2ttfobject";
import TTFReader from "./ttfreader";
import TTFWriter from "./ttfwriter";
import ttf2eot from "./ttf2eot";
import ttf2woff from "./ttf2woff";
import ttf2svg from "./ttf2svg";
import ttf2symbol from "./ttf2symbol";
import ttftowoff2 from "./ttftowoff2";
import woff2tottf from "./woff2tottf";
import ttf2base64 from "./ttf2base64";
import eot2base64 from "./eot2base64";
import woff2base64 from "./woff2base64";
import svg2base64 from "./svg2base64";
import bytes2base64 from "./util/bytes2base64";
import woff2tobase64 from "./woff2tobase64";
import optimizettf from "./util/optimizettf";
export namespace FontEditor {
export type FontType = "ttf" | "otf" | "woff" | "woff2" | "eot" | "svg";
export interface SubsetOptions {
type?: string;
subset?: number[];
kerning?: boolean;
/** 保留 hinting(fpgm/cvt/prep/gasp 及 glyf instructions) */
hinting?: boolean;
extraSubsetGids?: number[];
presetCmap?: Record<number, number>;
}
}
/**
* 字体读取/写入参数
*/
export interface FontOptions {
/** 字体类型 */
type?: string;
/** nodejs 环境中返回 Buffer 对象, 默认 true */
toBuffer?: boolean;
/** 是否保留 hinting 信息 */
hinting?: boolean;
/** 是否保留 kerning 信息 */
kerning?: boolean;
/** 零轮廓字形是否写出数据(10B header):false 时 glyf 中跳过(loca 等偏移),
* 整表空(如子集仅剩空 .notdef)会产生 glyf length=0,Chrome OTS 拒绝加载 */
writeZeroContoursGlyfData?: boolean;
/** 复合字形转简单字形 */
compound2simple?: boolean;
/** 子集化 unicode 编码列表 */
subset?: number[];
/** 额外保留的字形 gid 列表 */
extraSubsetGids?: number[];
/** codepoint 到 gid 的预设映射 */
presetCmap?: Record<number, number>;
/** 解压相关函数 */
inflate?: (data: Uint8Array) => Uint8Array;
/** 压缩相关函数 */
deflate?: (data: Uint8Array) => Uint8Array;
/** 字体相关的信息 */
metadata?: object;
/** 是否合并成单个字形,仅限于普通svg导入 */
combinePath?: boolean;
}
/** find 查询条件 */
export interface GlyfFindCondition {
/** unicode 编码列表或者单个 unicode 编码 */
unicode?: number | string | (number | string)[];
/** glyf 名字,例如`uniE001`, `uniE` */
name?: string;
/** 自定义过滤器 */
filter?: (glyf: object) => boolean;
}
// 必须是nodejs环境下的Buffer对象才能触发buffer转换
const SUPPORT_BUFFER = (typeof process === "undefined" ? "undefined" : typeof process) === 'object'
&& typeof process.versions === 'object'
&& typeof process.versions.node !== 'undefined'
&& typeof Buffer === 'function';
/**
* 字体管理对象,处理字体相关的读取、查询、转换
*/
export class Font {
/** 字体的 ttfObject 数据 */
data: any;
/** 当前字体类型 */
type?: string;
/**
* 字体对象构造函数
*
* @param buffer 字体数据
* @param options 读取参数
*/
constructor(buffer: any, options: FontOptions = { type: 'ttf' }) {
// 字形对象
if (typeof buffer === 'object' && buffer.glyf) {
this.set(buffer);
}
// buffer
else if (buffer) {
this.read(buffer, options);
}
// 空
else {
this.readEmpty();
}
}
/**
* 设置一个空的 ttfObject 对象
*
* @return {Font}
*/
readEmpty(): Font {
this.data = getEmptyttfObject();
return this;
}
/**
* 读取字体数据
*
* @param buffer 字体数据
* @param options 读取参数
*
* ttf, woff , eot 读取配置
* svg 读取配置
* @return {Font}
*/
read(buffer: any, options: FontOptions): Font {
// nodejs buffer
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = nodeBuffer.toArrayBuffer(buffer);
}
}
if (options.type === 'ttf') {
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'otf') {
this.data = otf2ttfobject(buffer, options);
} else if (options.type === 'eot') {
buffer = eot2ttf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'woff') {
buffer = woff2ttf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'woff2') {
buffer = woff2tottf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'svg') {
this.data = svg2ttfobject(buffer, options);
} else {
throw new Error('not support font type' + options.type);
}
this.type = options.type;
return this;
}
/**
* 写入字体数据
*
* @param options 写入参数
* @return {Buffer|ArrayBuffer|string}
*/
write(options: FontOptions = {}): ArrayBuffer | Buffer | string {
if (!options.type) {
options.type = this.type;
}
let buffer: ArrayBuffer | Buffer | string;
if (options.type === 'ttf') {
buffer = new TTFWriter(options).write(this.data);
} else if (options.type === 'eot') {
buffer = new TTFWriter(options).write(this.data);
buffer = ttf2eot(buffer, options);
} else if (options.type === 'woff') {
buffer = new TTFWriter(options).write(this.data);
buffer = ttf2woff(buffer, options);
} else if (options.type === 'woff2') {
/** 优化316: woff2 重新编码,不消费 TTF directory checksum 与 head.checkSumAdjustment,跳过计算省大字集 ~5% */
buffer = new TTFWriter(Object.assign({}, options, { skipCheckSum: true })).write(this.data);
buffer = ttftowoff2(buffer) as unknown as ArrayBuffer;
} else if (options.type === 'svg') {
buffer = ttf2svg(this.data, options);
} else if (options.type === 'symbol') {
buffer = ttf2symbol(this.data, options);
} else {
throw new Error('not support font type' + options.type);
}
if (SUPPORT_BUFFER) {
if (false !== options.toBuffer && buffer instanceof ArrayBuffer) {
buffer = nodeBuffer.toBuffer(buffer);
}
}
return buffer;
}
/**
* 转换成 base64编码
*
* @param options 写入参数, 参考 write
* @param buffer 如果提供了buffer数据则使用 buffer数据, 否则转换现有的 font
* @return {string}
*/
toBase64(options: FontOptions, buffer?: ArrayBuffer | Buffer | string): string {
if (!options.type) {
options.type = this.type;
}
if (buffer) {
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = nodeBuffer.toArrayBuffer(buffer);
}
}
} else {
options.toBuffer = false;
buffer = this.write(options);
}
let base64Str: string;
if (options.type === 'ttf') {
base64Str = ttf2base64(buffer as ArrayBuffer);
} else if (options.type === 'eot') {
base64Str = eot2base64(buffer as ArrayBuffer);
} else if (options.type === 'woff') {
base64Str = woff2base64(buffer as ArrayBuffer);
} else if (options.type === 'woff2') {
base64Str = woff2tobase64(buffer as ArrayBuffer);
} else if (options.type === 'svg') {
base64Str = svg2base64(buffer as string);
} else if (options.type === 'symbol') {
base64Str = svg2base64(buffer as string, 'image/svg+xml');
} else {
throw new Error('not support font type' + options.type);
}
return base64Str;
}
/**
* 设置 font 对象
*
* @param data font的ttfObject对象
* @return {Font}
*/
set(data: any): Font {
this.data = data;
return this;
}
/**
* 获取 font 数据
*
* @return ttfObject 对象
*/
get(): any {
return this.data;
}
/**
* 对字形数据进行优化
*
* @param out 输出结果
* @return {Font}
*/
optimize(out?: { result?: boolean | object }): Font {
const result = optimizettf(this.data);
if (out) {
out.result = result;
}
return this;
}
/**
* 将字体中的复合字形转为简单字形
*
* @return {Font}
*/
compound2simple(): Font {
const ttfHelper = this.getHelper();
ttfHelper.compound2simple();
this.data = ttfHelper.get();
return this;
}
/**
* 对字形按照unicode编码排序
*
* @return {Font}
*/
sort(): Font {
const ttfHelper = this.getHelper();
ttfHelper.sortGlyf();
this.data = ttfHelper.get();
return this;
}
/**
* 查找相关字形
*
* @param condition 查询条件
* @return glyf字形列表
*/
find(condition: GlyfFindCondition) {
const ttfHelper = this.getHelper();
const indexList = ttfHelper.findGlyf(condition);
return indexList.length ? ttfHelper.getGlyf(indexList) : indexList;
}
/**
* 合并 font 到当前的 font
*
* @param font Font 对象
* @param options 参数选项
* @param options.scale 是否自动缩放
* @param options.adjustGlyf 是否调整字形以适应边界
* (和 options.scale 参数互斥)
* @return {Font}
*/
merge(font: Font, options?: { scale?: boolean; adjustGlyf?: boolean }): Font {
const ttfHelper = this.getHelper();
ttfHelper.mergeGlyf(font.get(), options);
this.data = ttfHelper.get();
return this;
}
/**
* 获取 TTF helper 实例
*/
getHelper() {
return new TTF(this.data);
}
/**
* Create a Font instance
*
* @param buffer 字体数据
* @param options 读取参数
* @return {Font}
*/
static create(buffer: any, options?: FontOptions): Font {
return new Font(buffer, options);
}
/**
* base64序列化buffer 数据
*
* @param buffer 字体数据
* @return {string}
*/
static toBase64(buffer: ArrayBuffer | Buffer | string): string {
if (typeof buffer === 'string') {
// node 环境中没有 btoa 函数
if (typeof btoa === 'undefined') {
return Buffer.from(buffer, 'binary').toString('base64');
}
return btoa(buffer);
}
return bytes2base64(buffer);
}
}
/**
* Create a Font instance
*
* @param buffer 字体数据
* @param options 读取参数
* @return {Font}
*/
export function createFont(buffer: any, options?: FontOptions) {
return new Font(buffer, options);
}
export default Font;

View File

@ -1,21 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getEmpty;
var _lang = require("../common/lang");
var _empty = _interopRequireDefault(require("./data/empty"));
var _default = _interopRequireDefault(require("./data/default"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 获取空的ttf对象
* @author mengke01(kekee000@gmail.com)
*/
function getEmpty() {
var ttf = (0, _lang.clone)(_empty.default);
Object.assign(ttf.name, _default.default.name);
ttf.head.created = ttf.head.modified = Date.now();
return ttf;
}

View File

@ -0,0 +1,20 @@
import { clone } from "../common/lang";
import empty from "./data/empty";
import def from "./data/default";
/**
* @file 获取空的ttf对象
* @author mengke01(kekee000@gmail.com)
*/
/**
* 获取空的ttf对象
*
* @return {Object} ttf对象
*/
export default function getEmpty() {
const ttf = clone(empty);
Object.assign(ttf.name, def.name);
ttf.head.created = ttf.head.modified = Date.now();
return ttf;
}

View File

@ -1,17 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _I18n = _interopRequireDefault(require("../common/I18n"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file 语言字符串管理
* @author mengke01(kekee000@gmail.com)
*/
import I18n from '../common/I18n';
var zh = {
declare global {
interface Window {
/** 宿主页面注入的默认语言(如 zh-cn / en-us) */
language?: string;
}
}
/** zh-cn 语言字符串表(键为错误号) */
const zh: Record<number, string> = {
// error define
10001: '超出读取范围:${0}, ${1}',
10002: '超出写入范围:${0}, ${1}',
@ -39,7 +40,9 @@ var zh = {
10302: '读取otf表错误',
10303: 'otf字形轮廓数据为空'
};
var en = {
/** en-us 语言字符串表(键为错误号) */
const en: Record<number, string> = {
// error define
10001: 'Reading index out of range: ${0}, ${1}',
10002: 'Writing index out of range: ${0}, ${1}',
@ -52,7 +55,7 @@ var en = {
10105: 'Read woff error',
10106: 'Read svg error',
10107: 'Write ttf error',
10108: 'Write woff error',
10108: 'Write svg error',
10109: 'Write svg error',
10112: 'Write svg symbol error',
10110: 'Read eot error',
@ -67,4 +70,10 @@ var en = {
10302: 'Read otf table error',
10303: 'otf `glyph` data is empty'
};
var _default = exports.default = new _I18n.default([['zh-cn', zh], ['en-us', en]], typeof window !== 'undefined' ? window.language : 'en-us');
const i18n = new I18n(
[['zh-cn', zh], ['en-us', en]],
typeof window !== 'undefined' ? window.language : 'en-us'
);
export default i18n;

View File

@ -1,22 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ttf2base64;
var _bytes2base = _interopRequireDefault(require("./util/bytes2base64"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file otf转bse64字体
* @author mengke01(kekee000@gmail.com)
*/
/**
* ttf 二进制转base64编码
*
* @param {Array} arrayBuffer ArrayBuffer对象
* @return {string} base64编码
*/
function ttf2base64(arrayBuffer) {
return 'data:font/otf;charset=utf-8;base64,' + (0, _bytes2base.default)(arrayBuffer);
}

View File

@ -0,0 +1,17 @@
/// <reference types="node" />
/**
* @file otf转bse64字体
* @author mengke01(kekee000@gmail.com)
*/
import bytes2base64 from "./util/bytes2base64";
/**
* ttf 二进制转base64编码
*
* @param arrayBuffer ArrayBuffer对象
* @return base64编码
*/
export default function ttf2base64(arrayBuffer: ArrayBuffer | Buffer): string {
return "data:font/otf;charset=utf-8;base64," + bytes2base64(arrayBuffer);
}

View File

@ -1,42 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = otf2ttfobject;
var _error = _interopRequireDefault(require("./error"));
var _otfreader = _interopRequireDefault(require("./otfreader"));
var _otfContours2ttfContours = require("./util/otfContours2ttfContours");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file otf格式转ttf格式对象
* @author mengke01(kekee000@gmail.com)
*/
import error from "./error";
import OTFReader from "./otfreader";
import { otfContours2ttfContoursInPlace } from "./util/otfContours2ttfContours";
/** otf/ttf 对象(字段动态访问) */
type FontObject = Record<string, any>;
/**
* otf格式转ttf格式对象
*
* @param {ArrayBuffer|otfObject} otfBuffer 原始数据或者解析后的otf数据
* @param {Object} options 参数
* @return {Object} ttfObject对象
* @param otfBuffer 原始数据或者解析后的otf数据
* @param options 参数
* @return ttfObject对象
*/
function otf2ttfobject(otfBuffer, options) {
var otfObject;
export default function otf2ttfobject(
otfBuffer: ArrayBuffer | FontObject,
options?: object
): FontObject {
let otfObject: FontObject;
if (otfBuffer instanceof ArrayBuffer) {
var otfReader = new _otfreader.default(options);
const otfReader = new OTFReader(options);
otfObject = otfReader.read(otfBuffer);
otfReader.dispose();
} else if (otfBuffer.head && otfBuffer.glyf && otfBuffer.cmap) {
otfObject = otfBuffer;
} else {
_error.default.raise(10111);
return error.raise(10111);
}
// 转换otf轮廓,同时获取包围盒
var glyf = otfObject.glyf;
/** 优化291: 使用就地写入版本,消除每个 glyph 一次中间对象分配 */
var convertInPlace = _otfContours2ttfContours.otfContours2ttfContoursInPlace;
for (var i = 0, l = glyf.length; i < l; i++) {
const glyf = otfObject.glyf;
/* 使用就地写入版本,消除每个 glyph 一次中间对象分配 */
const convertInPlace = otfContours2ttfContoursInPlace;
for (let i = 0, l = glyf.length; i < l; i++) {
convertInPlace(glyf[i].contours, glyf[i]);
}
otfObject.version = 0x1;
@ -53,8 +53,8 @@ function otf2ttfobject(otfBuffer, options) {
*/
otfObject.head.flags = (otfObject.head.flags || 0) & ~(0x0008 | 0x0800);
otfObject.head.fontDirectionHint = 2;
/** 优化245: delete → null 赋值,避免 V8 隐藏类转换 */
/* delete → null 赋值,避免 V8 隐藏类转换 */
otfObject.CFF = null;
otfObject.VORG = null;
return otfObject;
}
}

View File

@ -1,262 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _directory = _interopRequireDefault(require("./table/directory"));
var _supportOtf = _interopRequireDefault(require("./table/support-otf"));
var _reader = _interopRequireDefault(require("./reader"));
var _error = _interopRequireDefault(require("./error"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
* @file otf字体读取
* @author mengke01(kekee000@gmail.com)
*/
var OTFReader = exports.default = /*#__PURE__*/function () {
/**
* OTF读取函数
*
* @param {Object} options 写入参数
* @constructor
*/
function OTFReader() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, OTFReader);
options.subset = options.subset || [];
this.options = options;
}
/**
* 初始化
*
* @param {ArrayBuffer} buffer buffer对象
* @return {Object} ttf对象
*/
return _createClass(OTFReader, [{
key: "readBuffer",
value: function readBuffer(buffer) {
var reader = new _reader.default(buffer, 0, buffer.byteLength, false);
var font = {};
// version
font.version = reader.readString(0, 4);
if (font.version !== 'OTTO') {
_error.default.raise(10301);
}
// num tables
font.numTables = reader.readUint16();
if (font.numTables <= 0 || font.numTables > 100) {
_error.default.raise(10302);
}
// searchRange
font.searchRange = reader.readUint16();
// entrySelector
font.entrySelector = reader.readUint16();
// rangeShift
font.rangeShift = reader.readUint16();
font.tables = new _directory.default(reader.offset).read(reader, font);
if (!font.tables.head || !font.tables.cmap || !font.tables.CFF) {
_error.default.raise(10302);
}
font.readOptions = this.options;
/** 优化232: 预构建表名列表,替代 for...in 遍历 */
var otfTableNames = ['head', 'maxp', 'cmap', 'name', 'hhea', 'hmtx', 'post', 'OS/2', 'CFF', 'GPOS', 'kern'];
var otfSupport = _supportOtf.default;
for (var ti = 0, tl = otfTableNames.length; ti < tl; ti++) {
var tableName = otfTableNames[ti];
if (font.tables[tableName]) {
var offset = font.tables[tableName].offset;
font[tableName] = new otfSupport[tableName](offset).read(reader, font);
}
}
if (!font.CFF.glyf) {
_error.default.raise(10303);
}
reader.dispose();
return font;
}
/**
* 关联glyf相关的信息
*
* @param {Object} font font对象
*/
}, {
key: "resolveGlyf",
value: function resolveGlyf(font) {
var codes = font.cmap;
var glyf = font.CFF.glyf;
var subsetMap = font.readOptions.subset ? font.subsetMap : null;
/**
* 优化298: subset 模式下只遍历 subset unicode 列表(O(S)),避免全 cmap 遍历(O(U))
* 思源等大 CID 字体 cmap 有数万映射,原 Object.keys + 全量循环开销显著
*/
if (subsetMap && font.readOptions.subset && font.readOptions.subset.length > 0) {
var subsetList = font.readOptions.subset;
for (var si = 0, sl = subsetList.length; si < sl; si++) {
var cp = subsetList[si];
var gid = codes[cp];
if (gid === undefined) continue;
if (!subsetMap[gid]) continue;
if (!glyf[gid].unicode) glyf[gid].unicode = [];
glyf[gid].unicode.push(cp);
}
} else {
/** 优化290: subsetMap 检查提到循环外,消除每次迭代的分支判断 */
var cmapKeys = Object.keys(codes);
if (subsetMap) {
for (var ki = 0, kl = cmapKeys.length; ki < kl; ki++) {
var c = cmapKeys[ki];
var i = codes[c];
if (!subsetMap[i]) continue;
if (!glyf[i].unicode) glyf[i].unicode = [];
glyf[i].unicode.push(+c);
}
} else {
for (var ki2 = 0, kl2 = cmapKeys.length; ki2 < kl2; ki2++) {
var c2 = cmapKeys[ki2];
var i2 = codes[c2];
if (!glyf[i2].unicode) glyf[i2].unicode = [];
glyf[i2].unicode.push(+c2);
}
}
}
/* leftSideBearing / advanceWidth —— 兼容扁平 Int32Array 和对象数组 */
var hmtxData = font.hmtx;
var isFlat = hmtxData instanceof Int32Array;
var hLen = isFlat ? hmtxData.length / 2 : hmtxData.length;
/**
* 优化298: subset 模式下遍历 subsetGids(O(S)),避免全 hmtx 遍历(O(U))
*/
if (subsetMap && font.subsetGids) {
var sGids = font.subsetGids;
if (isFlat) {
for (var gi = 0, gl = sGids.length; gi < gl; gi++) {
var gid2 = sGids[gi];
glyf[gid2].advanceWidth = hmtxData[gid2 * 2] || 0;
glyf[gid2].leftSideBearing = hmtxData[gid2 * 2 + 1];
}
} else {
for (var gi2 = 0, gl2 = sGids.length; gi2 < gl2; gi2++) {
var gid3 = sGids[gi2];
glyf[gid3].advanceWidth = hmtxData[gid3].advanceWidth || 0;
glyf[gid3].leftSideBearing = hmtxData[gid3].leftSideBearing;
}
}
} else if (subsetMap) {
if (isFlat) {
for (var hi = 0, j = 0; hi < hLen; hi++, j += 2) {
if (!subsetMap[hi]) continue;
glyf[hi].advanceWidth = hmtxData[j] || 0;
glyf[hi].leftSideBearing = hmtxData[j + 1];
}
} else {
for (var hi = 0; hi < hLen; hi++) {
if (!subsetMap[hi]) continue;
glyf[hi].advanceWidth = hmtxData[hi].advanceWidth || 0;
glyf[hi].leftSideBearing = hmtxData[hi].leftSideBearing;
}
}
} else {
if (isFlat) {
for (var hi = 0, j = 0; hi < hLen; hi++, j += 2) {
glyf[hi].advanceWidth = hmtxData[j] || 0;
glyf[hi].leftSideBearing = hmtxData[j + 1];
}
} else {
for (var hi = 0; hi < hLen; hi++) {
glyf[hi].advanceWidth = hmtxData[hi].advanceWidth || 0;
glyf[hi].leftSideBearing = hmtxData[hi].leftSideBearing;
}
}
}
// 设置了subsetMap之后需要选取subset中的字形
/* 优化167: 密集数组替代 for...in,消除字符串键转换 */
if (subsetMap) {
var subsetGids = font.subsetGids;
var subGlyf;
if (subsetGids) {
subGlyf = new Array(subsetGids.length);
for (var si = 0, sl = subsetGids.length; si < sl; si++) {
subGlyf[si] = glyf[subsetGids[si]];
}
} else {
subGlyf = [];
var subsetKeys = Object.keys(subsetMap);
for (var si = 0, sl = subsetKeys.length; si < sl; si++) {
subGlyf.push(glyf[+subsetKeys[si]]);
}
}
glyf = subGlyf;
}
font.glyf = glyf;
}
/**
* 清除非必须的表
*
* @param {Object} font font对象
*/
}, {
key: "cleanTables",
value: function cleanTables(font) {
/** 优化245: delete → null 赋值,避免 V8 隐藏类转换 */
font.readOptions = null;
font.tables = null;
font.hmtx = null;
font.post.glyphNameIndex = null;
font.post.names = null;
font.subsetMap = null;
// 清除无用的表
var cff = font.CFF;
cff.glyf = null;
cff.charset = null;
cff.encoding = null;
cff.gsubrs = null;
cff.gsubrsBias = null;
cff.subrs = null;
cff.subrsBias = null;
}
/**
* 获取解析后的ttf文档
*
* @param {ArrayBuffer} buffer buffer对象
*
* @return {Object} ttf文档
*/
}, {
key: "read",
value: function read(buffer) {
this.font = this.readBuffer(buffer);
this.resolveGlyf(this.font);
this.cleanTables(this.font);
return this.font;
}
/**
* 注销
*/
}, {
key: "dispose",
value: function dispose() {
/** 优化262: delete → null 赋值,避免 V8 隐藏类转换 */
this.font = null;
this.options = null;
}
}]);
}();

Some files were not shown because too many files have changed in this diff Show More