From c1ea66d79db2f28db334605c2352a2b0a3e5576d Mon Sep 17 00:00:00 2001
From: DNT_OF <3174600270@qq.com>
Date: Fri, 13 Nov 2026 09:38:59 +0800
Subject: [PATCH 1/9] wip(ink): port ink-feel prototype behind off-by-default
flags
Ports src/ink and experiments/2026-11-12-ink-prediction from the local ink prototype onto origin/main. Board.tsx merges main's capsule eraser, abort-on-interrupt and guarded setLive with the experiment hooks. Every ink flag defaults to false; with flags off the board keeps main's behaviour.
---
.../2026-11-12-ink-prediction/README.md | 165 ++++++++++
.../2026-11-12-ink-prediction/bench.ts | 115 +++++++
.../replay-output.txt | 80 +++++
.../2026-11-12-ink-prediction/replay.ts | 51 +++
src/App.tsx | 6 +
src/board/Board.tsx | 213 ++++++++++++-
src/ink/InkDebugPanel.tsx | 87 ++++++
src/ink/capsule.test.ts | 60 ++++
src/ink/capsule.ts | 82 +++++
src/ink/debug.ts | 33 ++
src/ink/flags.test.ts | 94 ++++++
src/ink/flags.ts | 124 ++++++++
src/ink/integration.test.ts | 49 +++
src/ink/predict.test.ts | 193 ++++++++++++
src/ink/predict.ts | 293 ++++++++++++++++++
src/ink/replay.test.ts | 65 ++++
src/ink/replay.ts | 202 ++++++++++++
src/ink/smooth.test.ts | 169 ++++++++++
src/ink/smooth.ts | 127 ++++++++
src/ink/tolerance.test.ts | 72 +++++
src/ink/tolerance.ts | 66 ++++
21 files changed, 2329 insertions(+), 17 deletions(-)
create mode 100644 experiments/2026-11-12-ink-prediction/README.md
create mode 100644 experiments/2026-11-12-ink-prediction/bench.ts
create mode 100644 experiments/2026-11-12-ink-prediction/replay-output.txt
create mode 100644 experiments/2026-11-12-ink-prediction/replay.ts
create mode 100644 src/ink/InkDebugPanel.tsx
create mode 100644 src/ink/capsule.test.ts
create mode 100644 src/ink/capsule.ts
create mode 100644 src/ink/debug.ts
create mode 100644 src/ink/flags.test.ts
create mode 100644 src/ink/flags.ts
create mode 100644 src/ink/integration.test.ts
create mode 100644 src/ink/predict.test.ts
create mode 100644 src/ink/predict.ts
create mode 100644 src/ink/replay.test.ts
create mode 100644 src/ink/replay.ts
create mode 100644 src/ink/smooth.test.ts
create mode 100644 src/ink/smooth.ts
create mode 100644 src/ink/tolerance.test.ts
create mode 100644 src/ink/tolerance.ts
diff --git a/experiments/2026-11-12-ink-prediction/README.md b/experiments/2026-11-12-ink-prediction/README.md
new file mode 100644
index 0000000..0b8ffb4
--- /dev/null
+++ b/experiments/2026-11-12-ink-prediction/README.md
@@ -0,0 +1,165 @@
+# MathScrap 墨迹手感原型(预测 + 平滑 + 扫掠胶囊橡皮 + 按指针类型容差)
+
+日期:2026-11-12 / 2026-11-13(第二、三、四轮)· 分支:`experiment/ink-prediction-20261112`(基于本地 main `67b785a`)· worktree:`MathScrap-ink-proto`
+
+目的:参考对希沃白板 5.2.4 的只读逆向**结论**(只学思路,不复制其代码/常量表/资源),在 MathScrap 里做默认关闭的墨迹手感原型:去近点 + 中点二次贝塞尔平滑、短时程预测显示、扫掠胶囊橡皮、按指针类型容差、湿墨增量重绘。不引入任何新依赖(未 vendor ink-stroke-modeler,仅参考其公开论文/思路)。
+
+## 现状(main 分支)
+
+- 采集:`src/board/Board.tsx` `onPointerMove`(draw 分支)——已用 `getCoalescedEvents()`,逐事件转世界坐标后丢弃与笔尖距离 <0.8 屏幕 px 的近点,`pts` 平铺为 `[x, y, pressure, ...]`(世界坐标,无真实压感时恒 0.5,`types.ts`)。
+- 渲染:`src/board/strokes.tsx` `StrokeShape`——`ink` 样式走 perfect-freehand 轮廓(streamline 0.45),其它样式走 `centerPath`(**已经是**中点二次贝塞尔 Q 曲线)。湿墨(live)与干墨同一条渲染路径。
+- 橡皮:`Board.tsx` `eraseAt`——每个 move 事件单点 `hitStroke`(半径固定 `12/scale` 世界单位),**没有**事件间的扫掠,快速移动会漏擦。
+- 容差:不区分指针类型(鼠标/触摸/笔同一阈值)。
+- 测试:仓库没有单测框架;`tsx` + Node 内置 `node:test` 可用(Node 24)。
+
+## 方案(全部默认关闭)
+
+新增 `src/ink/` 纯函数模块 + `Board.tsx`/`App.tsx` 最小集成。开关存在 `localStorage['mathscrap.ink-flags.v1']`(JSON),URL 参数优先,并可由调试面板实时切换(响应式 store + `useSyncExternalStore`)。
+
+| 开关 | URL 参数 | 功能 |
+|---|---|---|
+| `smoothing` | `ink-smooth=1` | 采集去近点阈值 0.8→0.5 DIP(`appendStrokePoint`);抬笔时把中点二次贝塞尔采样折线烘焙进保存的 `pts`(端点精确不变,点数 <3 不处理);湿墨实时按同一函数渲染,湿/干一致 |
+| `prediction` | `ink-predict=1` | 湿墨尾部显示外推点:优先 `getPredictedEvents()`(Chromium),不可用则自研兜底——每轴 2 状态常速卡尔曼。**步长/时程按 rAF 估计的刷新率自适应**(60Hz≈33ms/8.3ms 步长、120Hz≈16.7ms/4.2ms 步长,见 `frameAdaptivePrediction`),直线满时程 ≈2 帧、曲线减半、绝对上限 36ms;门控 `gateSamples`:速度 <0.04px/ms(idle)、单次转角 >65°(sharp)、两次反向大转角或 ≥3 次摆动(jitter)时关闭。**预测点绝不写入保存数据**,下一帧真实点即替换;采样历史窗口上限 96 |
+| `predictionGhost` | `ink-ghost=1` | 预测子选项:预测尾从实墨路径拆出,用独立半透明路径(opacity 0.4,`predictionTailPath` 从笔画末端起笔)渲染,避免把预测误读为实际墨迹;关闭时维持第二轮融资的合并渲染 |
+| `capsuleEraser` | `ink-capsule=1` | `hitSweep`:上一位置到当前位置的扫掠胶囊(线段-线段距离 + `hitStroke` 同款宽度余量:ink/pencil ×0.8,marker/washi ×2.5);按住起点仍是原单点测试 |
+| `pointerTolerance` | `ink-tolerance=1` | 橡皮半径按指针类型取命中容差(鼠标/触摸/笔 = 3/10/5 DIP ÷ 缩放);**点按折叠看双条件**——整笔位移 < 该类型拖动阈值(1/16/4 DIP ÷ 缩放)**且**按下时长 ≤250ms(`TAP_MAX_DURATION_MS`)才折叠成落笔点圆点,慢速刻意短笔画保留为笔画。`hasRealPressure`:恒 0.5/0 视为无压感设备 |
+| `wetIncremental` | `ink-wet-inc=1` | 平滑子选项:湿墨增量重绘。中点贝塞尔每段只依赖 P[i-1..i+1],段一旦生成即不再变化——`updateIncrementalSmooth` 每个事件只补算新确定的 1 段 + 端点(复用共享的 `pushSegmentSamples`),与抬笔时的整笔烘焙**逐位一致**(单测保证),2000 点笔画每帧平滑成本 182.7µs → 0.5µs |
+
+调试面板 `src/ink/InkDebugPanel.tsx`:`?ink-debug=1` 强制显示(`=0` 隐藏),否则仅**开发构建且任一实验开关打开**时显示(生产无参数不可见)。面板可实时切换六个开关,显示 pointerType、是否有真实压力、`getPredictedEvents` 可用性、最近预测点数及来源(native/self/off)、move 处理耗时、rAF 帧间隔与刷新率估计(Hz)、当前笔画点数。
+
+集成点:`Board.tsx`(响应式 flags、`pointerTypeRef`、`eraseRadius()`、`finishStroke` 点按折叠(位移+时长)、`updatePrediction` 自适应步长 + 统计、draw 分支增量湿墨 + 计时、渲染处 `liveDisplay`/`tailDisplay` 分离)与 `App.tsx`(仅挂载面板一处)。`strokes.tsx`、OCR(`src/ocr/**`)、签名、版本号均未改动。
+
+开关全关时:draw 循环经 `appendStrokePoint(…, 0.8, …)`(单测证明与 main 内联循环逐事件等价),橡皮半径 12/scale、无折叠/预测/平滑/增量,行为与 main 完全一致。
+
+## 风险
+
+- 平滑与点按折叠会改变保存的 `pts` 几何(切角/折叠),开启后影响 OCR/几何推理输入形状(本 worktree 未动 OCR 代码,但输入墨迹会变)。默认关闭。
+- 点按折叠现含时长条件(≤250ms),大幅降低"吃掉刻意短笔画"的风险,但快速描点式书写(连续快短笔)仍可能被折叠——原型取舍,已记录。
+- 卡尔曼/门控/自适应常数为按手写速度量级手调,**未在真机验证手感**;rAF 估计在后台标签页会暂时失真(已 clamp 4-33ms)。
+- `getPredictedEvents` 仅 Chromium 提供;Firefox/Safari 走自研兜底,兜底在浏览器中未实测。
+- ghost 预测尾对 marker/washi 等宽笔会渲染成半透明宽带,视觉是否合适待实机确认。
+- 增量湿墨与整笔烘焙的一致性由单测逐位保证,但 React 渲染时序(state 批处理)下的实际表现待实机确认。
+
+## 改动文件(本 worktree,未提交)
+
+- `src/ink/flags.ts`:六开关解析/加载 + 响应式 store + 面板门控
+- `src/ink/smooth.ts`:去近点、`pushSegmentSamples`(整笔/增量共享采样)、`midpointBezierPolyline`、`createIncrementalSmooth`/`updateIncrementalSmooth`(增量缓存)
+- `src/ink/predict.ts`:门控 + 卡尔曼 + native 预测 + 历史窗口上限 + `frameAdaptivePrediction`(刷新率自适应,可选 framesAhead/curveFraction)+ `predictionTailPath`(ghost 独立路径)+ `PredictOptions.qAcc/measVar`(回放调参旋钮,默认不变)+ 门控噪声鲁棒性修复(翻转只看最近 12 对、曲线判定用中位数转角)
+- `src/ink/replay.ts`(合成轨迹生成 + 回放指标,纯 Node)、`src/ink/replay.test.ts`(回放单测)
+- `experiments/2026-11-12-ink-prediction/replay.ts`(回放 runner)、`replay-output.txt`(第四轮结果存档)
+- `src/ink/capsule.ts`(扫掠胶囊)、`src/ink/tolerance.ts`(指针类型容差/无压感判定/位移+时长点按判定)、`src/ink/debug.ts`(面板数据暂存)、`src/ink/InkDebugPanel.tsx`(调试面板,六开关 + 刷新率行)
+- 测试 `src/ink/{smooth,predict,capsule,flags,integration,tolerance}.test.ts`(顶部 `/// `,因 tsconfig.app.json `types:["vite/client"]` 不含 node 类型;未改 tsconfig)
+- `src/board/Board.tsx`:集成六个开关 + 统计上报(唯一被改的既有组件)
+- `src/App.tsx`:挂载调试面板(一处)
+- `experiments/2026-11-12-ink-prediction/bench.ts`(微基准)、本 README
+
+未改动:`strokes.tsx`、`src/ocr/**`、`src/wasm/**`、`package.json`、版本号、签名、默认引擎。
+
+## 测试
+
+命令(在 `MathScrap-ink-proto` 下,轻量、无构建/打包/推理):
+
+```
+npx tsx --test src/ink/*.test.ts # 55 tests, 55 pass / 0 fail
+npx tsc -p tsconfig.app.json # 类型检查通过(0 错误)
+npx oxlint src/ink src/board src/App.tsx # src/ink 0 警告;board=6、App=3 与 main 基线完全相同
+```
+
+覆盖要点:平滑端点不变/无 NaN/压感在邻域内、flag-off 与 main 采集循环等价;门控(直线/曲线/急转/抖动/停笔/样本不足)、预测尾时程 ≤36ms 与输入不可变;**预测点永不进入保存笔画**;胶囊快速移动命中、退化成圆、宽度余量;指针类型映射与三档阈值 ÷ 缩放、无压感判定;**点按 = 位移且时长双条件**(慢速刻意短笔画保留);**刷新率自适应**(60/120/144Hz 步长与时程单调、绝对上限、退化 clamp);**增量平滑在每个前缀上与整笔重采样逐位一致**、冷启动、no-op、输入不变性;ghost 路径从笔画末端起笔且不改输入;开关默认全关、解析优先级、store 稳定性、面板门控。
+
+## 性能微基准(Node 24 / tsx,单线程,与 OCR 任务并存时测得)
+
+`npx tsx experiments/2026-11-12-ink-prediction/bench.ts`:
+
+| 项目 | 单次耗时 |
+|---|---|
+| 平滑 200 点(整笔重采样,每湿墨帧) | 13.1 µs |
+| 平滑 2000 点(整笔,压力测试) | 328.5 µs |
+| **增量平滑每事件(2000 点笔画全程)** | **0.5 µs/事件(全程 0.91ms,比整笔快 ~399×)** |
+| 整笔重采样每事件(2000 点全程均值) | 182.7 µs/事件(全程 364.98ms) |
+| 门控 20 / 96 样本窗口 | 1.6 / 7.8 µs |
+| 预测 20 / 96 样本 → 33ms | 1.8 / 6.6 µs |
+| 胶囊命中 miss 200 / 2000 点 | 3.7 / 33.8 µs |
+| 采集追加到 2000 点笔画 | 10.7 µs |
+| 橡皮一帧:扫掠 20×200 点全 miss | 77.3 µs |
+
+**结论:满足每帧 <1ms。** 真实帧(200 点湿墨平滑 + 96 样本门控/预测 + 20×200 点橡皮扫掠)≈ **0.105ms**;开 `wetIncremental` 后 ≈ **0.092ms**;压力帧(2000 点整笔重采样)≈ **0.420ms**,增量模式下平滑项 329µs → 0.5µs。湿/干形状一致性由单测保证(非基准断言)。
+
+## 第四轮:离线回放评估(合成轨迹,2026-11-13)
+
+**⚠ 全部为合成轨迹**(确定性 mulberry32 种子 + 高斯噪声 0.6px,只加在采样上、真值精确),不代表真实笔迹;下表常数只作为 **iPad 实测的初值候选**,本轮未改任何默认常数。工具:
+
+```
+npx tsx experiments/2026-11-12-ink-prediction/replay.ts # 完整表格,输出已存档 replay-output.txt
+```
+
+- 轨迹(`src/ink/replay.ts`):直线 600px/s、快弧(r=25 v=600,写 e/圈的极端情形)、急转(直行 600ms 后 90°)、抖动(±60° 交替锯齿)、停笔(300ms 保持上报)、慢短笔(6px/500ms),各 60Hz 与 120Hz 两档。
+- 指标:在每次有足够历史的采样点上走与 Board 相同的门控+卡尔曼管线,预测尾**末端**与其自身时间戳上的精确真值比较 → errMean/errP95/errMax;过冲 = 误差在行进方向上的分量(+超前/−滞后);pred% = 门控放行占比。
+- 候选:A=现行默认(65/30/12,q=9e6,r=2,2 帧);B=更响应(55/25/10,q=2e6,r=1,1.5 帧);C=更激进(75/35/15,q=2.5e7,r=4,2.5 帧);D=更保守(55/25/14,q=4e6,r=2,1.5 帧)。
+
+各场景等权平均 errMean(完整逐场景表见 `replay-output.txt`):
+
+| 候选 | 60Hz | 120Hz |
+|---|---|---|
+| **A-现行默认** | 3.41px | 2.09px |
+| **B-更响应** | **2.70px** | **1.76px** |
+| C-更激进 | 3.45px | 3.05px |
+| D-更保守 | 2.86px | 2.04px |
+
+典型场景(errMean):快弧 60Hz A=11.3px vs C=10.2px(KF 速度在急弯上滞后是主项,过冲 −2~−6px 即"滞后于切线");急转 60Hz A errMax=28px vs B/D=21px;停笔 60Hz A errMax=20px(停笔瞬间尾甩出,1.5 帧候选减半);慢短笔全程 0% pred(idle 门控符合设计:不给刻意慢笔画外推)。
+
+**回放发现并修复的两个门控真问题**(属于 prediction 实验内部的噪声鲁棒性修复,常数默认值未动):
+1. 抖动翻转规则原本在**整个窗口**累计 ≥3 次 ≥10° 的变号转角——真实尺度的指针噪声让直线全程被判 jitter、预测完全失效;改为只看**最近 12 对**转角、需两侧 ≥ jitterTurnDeg/2 且 ≥3 次翻转。
+2. 曲线/直线判定原用窗口内**最大**转角——96 样本窗口的噪声几乎必然把最大值顶过阈值,直线永远读成"曲线";改用**中位数**转角(急转判定仍用最大值,单个大转角仍立即关断)。
+
+**结论**:B-更响应(更严门控 + 更低 q + 1.5 帧)在两类刷新率上都最优;"更多帧"(C)在弯曲轨迹上放大误差、不可取。120Hz 下直线 pred% 从 100%→58%(A),说明 idle/翻转阈值需要随刷新率与噪声自适应——列入 iPad 调参项,本轮不改。
+
+## iPad 实测步骤(两种方式,均临时启动、测完即停)
+
+### 方式 A:iPad 作为笔记本的外接手写屏(spacedesk / Duet Display 等)
+
+1. Windows 笔记本安装 spacedesk(免费)或 Duet Display,iPad 装对应 App,连接后 iPad 成为 Windows 扩展屏。
+2. Windows 浏览器打开 dev 页(先按方式 B 的第 1-2 步启动本地 dev,或直接 `npm run dev` 后访问 http://localhost:5173),把窗口拖到 iPad 那块屏。
+3. 用 Apple Pencil 在该屏书写。注意:转发软件通常把 Pencil 映射成 Windows 触摸/笔,**面板里先看 pointerType 实际是什么**(决定走哪档容差),且此类方案会引入额外传输延迟,手感结论只做参考,不与方式 B 横比。
+4. 测试完关闭转发软件。
+
+### 方式 B:iPad 浏览器访问局域网 dev 服务器(推荐:真实 PointerEvent 与延迟)
+
+1. Windows 上 `ipconfig` 查局域网 IPv4(下例 `192.168.1.23`),iPad 与笔记本同一 Wi-Fi。
+2. 临时启动(显式绑定该 IP,**不改 vite.config 默认值,不绑 0.0.0.0**):
+ `npm run dev -- --host 192.168.1.23`
+3. Windows 防火墙弹窗选"允许(专用网络)";iPad Safari 打开:
+ `http://192.168.1.23:5173/?ink-debug=1&ink-smooth=1&ink-predict=1&ink-ghost=1&ink-capsule=1&ink-tolerance=1&ink-wet-inc=1`
+4. **不要启动 `npm run mcp`,MCP 端点不暴露**;只跑这一个 dev 进程。
+5. 测完在笔记本 Ctrl+C 停掉服务器(不常驻、不写进任何配置)。
+
+### 手感验收清单(开着面板逐项看)
+
+1. **跟笔延迟**:预测开 vs 关画长直线/快弧线,墨迹前缘与笔尖的分离应明显减小;急转弯/停顿时预测应自动消失,不得出现"墨迹甩尾"(对应门控 sharp/jitter/idle)。
+2. **预测尾观感(新)**:`ink-ghost=1` 时预测尾应是半透明浅色独立路径、从笔尖伸出,与实墨明显可区分;关闭 ghost 时与实墨同色。两种观感各试快/慢笔画。
+3. **刷新率自适应(新)**:面板看"帧间隔 ≈ xx Hz";iPad(通常 60Hz)下预测尾约 2 帧长度,步长不再是固定 11ms 的颗粒感;急转/慢速时尾应收缩或消失。
+4. **平滑**:快速画锯齿线,毛刺减少;起笔/收笔端点仍在笔尖起止位置(端点精确保持)。
+5. **湿/干一致(新)**:`ink-wet-inc=1` 开关下画长笔画(尽量 1000+ 点),抬笔瞬间墨迹形状**不应有任何跳变**(增量与烘焙逐位一致);再对比关闭增量时画同样笔画,观感应相同。
+6. **点按 vs 短笔画(新)**:快速轻点 → 圆点;放慢速度画一条刻意短 tick(约 0.5s)→ 应保留为短笔画而不是被折叠成点(位移+时长双条件)。
+7. **橡皮**:快速横扫细线条,胶囊开时无漏擦;容差开关开时,手指擦除比鼠标明显更"宽容"(10 vs 3 DIP),笔居中(5 DIP)。
+8. **缩放**:2×/4× 放大后重复橡皮与轻点,屏幕手感应一致(阈值按缩放换算)。
+9. **压感**:面板显示"无压感(恒 0.5/0)"时笔画宽度不随力度变化;有真实压感的设备显示"真实压力"。
+10. **性能**:面板帧间隔 <16.7ms(60Hz)且 move 处理耗时 <1ms(基准显示 ~0.01-0.4ms);快速画超长笔画(2000+ 点)不卡顿,增量开启时尤其应平稳。
+11. **回归**:六个开关全关(或无参数的普通链接)时,书写/橡皮与 main 完全一致。
+
+## 未验证
+
+- iPad 实测(方式 A/B 均未在本会话执行——按约束不自动启动服务器);spacedesk/Duet 把 Apple Pencil 映射成哪种 pointerType 未知。
+- 真机手感:ghost 预测尾的透明度(0.4 为拍脑袋值)与宽笔观感、自适应步长在真实 60/120Hz 屏上的颗粒感、增量湿墨在 React 批处理下的实际表现。
+- 回放评估全部基于**合成轨迹**(高斯噪声、理想参数曲线):真实 Apple Pencil 采样噪声分布、压力、掌部抑制等未建模;候选常数(B/D 组)只是初值候选,未经真机验证。
+- rAF 刷新率估计在 iPad Safari(省电模式降帧)与后台切换时的行为(代码已 clamp,未实测)。
+- Firefox/Safari 的自研预测兜底在真实浏览器中的表现。
+- 打包体积/生产构建(按约束未跑);与同机 OCR 计时任务的相互干扰未测量。
+
+## 建议下一步
+
+1. 用方式 B 在 iPad 上跑一遍验收清单,按面板数字手调常数:`predict.ts`(门控角度、卡尔曼 q/r、`ADAPTIVE_FRAMES_AHEAD`)、`tolerance.ts` 三档与 `TAP_MAX_DURATION_MS`、ghost 的 opacity。回放结论支持从 **B-更响应** 组起步。
+2. 门控阈值随刷新率/噪声自适应(120Hz 回放显示直线被过度门控:idle 与翻转阈值应按帧间隔换算)。
+3. 若 ghost 观感成立,考虑给预测尾再加"长度随速度缩放"(快笔画更长、慢笔画更短)。
+4. 增量湿墨验证后,可把"湿墨分段增量重绘"进一步推进到 DOM 层(只更新新增 path 而非重建整个 StrokeShape),当前实现的收益主要在平滑计算,DOM 更新仍是整笔。
+5. 若采纳平滑/容差,把实验开关转为正式设置项并评估默认值(笔=开、触摸=保守)。
diff --git a/experiments/2026-11-12-ink-prediction/bench.ts b/experiments/2026-11-12-ink-prediction/bench.ts
new file mode 100644
index 0000000..c4676b7
--- /dev/null
+++ b/experiments/2026-11-12-ink-prediction/bench.ts
@@ -0,0 +1,115 @@
+/**
+ * Light micro-benchmark for the ink prototype modules (Node + tsx, single thread).
+ *
+ * npx tsx experiments/2026-11-12-ink-prediction/bench.ts
+ *
+ * Deliberately CPU-light (a few seconds total, no GPU, no build) — safe to run
+ * next to the OCR timing job. Numbers are per single call; the "frame budget"
+ * section adds up the calls one rendered frame would actually make.
+ */
+import { hitSweep } from '../../src/ink/capsule'
+import { gateSamples, predictTail, type InkSample } from '../../src/ink/predict'
+import { appendStrokePoint, createIncrementalSmooth, midpointBezierPolyline, updateIncrementalSmooth } from '../../src/ink/smooth'
+import type { Stroke } from '../../src/board/types'
+
+const now = () => performance.now()
+
+function bench(name: string, fn: () => unknown, minIter: number, budgetMs: number): number {
+ for (let i = 0; i < 5; i++) fn() // warmup
+ let iter = 0
+ const t0 = now()
+ let elapsed = 0
+ do {
+ fn()
+ iter++
+ elapsed = now() - t0
+ } while (elapsed < budgetMs || iter < minIter)
+ const perCallUs = (elapsed / iter) * 1000
+ console.log(`${name.padEnd(56)} ${perCallUs.toFixed(1).padStart(9)} µs/call (${String(iter)} iters)`)
+ return perCallUs
+}
+
+/** synthetic handwriting-ish stroke: gentle waves, flat [x, y, pressure, ...] */
+function makeStrokePts(n: number): number[] {
+ const pts: number[] = []
+ for (let i = 0; i < n; i++) {
+ const t = i / (n - 1 || 1)
+ pts.push(t * 800, 300 + Math.sin(t * Math.PI * 6) * 120 + Math.sin(t * Math.PI * 23) * 8, 0.5)
+ }
+ return pts
+}
+
+const strokeOf = (pts: number[]): Stroke => ({ id: 'bench', pts, color: '#000', width: 4, style: 'ink', createdAt: 0 })
+
+/** slightly curving drag, 8 ms sampling */
+function makeSamples(n: number): InkSample[] {
+ let x = 0
+ let y = 0
+ let heading = 0
+ return Array.from({ length: n }, (_, i) => {
+ heading += 0.03
+ x += Math.cos(heading) * 5.6
+ y += Math.sin(heading) * 5.6
+ return { x, y, t: 1000 + i * 8 }
+ })
+}
+
+console.log('--- ink prototype micro-benchmark (Node, single thread) ---')
+const pts200 = makeStrokePts(200)
+const pts2000 = makeStrokePts(2000)
+
+const tSmooth200 = bench('smooth: midpointBezierPolyline 200 pts (per wet frame)', () => midpointBezierPolyline(pts200), 50, 400)
+const tSmooth2000 = bench('smooth: midpointBezierPolyline 2000 pts (stress)', () => midpointBezierPolyline(pts2000), 20, 600)
+
+const samples20 = makeSamples(20)
+const samples96 = makeSamples(96)
+bench('predict: gateSamples (20-sample window)', () => gateSamples(samples20), 100, 200)
+const tGate96 = bench('predict: gateSamples (96-sample window = cap)', () => gateSamples(samples96), 100, 200)
+bench('predict: predictTail (20 samples → 33 ms)', () => predictTail(samples20, { horizonMs: 33 }), 100, 200)
+const tPredict96 = bench('predict: predictTail (96 samples → 33 ms)', () => predictTail(samples96, { horizonMs: 33 }), 100, 200)
+
+const stroke200 = strokeOf(pts200)
+const stroke2000 = strokeOf(pts2000)
+bench('eraser: hitSweep miss on 200-pt stroke', () => hitSweep(stroke200, -50, 500, -40, 520, 12), 100, 300)
+bench('eraser: hitSweep miss on 2000-pt stroke', () => hitSweep(stroke2000, -50, 500, -40, 520, 12), 20, 400)
+const hitX = pts2000[999 * 3]
+const hitY = pts2000[999 * 3 + 1]
+bench('eraser: hitSweep hit mid-stroke on 2000-pt stroke', () => hitSweep(stroke2000, hitX, hitY, hitX + 2, hitY + 2, 12), 20, 400)
+bench('capture: appendStrokePoint onto 2000-pt stroke', () => appendStrokePoint(pts2000, { x: 1e6, y: 1e6, pressure: 0.5 }, 0.5, 1), 100, 300)
+
+const docStrokes = Array.from({ length: 20 }, () => strokeOf(makeStrokePts(200)))
+const tEraseFrame = bench('eraser frame: sweep over 20 × 200-pt strokes (all miss)', () => {
+ for (const s of docStrokes) hitSweep(s, -50, 500, -40, 520, 12)
+}, 20, 400)
+
+console.log('\n--- wet-ink redraw: full resample vs incremental (2000-point stroke) ---')
+// model the Board: the pts array grows by one sample per pointer event and the
+// smoother reads it in place (no extra copying on either side)
+const fullPts: number[] = []
+const fullStart = now()
+for (let k = 1; k <= 2000; k++) {
+ fullPts.push(k, 300 + Math.sin(k / 200) * 100, 0.5)
+ if (k >= 3) midpointBezierPolyline(fullPts)
+}
+const fullMs = now() - fullStart
+const incPts: number[] = []
+const incState = createIncrementalSmooth()
+const incStart = now()
+for (let k = 1; k <= 2000; k++) {
+ incPts.push(k, 300 + Math.sin(k / 200) * 100, 0.5)
+ if (k >= 3) updateIncrementalSmooth(incState, incPts)
+}
+const incMs = now() - incStart
+const fullPerEventUs = (fullMs / 1998) * 1000
+const incPerEventUs = (incMs / 1998) * 1000
+console.log(`full resample every event: ${fullMs.toFixed(2)} ms total, ${fullPerEventUs.toFixed(1)} µs/event avg (last event ≈ ${tSmooth2000.toFixed(0)} µs)`)
+console.log(`incremental per event: ${incMs.toFixed(2)} ms total, ${incPerEventUs.toFixed(1)} µs/event avg (${(fullMs / Math.max(incMs, 0.001)).toFixed(0)}× faster)`)
+console.log(`wet/dry shape equality is asserted by unit tests, not here`)
+
+console.log('\n--- per-frame budget (target: < 1 ms) ---')
+const realistic = tSmooth200 + tGate96 + tPredict96 + tEraseFrame
+const stress = tSmooth2000 + tGate96 + tPredict96 + tEraseFrame
+const realisticInc = incPerEventUs + tGate96 + tPredict96 + tEraseFrame
+console.log(`realistic frame (200-pt live stroke) = ${(realistic / 1000).toFixed(3)} ms ${realistic < 1000 ? '✓ under budget' : '✗ over budget'}`)
+console.log(`realistic frame with wetIncremental = ${(realisticInc / 1000).toFixed(3)} ms ${realisticInc < 1000 ? '✓ under budget' : '✗ over budget'}`)
+console.log(`stress frame (2000-pt live stroke) = ${(stress / 1000).toFixed(3)} ms ${stress < 1000 ? '✓ under budget' : '✗ over budget'}`)
diff --git a/experiments/2026-11-12-ink-prediction/replay-output.txt b/experiments/2026-11-12-ink-prediction/replay-output.txt
new file mode 100644
index 0000000..28c897b
--- /dev/null
+++ b/experiments/2026-11-12-ink-prediction/replay-output.txt
@@ -0,0 +1,80 @@
+=== 墨迹预测离线回放评估(合成轨迹!仅供 iPad 实测初值候选;默认值未改) ===
+噪声: 高斯 0.6px(仅加在采样上,真值精确);窗口 96 样本;绝对时程上限 36ms;预测起点 = 第 8 个样本
+
+───────── 60Hz(帧间隔 16.7ms)─────────
+场景 │ 候选 │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后)
+直线 │ A-现行默认 │ 100% │ 1.1px │ 1.9px │ 2.4px │ +0.13px
+直线 │ B-更响应 │ 100% │ 0.8px │ 1.5px │ 1.8px │ +0.12px
+直线 │ C-更激进 │ 100% │ 1.2px │ 2.1px │ 2.6px │ +0.13px
+直线 │ D-更保守 │ 100% │ 0.8px │ 1.5px │ 1.8px │ +0.12px
+
+快弧(小半径) │ A-现行默认 │ 100% │ 11.3px │ 12.6px │ 12.6px │ -2.29px
+快弧(小半径) │ B-更响应 │ 100% │ 9.9px │ 10.8px │ 10.9px │ -5.21px
+快弧(小半径) │ C-更激进 │ 100% │ 10.2px │ 11.5px │ 11.6px │ -1.35px
+快弧(小半径) │ D-更保守 │ 100% │ 9.9px │ 10.8px │ 10.9px │ -5.21px
+
+急转 │ A-现行默认 │ 55% │ 2.5px │ 14.8px │ 28.0px │ +1.27px
+急转 │ B-更响应 │ 55% │ 1.7px │ 7.5px │ 21.1px │ +0.93px
+急转 │ C-更激进 │ 55% │ 2.6px │ 14.8px │ 28.0px │ +1.27px
+急转 │ D-更保守 │ 55% │ 1.7px │ 7.5px │ 21.1px │ +0.92px
+
+抖动 │ A-现行默认 │ 100% │ 3.2px │ 6.7px │ 7.3px │ +0.02px
+抖动 │ B-更响应 │ 100% │ 2.2px │ 4.7px │ 5.3px │ -0.16px
+抖动 │ C-更激进 │ 100% │ 4.3px │ 7.7px │ 8.7px │ +0.49px
+抖动 │ D-更保守 │ 100% │ 3.0px │ 5.0px │ 5.3px │ +0.01px
+
+停笔 │ A-现行默认 │ 32% │ 2.4px │ 10.9px │ 20.1px │ +1.45px
+停笔 │ B-更响应 │ 32% │ 1.6px │ 5.6px │ 15.1px │ +1.03px
+停笔 │ C-更激进 │ 32% │ 2.4px │ 11.0px │ 20.0px │ +1.45px
+停笔 │ D-更保守 │ 32% │ 1.7px │ 5.6px │ 15.1px │ +1.02px
+
+慢短笔 │ A-现行默认 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ C-更激进 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+
+ [60Hz 汇总 | 各场景等权平均 errMean]
+ A-现行默认 3.41px
+ B-更响应 2.70px
+ C-更激进 3.45px
+ D-更保守 2.86px
+
+───────── 120Hz(帧间隔 8.3ms)─────────
+场景 │ 候选 │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后)
+直线 │ A-现行默认 │ 58% │ 0.6px │ 1.2px │ 1.7px │ +0.04px
+直线 │ B-更响应 │ 35% │ 0.5px │ 0.9px │ 1.0px │ +0.17px
+直线 │ C-更激进 │ 69% │ 0.7px │ 1.3px │ 2.1px │ +0.02px
+直线 │ D-更保守 │ 35% │ 0.5px │ 1.0px │ 1.2px │ +0.19px
+
+快弧(小半径) │ A-现行默认 │ 100% │ 8.5px │ 9.3px │ 11.8px │ -4.01px
+快弧(小半径) │ B-更响应 │ 82% │ 9.2px │ 10.0px │ 11.0px │ -6.35px
+快弧(小半径) │ C-更激进 │ 100% │ 13.0px │ 15.2px │ 15.4px │ -3.31px
+快弧(小半径) │ D-更保守 │ 82% │ 10.4px │ 14.4px │ 14.5px │ -6.74px
+
+急转 │ A-现行默认 │ 32% │ 0.7px │ 1.0px │ 7.9px │ +0.17px
+急转 │ B-更响应 │ 16% │ 0.4px │ 0.6px │ 0.6px │ +0.09px
+急转 │ C-更激进 │ 40% │ 1.4px │ 4.7px │ 18.8px │ +0.51px
+急转 │ D-更保守 │ 16% │ 0.4px │ 0.7px │ 0.7px │ +0.09px
+
+抖动 │ A-现行默认 │ 30% │ 2.0px │ 3.2px │ 3.3px │ -0.20px
+抖动 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+抖动 │ C-更激进 │ 66% │ 2.0px │ 3.2px │ 3.2px │ -0.35px
+抖动 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+
+停笔 │ A-现行默认 │ 23% │ 0.7px │ 1.0px │ 4.4px │ +0.17px
+停笔 │ B-更响应 │ 12% │ 0.5px │ 2.1px │ 2.1px │ +0.22px
+停笔 │ C-更激进 │ 26% │ 1.2px │ 6.8px │ 11.7px │ +0.61px
+停笔 │ D-更保守 │ 12% │ 0.9px │ 7.0px │ 7.0px │ +0.63px
+
+慢短笔 │ A-现行默认 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ C-更激进 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+慢短笔 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px
+
+ [120Hz 汇总 | 各场景等权平均 errMean]
+ A-现行默认 2.09px
+ B-更响应 1.76px
+ C-更激进 3.05px
+ D-更保守 2.04px
+
+提醒:以上均为合成轨迹上的离线数字;候选常数只在 iPad 真机手感验证后才可能被采纳,本轮未改任何默认值。
diff --git a/experiments/2026-11-12-ink-prediction/replay.ts b/experiments/2026-11-12-ink-prediction/replay.ts
new file mode 100644
index 0000000..9e25a43
--- /dev/null
+++ b/experiments/2026-11-12-ink-prediction/replay.ts
@@ -0,0 +1,51 @@
+/**
+ * Replay-eval runner: synthetic trajectories × candidate constant sets → table.
+ *
+ * npx tsx experiments/2026-11-12-ink-prediction/replay.ts
+ *
+ * ⚠ 全部为合成轨迹(高斯噪声 ≠ 真实笔迹)。结果只作为 iPad 实测的初值候选,
+ * 本工具不修改任何默认常数。
+ */
+import { makeTrajectory, replayTrajectory, SCENARIO_LABELS, type ReplayCandidate, type TrajectoryScenario } from '../../src/ink/replay'
+
+const SCENARIOS: TrajectoryScenario[] = ['straight', 'fastArc', 'sharpTurn', 'jitter', 'pause', 'slowTick']
+const RATES = [60, 120]
+
+const CANDIDATES: ReplayCandidate[] = [
+ { name: 'A-现行默认' }, // gate 65/30/12, KF q=9e6 r=2, 2 frames ahead
+ { name: 'B-更响应', gate: { sharpTurnDeg: 55, jitterTurnDeg: 25, curveTurnDeg: 10 }, qAcc: 2e6, measVar: 1, framesAhead: 1.5 },
+ { name: 'C-更激进', gate: { sharpTurnDeg: 75, jitterTurnDeg: 35, curveTurnDeg: 15 }, qAcc: 2.5e7, measVar: 4, framesAhead: 2.5 },
+ { name: 'D-更保守', gate: { sharpTurnDeg: 55, jitterTurnDeg: 25, curveTurnDeg: 14 }, qAcc: 4e6, measVar: 2, framesAhead: 1.5 },
+]
+
+console.log('=== 墨迹预测离线回放评估(合成轨迹!仅供 iPad 实测初值候选;默认值未改) ===')
+console.log('噪声: 高斯 0.6px(仅加在采样上,真值精确);窗口 96 样本;绝对时程上限 36ms;预测起点 = 第 8 个样本\n')
+
+for (const rateHz of RATES) {
+ console.log(`───────── ${rateHz}Hz(帧间隔 ${(1000 / rateHz).toFixed(1)}ms)─────────`)
+ console.log(
+ `${'场景'.padEnd(10)} │ ${'候选'.padEnd(11)} │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后)`,
+ )
+ for (const scenario of SCENARIOS) {
+ const traj = makeTrajectory(scenario, { rateHz, noisePx: 0.6, seed: 42 })
+ for (const cand of CANDIDATES) {
+ const s = replayTrajectory(traj, cand, rateHz)
+ const predPct = s.moments ? ((s.predicted / s.moments) * 100).toFixed(0).padStart(3) : ' 0'
+ console.log(
+ `${SCENARIO_LABELS[scenario].padEnd(9)} │ ${cand.name.padEnd(11)} │ ${predPct}% │ ${s.meanErr.toFixed(1).padStart(6)}px │ ${s.p95Err
+ .toFixed(1)
+ .padStart(5)}px │ ${s.maxErr.toFixed(1).padStart(5)}px │ ${(s.meanOvershoot >= 0 ? '+' : '') + s.meanOvershoot.toFixed(2)}px`,
+ )
+ }
+ console.log('')
+ }
+ // grand summary per candidate: mean err across scenarios (equal weight)
+ console.log(` [${rateHz}Hz 汇总 | 各场景等权平均 errMean]`)
+ for (const cand of CANDIDATES) {
+ const means = SCENARIOS.map((sc) => replayTrajectory(makeTrajectory(sc, { rateHz, noisePx: 0.6, seed: 42 }), cand, rateHz).meanErr)
+ const grand = means.reduce((a, b) => a + b, 0) / means.length
+ console.log(` ${cand.name.padEnd(11)} ${grand.toFixed(2)}px`)
+ }
+ console.log('')
+}
+console.log('提醒:以上均为合成轨迹上的离线数字;候选常数只在 iPad 真机手感验证后才可能被采纳,本轮未改任何默认值。')
diff --git a/src/App.tsx b/src/App.tsx
index 32c5900..c1e1fc7 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -25,6 +25,8 @@ import { pageGroups } from '@/math/page'
import { summarizeCard } from '@/math/scene'
import { parseCard } from '@/math/statements'
import { clusterStrokes, mockRecognizer, OCR_ACCEPT } from '@/ocr/recognizer'
+import { InkDebugPanel } from '@/ink/InkDebugPanel'
+import { inkFlagsStore, shouldShowDebugPanel } from '@/ink/flags'
import { PlotButton } from '@/plot/PlotButton'
import { PlotPanel } from '@/plot/PlotPanel'
import { PlotPane } from '@/plot/PlotPane'
@@ -470,6 +472,8 @@ export default function App() {
const floated = plot.open && !plot.details && !plot.full
const docked = plot.open && plot.details && !plot.full && !compact
const modal = plot.open && (plot.full || (plot.details && compact))
+ // ink debug panel: ?ink-debug=1 (or a dev build with any ink experiment on) — production never shows it
+ const inkDebugVisible = shouldShowDebugPanel(window.location.search, import.meta.env.DEV, inkFlagsStore.get())
return (
@@ -515,6 +519,8 @@ export default function App() {
+ {inkDebugVisible && }
+
(null)
const lastErase = useRef<{ x: number; y: number } | null>(null)
+ // ink-feel experiment switches — all opt-in, off by default (see src/ink/flags.ts);
+ // live via the flags store so the debug panel can toggle them mid-stroke
+ const flags = useSyncExternalStore(inkFlagsStore.subscribe, inkFlagsStore.get)
+ const [predTail, setPredTail] = useState([])
+ const samplesRef = useRef([])
+ const pointerTypeRef = useRef('mouse')
+ const [wetPts, setWetPts] = useState(null)
+ const incSmoothRef = useRef(null)
+ const frameMsRef = useRef(ADAPTIVE_DEFAULT_FRAME_MS)
const toWorld = useCallback((cx: number, cy: number) => {
const r = ref.current!.getBoundingClientRect()
@@ -73,9 +104,13 @@ export function Board(props: Props) {
mode.current = null
active.current = null
pointers.current.clear()
+ samplesRef.current = []
+ incSmoothRef.current = null
if (!busy) return
setLive(null)
setErasing(new Set())
+ setPredTail([])
+ setWetPts(null)
}, [])
useEffect(() => {
@@ -130,6 +165,22 @@ export function Board(props: Props) {
return () => window.removeEventListener('blur', onBlur)
}, [abortLive])
+ // estimate the display refresh from rAF deltas so the prediction step/horizon
+ // can scale with the panel (only runs while the prediction experiment is on)
+ useEffect(() => {
+ if (!flags.prediction) return
+ let raf = 0
+ let last = performance.now()
+ const loop = (t: number) => {
+ const d = t - last
+ last = t
+ if (d > 0 && d < 100) frameMsRef.current = frameMsRef.current * 0.8 + d * 0.2
+ raf = requestAnimationFrame(loop)
+ }
+ raf = requestAnimationFrame(loop)
+ return () => cancelAnimationFrame(raf)
+ }, [flags.prediction])
+
// a lone dot waits a moment before it is inked, so the two clicks of a double-click leave no marks
const pendingDots = useRef<{ s: Stroke; t: ReturnType }[]>([])
const [dots, setDots] = useState([])
@@ -137,14 +188,29 @@ export function Board(props: Props) {
const s = liveRef.current
liveRef.current = null
setLive(null)
+ samplesRef.current = []
+ incSmoothRef.current = null
+ if (predTail.length) setPredTail([]) // predicted points are display-only, never saved
+ if (wetPts) setWetPts(null)
if (!s || s.pts.length < 3) return
- if (s.pts.length > 3) return props.onAddStroke(s)
+ let stroke = s
+ // pointer-tolerance experiment: a quick press whose whole gesture stays
+ // within the per-type drag threshold (÷ zoom) is a tap — collapse it to the
+ // pen-down point. Slow deliberate ticks keep their (short) stroke.
+ if (flags.pointerTolerance && stroke.pts.length > 3 && isTapStroke(stroke.pts, dragThresholdWorld(toPointerKind(pointerTypeRef.current), viewRef.current.scale), Date.now() - stroke.createdAt)) {
+ stroke = { ...stroke, pts: [stroke.pts[0], stroke.pts[1], stroke.pts[2]] }
+ }
+ // bake the midpoint-Bézier smoothing into the saved stroke (dots and
+ // two-point strokes come back unchanged from midpointBezierPolyline)
+ const smooth = flags.smoothing ? midpointBezierPolyline(stroke.pts) : stroke.pts
+ const final = smooth === stroke.pts ? stroke : { ...stroke, pts: smooth }
+ if (final.pts.length > 3) return props.onAddStroke(final)
const t = setTimeout(() => {
- pendingDots.current = pendingDots.current.filter((d) => d.s !== s)
+ pendingDots.current = pendingDots.current.filter((d) => d.s !== final)
setDots(pendingDots.current.map((d) => d.s))
- props.onAddStroke(s)
+ props.onAddStroke(final)
}, 320)
- pendingDots.current.push({ s, t })
+ pendingDots.current.push({ s: final, t })
setDots(pendingDots.current.map((d) => d.s))
}
const dropDots = () => {
@@ -161,9 +227,14 @@ export function Board(props: Props) {
if (ids.length) props.onErase(ids)
}
+ // eraser radius: main's eraserWorldRadius, or the per-pointer-type hit
+ // tolerance (DIP ÷ zoom) under the pointerTolerance experiment
+ const eraseRadius = () =>
+ flags.pointerTolerance ? hitToleranceWorld(toPointerKind(pointerTypeRef.current), viewRef.current.scale) : eraserWorldRadius(viewRef.current.scale)
+
const eraseAt = (cx: number, cy: number) => {
const w = toWorld(cx, cy)
- const r = eraserWorldRadius(viewRef.current.scale)
+ const r = eraseRadius()
const prev = lastErase.current
lastErase.current = w
let changed = false
@@ -186,8 +257,65 @@ export function Board(props: Props) {
}
}
+ // capsule the eraser swept through since the previous position, so fast motion
+ // cannot skip over a stroke the point test would miss
+ const eraseSweep = (x0: number, y0: number, x1: number, y1: number) => {
+ const r = eraseRadius()
+ let changed = false
+ for (const s of doc.strokes) {
+ if (!erasingRef.current.has(s.id) && hitSweep(s, x0, y0, x1, y1, r)) {
+ erasingRef.current.add(s.id)
+ changed = true
+ }
+ }
+ if (changed) setErasing(new Set(erasingRef.current))
+ }
+
+ /** display-only extrapolated tail for the live stroke; never touches the stroke data */
+ const updatePrediction = (e: React.PointerEvent, list: PointerEvent[]): number => {
+ const hist = samplesRef.current
+ for (const ev of list) {
+ const last = hist[hist.length - 1]
+ if (ev.timeStamp >= (last ? last.t : -Infinity)) hist.push({ x: ev.clientX, y: ev.clientY, t: ev.timeStamp })
+ }
+ if (hist.length > PREDICTION_HISTORY_CAP) hist.splice(0, hist.length - PREDICTION_HISTORY_CAP)
+ const gate = gateSamples(hist)
+ let screen: { x: number; y: number }[] = []
+ let source: InkDebugStats['predictedSource'] = 'off'
+ if (gate.predict) {
+ const native = nativePredictedTail(e.nativeEvent).map((p) => ({ x: p.clientX, y: p.clientY }))
+ if (native.length) {
+ screen = native
+ source = 'native'
+ } else {
+ // step/horizon scale with the display's frame interval (rAF estimate),
+ // absolute cap preserved inside predictTail
+ const adapt = frameAdaptivePrediction(frameMsRef.current)
+ const horizon = gate.verdict === 'curve' ? adapt.curveHorizonMs : adapt.horizonMs
+ screen = predictTail(hist, { horizonMs: horizon, stepMs: adapt.stepMs }).map((s) => ({ x: s.x, y: s.y }))
+ source = 'self'
+ }
+ }
+ inkDebugStats.predictedCount = screen.length
+ inkDebugStats.predictedSource = source
+ if (!screen.length || !liveRef.current) {
+ if (predTail.length) setPredTail([])
+ return screen.length
+ }
+ const pressure = liveRef.current.pts[liveRef.current.pts.length - 1] ?? 0.5
+ const flat: number[] = []
+ for (const p of screen) {
+ const w = toWorld(p.x, p.y)
+ flat.push(w.x, w.y, pressure)
+ }
+ setPredTail(flat)
+ return screen.length
+ }
+
const onPointerDown = (e: React.PointerEvent) => {
if ((e.target as HTMLElement).closest('[data-no-board]')) return
+ pointerTypeRef.current = e.pointerType
+ inkDebugStats.pointerType = e.pointerType
if (e.pointerType === 'pen' && !penSeen.current) {
penSeen.current = true
props.onPenDetected()
@@ -203,6 +331,9 @@ export function Board(props: Props) {
erasingRef.current = new Set()
setErasing(new Set())
lastErase.current = null
+ incSmoothRef.current = null
+ if (predTail.length) setPredTail([])
+ if (wetPts) setWetPts(null)
const [a, b] = touches
pinch.current = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, view: viewRef.current }
mode.current = { kind: 'pinch' }
@@ -230,7 +361,8 @@ export function Board(props: Props) {
capture(e)
active.current = e.pointerId
if (tool === 'eraser') {
- mode.current = { kind: 'erase' }
+ const w = toWorld(e.clientX, e.clientY)
+ mode.current = { kind: 'erase', lx: w.x, ly: w.y }
lastErase.current = null
eraseAt(e.clientX, e.clientY)
return
@@ -246,6 +378,9 @@ export function Board(props: Props) {
}
liveRef.current = s
setLive(s)
+ incSmoothRef.current = null
+ if (wetPts) setWetPts(null)
+ if (flags.prediction) samplesRef.current = [{ x: e.clientX, y: e.clientY, t: e.nativeEvent.timeStamp }]
mode.current = { kind: 'draw' }
}
@@ -280,26 +415,50 @@ export function Board(props: Props) {
return
}
if (m.kind === 'erase') {
- const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : []
- const list = evs.length ? evs : [e.nativeEvent]
- for (const ev of list) eraseAt(ev.clientX, ev.clientY)
+ if (flags.capsuleEraser) {
+ const w = toWorld(e.clientX, e.clientY)
+ eraseSweep(m.lx, m.ly, w.x, w.y)
+ m.lx = w.x
+ m.ly = w.y
+ } else {
+ const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : []
+ const list = evs.length ? evs : [e.nativeEvent]
+ for (const ev of list) eraseAt(ev.clientX, ev.clientY)
+ }
return
}
if (m.kind === 'draw' && liveRef.current) {
+ const t0 = performance.now()
const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : []
const list = evs.length ? evs : [e.nativeEvent]
- const pts = liveRef.current.pts.slice()
+ // flags off → the exact main behaviour: looser 0.8 px near-point threshold, no prediction
+ const minDist = flags.smoothing ? SMOOTH_MIN_DIST_DIP : 0.8
+ let pts = liveRef.current.pts.slice()
for (const ev of list) {
const w = toWorld(ev.clientX, ev.clientY)
- const lx = pts[pts.length - 3]
- const ly = pts[pts.length - 2]
- if (Math.hypot(w.x - lx, w.y - ly) * viewRef.current.scale < 0.8) continue
- pts.push(w.x, w.y, ev.pointerType === 'pen' ? ev.pressure || 0.5 : 0.5)
+ pts = appendStrokePoint(pts, { x: w.x, y: w.y, pressure: ev.pointerType === 'pen' ? ev.pressure || 0.5 : 0.5 }, minDist, viewRef.current.scale)
}
const next = { ...liveRef.current, pts }
liveRef.current = next
// A deferred pointermove must not resurrect a stroke that an interruption already dropped.
setLive(() => (liveRef.current === next ? next : null))
+ // wet-ink incremental redraw: extend the cached smooth polyline by the one
+ // newly-final segment instead of resampling the whole stroke per frame
+ if (flags.smoothing && flags.wetIncremental) {
+ const st = incSmoothRef.current ?? (incSmoothRef.current = createIncrementalSmooth())
+ updateIncrementalSmooth(st, pts)
+ setWetPts(st.pts)
+ } else if (wetPts) {
+ setWetPts(null)
+ }
+ if (flags.prediction) updatePrediction(e, list)
+ else if (predTail.length) setPredTail([])
+ // debug-panel bookkeeping (hidden unless ?ink-debug=1; no behaviour change)
+ inkDebugStats.nativePredicted = typeof e.nativeEvent.getPredictedEvents === 'function'
+ inkDebugStats.hasPressure = hasRealPressure(liveRef.current.pts)
+ inkDebugStats.strokePoints = liveRef.current.pts.length / 3
+ inkDebugStats.handlerMs = performance.now() - t0
+ inkDebugStats.lastMoveAt = t0
}
}
@@ -343,6 +502,21 @@ export function Board(props: Props) {
}
const drawing = tool === 'pen' || tool === 'marker' || tool === 'eraser'
+ // wet-ink display: smoothing and the predicted tail are overlays on the live
+ // stroke only — they never mutate liveRef, which is what gets saved
+ const PREDICTION_GHOST_OPACITY = 0.4
+ const wetBase = live ? (flags.smoothing ? (flags.wetIncremental && wetPts ? wetPts : midpointBezierPolyline(live.pts)) : live.pts) : null
+ const liveDisplay = (() => {
+ if (!live || wetBase == null) return null
+ const merged = flags.prediction && predTail.length && !flags.predictionGhost
+ if (!merged) return wetBase === live.pts ? live : { ...live, pts: wetBase }
+ return { ...live, pts: [...wetBase, ...predTail] }
+ })()
+ // ghost tail: the prediction rendered as its own translucent path, starting at the stroke tip
+ const tailDisplay = (() => {
+ if (!live || wetBase == null || !flags.prediction || !flags.predictionGhost || !predTail.length) return null
+ return { ...live, pts: predictionTailPath(wetBase, predTail) }
+ })()
const fingerSelects = penOnly || penSeen.current
const passThrough = useCallback(
(e: React.PointerEvent) => (drawing || space) && !(e.pointerType === 'touch' && fingerSelects),
@@ -413,7 +587,12 @@ export function Board(props: Props) {
{dots.map((s) => (
))}
- {live && }
+ {liveDisplay && }
+ {tailDisplay && (
+
+
+
+ )}
diff --git a/src/ink/InkDebugPanel.tsx b/src/ink/InkDebugPanel.tsx
new file mode 100644
index 0000000..3f49fef
--- /dev/null
+++ b/src/ink/InkDebugPanel.tsx
@@ -0,0 +1,87 @@
+import { useEffect, useState, useSyncExternalStore } from 'react'
+import { inkDebugStats } from './debug'
+import { inkFlagsStore, type InkFlags } from './flags'
+
+/**
+ * Opt-in debug panel for the ink-feel experiments — toggles the flags live and
+ * shows pointer/prediction/frame info. Never rendered unless
+ * `shouldShowDebugPanel()` says so: `?ink-debug=1`, or a dev build with any
+ * experiment switched on. Production without the parameter never sees it.
+ */
+
+const SWITCHES: { key: keyof InkFlags; label: string }[] = [
+ { key: 'smoothing', label: '平滑(去近点+中点贝塞尔)' },
+ { key: 'prediction', label: '预测显示' },
+ { key: 'predictionGhost', label: '预测尾浅色渲染' },
+ { key: 'capsuleEraser', label: '扫掠胶囊橡皮' },
+ { key: 'pointerTolerance', label: '按指针类型容差' },
+ { key: 'wetIncremental', label: '湿墨增量重绘' },
+]
+
+const Row = ({ k, v }: { k: string; v: string }) => (
+
+ {k}
+ {v}
+
+)
+
+export function InkDebugPanel() {
+ const flags = useSyncExternalStore(inkFlagsStore.subscribe, inkFlagsStore.get)
+ const [snap, setSnap] = useState(() => ({ ...inkDebugStats }))
+ const [frameMs, setFrameMs] = useState(0)
+
+ useEffect(() => {
+ const poll = setInterval(() => setSnap({ ...inkDebugStats }), 250)
+ // frame interval measured on the panel's own rAF — same display pipeline as the board
+ let raf = 0
+ let last = performance.now()
+ let acc = 0
+ let n = 0
+ const loop = (t: number) => {
+ acc += t - last
+ last = t
+ if (++n >= 30) {
+ setFrameMs(acc / n)
+ acc = 0
+ n = 0
+ }
+ raf = requestAnimationFrame(loop)
+ }
+ raf = requestAnimationFrame(loop)
+ return () => {
+ clearInterval(poll)
+ cancelAnimationFrame(raf)
+ }
+ }, [])
+
+ return (
+
+
墨迹实验面板(?ink-debug=1)
+
+ {SWITCHES.map(({ key, label }) => (
+
+ ))}
+
+
+
+
+
+
+
+ 0 ? ` ≈ ${(1000 / frameMs).toFixed(0)} Hz` : ''}`} />
+
+
+
+ )
+}
diff --git a/src/ink/capsule.test.ts b/src/ink/capsule.test.ts
new file mode 100644
index 0000000..995c1eb
--- /dev/null
+++ b/src/ink/capsule.test.ts
@@ -0,0 +1,60 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { hitSweep, segSegDist2 } from './capsule'
+import type { Stroke } from '@/board/types'
+
+const strokeOf = (pts: number[], width = 4, style: Stroke['style'] = 'ink'): Stroke => ({
+ id: 's1',
+ pts,
+ color: '#000',
+ width,
+ style,
+ createdAt: 0,
+})
+
+test('capsule catches what the point test misses during fast motion', () => {
+ // a vertical stroke at x=100 (the same segment-distance rule the main eraser
+ // applies per pointer event, tested from the two event positions)
+ const stroke = strokeOf([100, 0, 0.5, 100, 200, 0.5])
+ const r = 12
+ const e1 = { x: 40, y: 50 }
+ const e2 = { x: 160, y: 50 }
+ // both pointer events sit 60 px away from the stroke → point tests miss
+ assert.ok(segSegDist2(e1, e1, { x: 100, y: 0 }, { x: 100, y: 200 }) > r * r)
+ assert.ok(segSegDist2(e2, e2, { x: 100, y: 0 }, { x: 100, y: 200 }) > r * r)
+ // the swept capsule between them crosses the stroke → hit
+ assert.equal(hitSweep(stroke, e1.x, e1.y, e2.x, e2.y, r), true)
+})
+
+test('capsule degenerates to a disc for a stationary eraser', () => {
+ const stroke = strokeOf([0, 0, 0.5, 50, 0, 0.5])
+ // tip 13 px above the line: radius 12 (+3.2 width pad → 15.2) → hit; radius 8 (+3.2 → 11.2) → miss
+ assert.equal(hitSweep(stroke, 25, 13, 25, 13, 12), true)
+ assert.equal(hitSweep(stroke, 25, 13, 25, 13, 8), false)
+})
+
+test('capsule keeps the same width padding as hitStroke', () => {
+ // vertical stroke at x=100, radius 12 → ink pad = 4*0.8 = 3.2 → reach 15.2
+ const ink = strokeOf([100, 0, 0.5, 100, 100, 0.5], 4, 'ink')
+ assert.equal(hitSweep(ink, 85, 10, 85, 90, 12), true) // 15 ≤ 15.2
+ assert.equal(hitSweep(ink, 84, 10, 84, 90, 12), false) // 16 > 15.2
+ // marker pad = 10*2.5 = 25 → reach 37
+ const marker = strokeOf([100, 0, 0.5, 100, 100, 0.5], 10, 'marker')
+ assert.equal(hitSweep(marker, 64, 10, 64, 90, 12), true) // 36 ≤ 37
+ assert.equal(hitSweep(marker, 62, 10, 62, 90, 12), false) // 38 > 37
+})
+
+test('capsule hits single-point strokes and later segments', () => {
+ const dot = strokeOf([500, 500, 0.5])
+ assert.equal(hitSweep(dot, 495, 495, 494, 494, 12), true)
+ const multi = strokeOf([0, 0, 0.5, 30, 30, 0.5, 60, 0, 0.5])
+ // sweep passing only over the second segment
+ assert.equal(hitSweep(multi, 40, 5, 50, 5, 12), true)
+ // well below the V shape → no segment within reach (width 4 → reach 9.2)
+ assert.equal(hitSweep(multi, 45, 40, 55, 40, 6), false)
+})
+
+test('capsule: empty stroke never hits', () => {
+ assert.equal(hitSweep(strokeOf([]), 0, 0, 50, 50, 12), false)
+})
diff --git a/src/ink/capsule.ts b/src/ink/capsule.ts
new file mode 100644
index 0000000..bbc4e7a
--- /dev/null
+++ b/src/ink/capsule.ts
@@ -0,0 +1,82 @@
+/**
+ * Swept-capsule eraser hit testing — pure functions.
+ *
+ * Idea learned from studying established whiteboards (not their code): test the
+ * capsule the eraser swept through since the previous pointer position, not just
+ * the point it sits on now, so fast motion cannot skip over a stroke.
+ */
+import type { Stroke } from '@/board/types'
+
+export interface Pt {
+ x: number
+ y: number
+}
+
+const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v)
+
+/** Squared distance between segments p1p2 and q1q2; degenerate segments count as points. */
+export function segSegDist2(p1: Pt, p2: Pt, q1: Pt, q2: Pt): number {
+ const d1x = p2.x - p1.x
+ const d1y = p2.y - p1.y
+ const d2x = q2.x - q1.x
+ const d2y = q2.y - q1.y
+ const rx = p1.x - q1.x
+ const ry = p1.y - q1.y
+ const a = d1x * d1x + d1y * d1y
+ const e = d2x * d2x + d2y * d2y
+ const f = d2x * rx + d2y * ry
+ let s: number
+ let t: number
+ if (a <= 1e-12 && e <= 1e-12) {
+ s = 0
+ t = 0
+ } else if (a <= 1e-12) {
+ s = 0
+ t = clamp01(f / e)
+ } else {
+ const c = d1x * rx + d1y * ry
+ if (e <= 1e-12) {
+ t = 0
+ s = clamp01(-c / a)
+ } else {
+ const b = d1x * d2x + d1y * d2y
+ const denom = a * e - b * b
+ s = denom > 1e-12 ? clamp01((b * f - c * e) / denom) : 0
+ t = (b * s + f) / e
+ if (t < 0) {
+ t = 0
+ s = clamp01(-c / a)
+ } else if (t > 1) {
+ t = 1
+ s = clamp01((b - c) / a)
+ }
+ }
+ }
+ const cx = p1.x + s * d1x - (q1.x + t * d2x)
+ const cy = p1.y + s * d1y - (q1.y + t * d2y)
+ return cx * cx + cy * cy
+}
+
+/** Same width padding rule as hitStroke() in board/strokes.tsx. */
+const sweepPad = (s: Stroke) => s.width * (s.style === 'marker' || s.style === 'washi' ? 2.5 : 0.8)
+
+/**
+ * Does the capsule swept from (x0,y0) to (x1,y1) with radius r touch the stroke?
+ * A stationary test (x0==x1, y0==y1) degenerates to the usual disc check.
+ */
+export function hitSweep(s: Stroke, x0: number, y0: number, x1: number, y1: number, r: number): boolean {
+ const rr = r + sweepPad(s)
+ const r2 = rr * rr
+ const p = s.pts
+ const n = p.length / 3
+ if (n === 0) return false
+ const a1: Pt = { x: x0, y: y0 }
+ const a2: Pt = { x: x1, y: y1 }
+ if (n === 1) return segSegDist2(a1, a2, { x: p[0], y: p[1] }, { x: p[0], y: p[1] }) <= r2
+ for (let i = 0; i < n - 1; i++) {
+ const b1: Pt = { x: p[i * 3], y: p[i * 3 + 1] }
+ const b2: Pt = { x: p[(i + 1) * 3], y: p[(i + 1) * 3 + 1] }
+ if (segSegDist2(a1, a2, b1, b2) <= r2) return true
+ }
+ return false
+}
diff --git a/src/ink/debug.ts b/src/ink/debug.ts
new file mode 100644
index 0000000..24b315c
--- /dev/null
+++ b/src/ink/debug.ts
@@ -0,0 +1,33 @@
+/**
+ * Shared scratchpad the Board writes and the (opt-in) ink debug panel reads.
+ * Deliberately a plain mutable object — the panel polls it, so pointer-move
+ * handling never triggers extra React renders for debug bookkeeping.
+ */
+export interface InkDebugStats {
+ /** pointerType of the last board pointer event */
+ pointerType: string
+ /** does the current stroke carry any real pressure (vs constant 0.5/0) */
+ hasPressure: boolean
+ /** is PointerEvent.getPredictedEvents available in this browser */
+ nativePredicted: boolean
+ /** predicted points shown for the last move, and where they came from */
+ predictedCount: number
+ predictedSource: 'off' | 'native' | 'self'
+ /** Board pointer-move handling cost for the last draw move (ms) */
+ handlerMs: number
+ /** samples in the live stroke */
+ strokePoints: number
+ /** performance.now() of the last recorded move */
+ lastMoveAt: number
+}
+
+export const inkDebugStats: InkDebugStats = {
+ pointerType: '',
+ hasPressure: false,
+ nativePredicted: false,
+ predictedCount: 0,
+ predictedSource: 'off',
+ handlerMs: 0,
+ strokePoints: 0,
+ lastMoveAt: 0,
+}
diff --git a/src/ink/flags.test.ts b/src/ink/flags.test.ts
new file mode 100644
index 0000000..4ffc37e
--- /dev/null
+++ b/src/ink/flags.test.ts
@@ -0,0 +1,94 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { parseInkFlags, DEFAULT_INK_FLAGS, INK_FLAGS_STORAGE_KEY, createInkFlagsStore, shouldShowDebugPanel, type InkFlags } from './flags'
+
+const ALL_OFF: InkFlags = {
+ smoothing: false,
+ prediction: false,
+ predictionGhost: false,
+ capsuleEraser: false,
+ pointerTolerance: false,
+ wetIncremental: false,
+}
+
+test('flags: defaults are all off', () => {
+ assert.deepEqual(parseInkFlags('', null), ALL_OFF)
+ assert.deepEqual(DEFAULT_INK_FLAGS, ALL_OFF)
+})
+
+test('flags: persisted JSON (partial) is honoured', () => {
+ const stored = JSON.stringify({ smoothing: true })
+ assert.deepEqual(parseInkFlags('', stored), { ...ALL_OFF, smoothing: true })
+})
+
+test('flags: URL params override the store; 0/false clears', () => {
+ const stored = JSON.stringify({ smoothing: true, prediction: true })
+ assert.deepEqual(parseInkFlags('?ink-smooth=0&ink-capsule=1', stored), { ...ALL_OFF, prediction: true, capsuleEraser: true })
+ assert.deepEqual(parseInkFlags('?ink-predict=1&ink-tolerance=1&ink-ghost=1&ink-wet-inc=1', null), {
+ ...ALL_OFF,
+ prediction: true,
+ pointerTolerance: true,
+ predictionGhost: true,
+ wetIncremental: true,
+ })
+ assert.equal(parseInkFlags('?ink-smooth=false', null).smoothing, false)
+})
+
+test('flags: broken store falls back to defaults, URL still applies', () => {
+ assert.deepEqual(parseInkFlags('?ink-smooth=1', '{oops'), { ...ALL_OFF, smoothing: true })
+})
+
+test('flags: unknown keys and junk values are ignored', () => {
+ const stored = JSON.stringify({ smoothing: true, evil: 'x', prediction: 'yes' })
+ assert.deepEqual(parseInkFlags('', stored), { ...ALL_OFF, smoothing: true })
+})
+
+test('flags: the storage key is stable', () => {
+ assert.equal(INK_FLAGS_STORAGE_KEY, 'mathscrap.ink-flags.v1')
+})
+
+test('flags store: get is stable, set merges + notifies + persists', () => {
+ let persisted: InkFlags | null = null
+ const store = createInkFlagsStore({ ...ALL_OFF }, (f) => (persisted = { ...f }))
+ const a = store.get()
+ assert.deepEqual(a, ALL_OFF)
+ assert.equal(store.get(), a) // stable identity between sets (useSyncExternalStore-safe)
+
+ let notified = 0
+ const unsub = store.subscribe(() => notified++)
+ store.set({ smoothing: true })
+ assert.equal(notified, 1)
+ assert.deepEqual(store.get(), { ...ALL_OFF, smoothing: true })
+ assert.notEqual(store.get(), a) // new identity after set
+ assert.deepEqual(persisted, store.get())
+
+ store.set({ prediction: true, smoothing: false })
+ assert.equal(notified, 2)
+ assert.deepEqual(store.get(), { ...ALL_OFF, prediction: true })
+
+ unsub()
+ store.set({ capsuleEraser: true })
+ assert.equal(notified, 2) // no notification after unsubscribe
+ assert.equal(store.get().capsuleEraser, true)
+})
+
+test('flags store: persist throwing is swallowed', () => {
+ const store = createInkFlagsStore(
+ { ...ALL_OFF },
+ () => {
+ throw new Error('no storage')
+ },
+ )
+ assert.doesNotThrow(() => store.set({ smoothing: true }))
+ assert.equal(store.get().smoothing, true)
+})
+
+test('debug panel gating: explicit param wins, otherwise dev + any flag on', () => {
+ const on = { ...ALL_OFF, smoothing: true }
+ assert.equal(shouldShowDebugPanel('?ink-debug=1', false, ALL_OFF), true) // explicit param even in prod
+ assert.equal(shouldShowDebugPanel('?ink-debug=0', true, on), false) // explicit hide wins
+ assert.equal(shouldShowDebugPanel('', true, on), true) // dev + experiment on
+ assert.equal(shouldShowDebugPanel('', true, ALL_OFF), false) // dev but nothing on
+ assert.equal(shouldShowDebugPanel('', false, on), false) // prod without param
+})
diff --git a/src/ink/flags.ts b/src/ink/flags.ts
new file mode 100644
index 0000000..676584c
--- /dev/null
+++ b/src/ink/flags.ts
@@ -0,0 +1,124 @@
+/**
+ * Experiment switches for the ink-feel prototype (prediction + smoothing + capsule eraser).
+ * Everything here is opt-in: with the flags off the board behaves exactly like main.
+ *
+ * Learnings are borrowed as *ideas* from studying how established whiteboard apps
+ * feel (Seewo-style tolerances, midpoint Bézier smoothing, short-horizon gated
+ * prediction) — no third-party code or resources were copied.
+ */
+
+export interface InkFlags {
+ /** near-point dedupe (0.5 DIP) + midpoint quadratic-Bézier smoothing of saved strokes */
+ smoothing: boolean
+ /** live predicted-tail display while drawing (display-only, never persisted) */
+ prediction: boolean
+ /** render the predicted tail as its own translucent ghost path instead of merging it into the ink (needs prediction) */
+ predictionGhost: boolean
+ /** swept-capsule eraser hit testing (catches strokes skipped during fast motion) */
+ capsuleEraser: boolean
+ /** per-pointer-type drag thresholds and eraser hit tolerances (mouse/touch/pen, DIP ÷ zoom) */
+ pointerTolerance: boolean
+ /** wet ink draws from an incremental segment cache instead of resampling the whole stroke per frame (needs smoothing) */
+ wetIncremental: boolean
+}
+
+export const DEFAULT_INK_FLAGS: InkFlags = {
+ smoothing: false,
+ prediction: false,
+ predictionGhost: false,
+ capsuleEraser: false,
+ pointerTolerance: false,
+ wetIncremental: false,
+}
+
+export const INK_FLAGS_STORAGE_KEY = 'mathscrap.ink-flags.v1'
+
+/** URL param per flag, e.g. `?ink-smooth=1&ink-predict=1&ink-ghost=1` (0/false clears). */
+const PARAMS: Record = {
+ smoothing: 'ink-smooth',
+ prediction: 'ink-predict',
+ predictionGhost: 'ink-ghost',
+ capsuleEraser: 'ink-capsule',
+ pointerTolerance: 'ink-tolerance',
+ wetIncremental: 'ink-wet-inc',
+}
+
+const parseParam = (v: string | null): boolean | undefined =>
+ v == null || v === '' ? undefined : !(v === '0' || v === 'false' || v === 'off')
+
+/** Pure: defaults ← persisted JSON ← URL params. Bad input quietly falls back. */
+export function parseInkFlags(search: string, stored: string | null): InkFlags {
+ const flags: InkFlags = { ...DEFAULT_INK_FLAGS }
+ if (stored) {
+ try {
+ const obj = JSON.parse(stored) as Record
+ for (const k of Object.keys(PARAMS) as (keyof InkFlags)[]) if (typeof obj[k] === 'boolean') flags[k] = obj[k] as boolean
+ } catch {
+ // unparseable store → keep defaults, URL overrides still apply
+ }
+ }
+ const qs = new URLSearchParams(search)
+ for (const k of Object.keys(PARAMS) as (keyof InkFlags)[]) {
+ const v = parseParam(qs.get(PARAMS[k]))
+ if (v !== undefined) flags[k] = v
+ }
+ return flags
+}
+
+/** Browser loader (safe when localStorage/location are unavailable). */
+export function loadInkFlags(): InkFlags {
+ try {
+ const stored = typeof localStorage !== 'undefined' ? localStorage.getItem(INK_FLAGS_STORAGE_KEY) : null
+ const search = typeof location !== 'undefined' ? location.search : ''
+ return parseInkFlags(search, stored)
+ } catch {
+ return { ...DEFAULT_INK_FLAGS }
+ }
+}
+
+export interface InkFlagsStore {
+ /** stable snapshot object (identity changes only on set) — useSyncExternalStore-safe */
+ get: () => InkFlags
+ /** merge a patch, persist (best-effort) and notify subscribers */
+ set: (patch: Partial) => void
+ subscribe: (listener: () => void) => () => void
+}
+
+export function createInkFlagsStore(initial: InkFlags, persist?: (flags: InkFlags) => void): InkFlagsStore {
+ let current = { ...initial }
+ const listeners = new Set<() => void>()
+ return {
+ get: () => current,
+ set: (patch) => {
+ current = { ...current, ...patch }
+ try {
+ persist?.(current)
+ } catch {
+ // persistence is best-effort; flags stay in memory
+ }
+ listeners.forEach((l) => l())
+ },
+ subscribe: (l) => {
+ listeners.add(l)
+ return () => {
+ listeners.delete(l)
+ }
+ },
+ }
+}
+
+const persistFlags = (flags: InkFlags) => {
+ if (typeof localStorage !== 'undefined') localStorage.setItem(INK_FLAGS_STORAGE_KEY, JSON.stringify(flags))
+}
+
+/** Module-level store: seeded from localStorage + URL, live-toggled by the debug panel. */
+export const inkFlagsStore = createInkFlagsStore(loadInkFlags(), persistFlags)
+
+export const DEBUG_PANEL_PARAM = 'ink-debug'
+
+/** Show the ink debug panel: `?ink-debug=1` forces it on (`=0` hides), else dev builds with any experiment on. */
+export function shouldShowDebugPanel(search: string, isDev: boolean, flags: InkFlags): boolean {
+ const v = parseParam(new URLSearchParams(search).get(DEBUG_PANEL_PARAM))
+ if (v !== undefined) return v
+ return isDev && Object.values(flags).some(Boolean)
+}
diff --git a/src/ink/integration.test.ts b/src/ink/integration.test.ts
new file mode 100644
index 0000000..e97d75e
--- /dev/null
+++ b/src/ink/integration.test.ts
@@ -0,0 +1,49 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { appendStrokePoint, midpointBezierPolyline } from './smooth'
+import { gateSamples, predictTail } from './predict'
+
+/**
+ * Board-level contract, exercised through the pure modules the Board calls:
+ * predicted points only ever flow through the display path
+ * ([...smoothedRealPts, ...predTail]); the saved stroke is built exclusively
+ * from real samples via appendStrokePoint + the finish-time bake, so no
+ * predicted coordinate can ever enter stroke data.
+ */
+test('predicted points never enter the saved stroke', () => {
+ // a quick straight stroke: real pointer/coalesced samples
+ const real: { x: number; y: number; t: number }[] = []
+ for (let i = 0; i < 12; i++) real.push({ x: 10 + i * 5.8, y: 20 + i * 1.2, t: 1000 + i * 8 })
+
+ // capture: only real samples are appended (this is the only stroke-mutating call in Board)
+ let strokePts: number[] = []
+ for (const s of real) strokePts = appendStrokePoint(strokePts, { x: s.x, y: s.y, pressure: 0.5 }, 0.5, 1)
+
+ // prediction: gate + tail from the same real history
+ const gate = gateSamples(real)
+ assert.equal(gate.predict, true)
+ const tail = predictTail(real, { horizonMs: gate.horizonMs })
+ assert.ok(tail.length > 0)
+ // the tail lives beyond the last real sample
+ const last = real[real.length - 1]
+ assert.ok(Math.hypot(tail[tail.length - 1].x - last.x, tail[tail.length - 1].y - last.y) > 0)
+
+ // what the renderer shows this frame (display path)…
+ const displayPts = [...midpointBezierPolyline(strokePts), ...tail.flatMap((p) => [p.x, p.y, 0.5])]
+ // …vs what finishStroke saves (the bake sees only the real capture)
+ const saved = midpointBezierPolyline(strokePts)
+ assert.deepEqual(saved, midpointBezierPolyline(strokePts))
+ assert.equal(displayPts.length, saved.length + tail.length * 3)
+ // the saved data contains none of the predicted coordinates
+ const triples: number[][] = []
+ for (let i = 0; i < saved.length; i += 3) triples.push([saved[i], saved[i + 1]])
+ for (const p of tail) {
+ assert.ok(
+ !triples.some(([x, y]) => Math.abs(x - p.x) < 1e-9 && Math.abs(y - p.y) < 1e-9),
+ `predicted point ${p.x},${p.y} leaked into saved stroke`,
+ )
+ }
+ // and the bake is a pure function of the real capture alone
+ assert.equal(saved.length, (1 + (strokePts.length / 3 - 2) * 6 + 1) * 3)
+})
diff --git a/src/ink/predict.test.ts b/src/ink/predict.test.ts
new file mode 100644
index 0000000..2d244ae
--- /dev/null
+++ b/src/ink/predict.test.ts
@@ -0,0 +1,193 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ ADAPTIVE_MAX_STEP_MS,
+ ADAPTIVE_MIN_STEP_MS,
+ DEFAULT_GATE_OPTIONS,
+ frameAdaptivePrediction,
+ gateSamples,
+ kfInit,
+ kfPredict,
+ kfUpdate,
+ nativePredictedTail,
+ predictionTailPath,
+ predictTail,
+ PREDICTION_MAX_HORIZON_MS,
+ type InkSample,
+} from './predict'
+
+/** straight drag to the right at constant speed */
+const straight = (n = 8, dt = 8, speed = 0.6): InkSample[] =>
+ Array.from({ length: n }, (_, i) => ({ x: 100 + i * speed * dt, y: 200, t: 1000 + i * dt }))
+
+test('gate: steady straight stroke predicts with the full horizon', () => {
+ const g = gateSamples(straight())
+ assert.equal(g.verdict, 'straight')
+ assert.equal(g.predict, true)
+ assert.equal(g.horizonMs, DEFAULT_GATE_OPTIONS.straightHorizonMs)
+})
+
+test('gate: gentle curve predicts with a shorter horizon', () => {
+ // heading rotates ~15° per step at constant speed (above curveTurnDeg=12, well below sharp=65)
+ const samples: InkSample[] = []
+ let x = 0
+ let y = 0
+ let heading = 0
+ for (let i = 0; i < 8; i++) {
+ samples.push({ x, y, t: 1000 + i * 8 })
+ heading += (15 * Math.PI) / 180
+ x += Math.cos(heading) * 4.8
+ y += Math.sin(heading) * 4.8
+ }
+ const g = gateSamples(samples)
+ assert.equal(g.verdict, 'curve')
+ assert.equal(g.predict, true)
+ assert.equal(g.horizonMs, DEFAULT_GATE_OPTIONS.curveHorizonMs)
+ assert.ok(g.horizonMs < DEFAULT_GATE_OPTIONS.straightHorizonMs)
+})
+
+test('gate: sharp turn disables prediction', () => {
+ const samples: InkSample[] = []
+ for (let i = 0; i < 6; i++) samples.push({ x: i * 5, y: 0, t: 1000 + i * 8 })
+ for (let i = 0; i < 3; i++) samples.push({ x: 25, y: i * 5, t: 1024 + i * 8 }) // hard 90° turn
+ const g = gateSamples(samples)
+ assert.equal(g.verdict, 'sharp')
+ assert.equal(g.predict, false)
+ assert.equal(g.horizonMs, 0)
+})
+
+test('gate: jitter (zig-zag waveform) disables prediction', () => {
+ // gentle zig-zag: ~53° alternating turns → not a single "sharp" turn, but oscillation
+ const samples: InkSample[] = []
+ for (let i = 0; i < 10; i++) samples.push({ x: i * 4, y: i % 2 === 0 ? 0 : 2, t: 1000 + i * 8 })
+ const g = gateSamples(samples)
+ assert.equal(g.verdict, 'jitter')
+ assert.equal(g.predict, false)
+})
+
+test('gate: parked pen (idle) and too-few samples do not predict', () => {
+ assert.equal(gateSamples([{ x: 1, y: 2, t: 0 }, { x: 1.001, y: 2, t: 8 }]).verdict, 'idle')
+ assert.equal(gateSamples([{ x: 1, y: 2, t: 0 }]).verdict, 'sparse')
+ assert.equal(gateSamples([]).verdict, 'sparse')
+ const idle = gateSamples([{ x: 1, y: 2, t: 0 }, { x: 1.001, y: 2, t: 8 }])
+ assert.equal(idle.predict, false)
+})
+
+test('gate: pure — input samples are never mutated', () => {
+ const frozen = Object.freeze(straight().map(Object.freeze)) as readonly InkSample[]
+ assert.doesNotThrow(() => gateSamples(frozen as InkSample[]))
+})
+
+test('predictTail: constant velocity is extrapolated within tolerance', () => {
+ const samples = straight(20, 8, 0.6) // 0.6 px/ms ≈ 600 px/s
+ const tail = predictTail(samples, { horizonMs: 33, stepMs: 11 })
+ assert.equal(tail.length, 3)
+ const last = samples[samples.length - 1]
+ const expected = last.x + 0.6 * 33
+ assert.ok(Math.abs(tail[2].x - expected) / expected < 0.15, `got ${tail[2].x}, want ≈ ${expected}`)
+ // y barely moves → prediction stays put
+ assert.ok(Math.abs(tail[2].y - last.y) < 3)
+ assert.equal(tail[2].t, last.t + 33)
+})
+
+test('predictTail: horizon is capped at 36 ms and input stays untouched', () => {
+ const samples = straight()
+ const snapshot = JSON.stringify(samples)
+ const tail = predictTail(samples, { horizonMs: 500, stepMs: 11 })
+ assert.ok(tail.length > 0)
+ const last = samples[samples.length - 1]
+ assert.ok(tail[tail.length - 1].t - last.t <= PREDICTION_MAX_HORIZON_MS + 1e-9)
+ assert.equal(JSON.stringify(samples), snapshot)
+})
+
+test('predictTail: degenerate inputs return an empty tail', () => {
+ assert.deepEqual(predictTail([]), [])
+ assert.deepEqual(predictTail([{ x: 1, y: 1, t: 5 }]), [])
+ assert.deepEqual(predictTail([{ x: 1, y: 1, t: 5 }, { x: 2, y: 1, t: 5 }]), []) // no time span
+})
+
+test('KF converges on constant velocity input', () => {
+ let k = kfInit(0)
+ for (let i = 1; i <= 20; i++) k = kfUpdate(kfPredict(k, 8), i * 0.6 * 8)
+ assert.ok(Math.abs(k.v - 600) / 600 < 0.1, `velocity estimate ${k.v}`)
+})
+
+test('nativePredictedTail: prefers the browser, falls back cleanly', () => {
+ const provider = {
+ getPredictedEvents: () => [
+ { clientX: 1, clientY: 2, pressure: 0.5 },
+ { clientX: 3, clientY: 4, pressure: 0.5 },
+ ],
+ }
+ const tail = nativePredictedTail(provider)
+ assert.deepEqual(tail, [{ clientX: 1, clientY: 2 }, { clientX: 3, clientY: 4 }])
+ // missing API → empty (caller uses the self-extrapolation fallback)
+ assert.deepEqual(nativePredictedTail({}), [])
+ assert.deepEqual(nativePredictedTail({ getPredictedEvents: () => [] }), [])
+ // throws → empty
+ assert.deepEqual(
+ nativePredictedTail({
+ getPredictedEvents: () => {
+ throw new Error('boom')
+ },
+ }),
+ [],
+ )
+ // capped
+ const many = nativePredictedTail({
+ getPredictedEvents: () => Array.from({ length: 9 }, (_, i) => ({ clientX: i, clientY: i })),
+ })
+ assert.equal(many.length, 4)
+})
+
+test('frameAdaptivePrediction: scales with the refresh rate, caps preserved', () => {
+ const a60 = frameAdaptivePrediction(16.7)
+ const a120 = frameAdaptivePrediction(8.3)
+ const a144 = frameAdaptivePrediction(6.9)
+ // ~2 frames ahead on a straight verdict, half of that on curves
+ assert.ok(Math.abs(a60.horizonMs - 33.4) < 0.01)
+ assert.ok(Math.abs(a60.stepMs - 8.35) < 0.01)
+ assert.ok(Math.abs(a60.curveHorizonMs - a60.horizonMs / 2) < 0.01)
+ // higher refresh → finer step and shorter tail
+ assert.ok(a120.stepMs < a60.stepMs)
+ assert.ok(a120.horizonMs < a60.horizonMs)
+ assert.ok(a144.stepMs < a120.stepMs)
+ assert.ok(a144.horizonMs < a120.horizonMs)
+ for (const a of [a60, a120, a144]) {
+ assert.ok(a.horizonMs <= PREDICTION_MAX_HORIZON_MS + 1e-9, 'absolute horizon cap')
+ assert.ok(a.stepMs >= ADAPTIVE_MIN_STEP_MS && a.stepMs <= ADAPTIVE_MAX_STEP_MS)
+ assert.ok(a.curveHorizonMs <= a.horizonMs + 1e-9)
+ }
+})
+
+test('frameAdaptivePrediction: degenerate intervals clamp into range', () => {
+ for (const f of [0, -5, NaN, Infinity, 500]) {
+ const a = frameAdaptivePrediction(f)
+ assert.ok(a.stepMs >= ADAPTIVE_MIN_STEP_MS && a.stepMs <= ADAPTIVE_MAX_STEP_MS)
+ assert.ok(a.horizonMs >= a.stepMs)
+ assert.ok(a.horizonMs <= PREDICTION_MAX_HORIZON_MS)
+ }
+ // at the clamps: a very slow / very fast panel still yields sane numbers
+ const slow = frameAdaptivePrediction(40)
+ assert.equal(slow.stepMs, ADAPTIVE_MAX_STEP_MS)
+ assert.equal(slow.horizonMs, PREDICTION_MAX_HORIZON_MS)
+ const fast = frameAdaptivePrediction(2)
+ assert.equal(fast.stepMs, ADAPTIVE_MIN_STEP_MS)
+ assert.equal(fast.horizonMs, 8)
+})
+
+test('predictionTailPath: ghost path starts at the stroke tip, inputs untouched', () => {
+ const base = [0, 0, 0.5, 10, 0, 0.5, 20, 0, 0.5]
+ const tail = [30, 0, 0.5, 40, 0, 0.5]
+ const snapshot = JSON.stringify({ base, tail })
+ const path = predictionTailPath(base, tail)
+ assert.equal(path.length, 3 + tail.length)
+ assert.deepEqual(path.slice(0, 3), [20, 0, 0.5]) // last smoothed point === real stroke tip
+ assert.deepEqual(path.slice(3), tail)
+ assert.equal(JSON.stringify({ base, tail }), snapshot)
+ // degenerate base (no full triple yet): tail alone
+ assert.deepEqual(predictionTailPath([], tail), tail)
+ // a single full triple IS a valid tip
+ assert.deepEqual(predictionTailPath([1, 2, 0.5], tail), [1, 2, 0.5, ...tail])
+})
diff --git a/src/ink/predict.ts b/src/ink/predict.ts
new file mode 100644
index 0000000..7ef474c
--- /dev/null
+++ b/src/ink/predict.ts
@@ -0,0 +1,293 @@
+/**
+ * Pen-position prediction for the live stroke — pure functions.
+ *
+ * Idea learned from studying established whiteboards (not their code): predict
+ * only a very short horizon (~one frame up to 36 ms) from x/y/time alone, gate
+ * the prediction off on sharp turns and jitter, and treat predicted points as
+ * display-only — the next real sample replaces them and they never enter the
+ * saved stroke.
+ *
+ * Two sources, in order of preference:
+ * 1. `PointerEvent.getPredictedEvents()` (browser-native, Chromium).
+ * 2. A tiny per-axis constant-velocity Kalman filter as fallback.
+ */
+
+export interface InkSample {
+ /** screen px */
+ x: number
+ y: number
+ /** ms, monotonic (event.timeStamp) */
+ t: number
+}
+
+export type GateVerdict = 'sparse' | 'idle' | 'straight' | 'curve' | 'sharp' | 'jitter'
+
+export interface GateResult {
+ verdict: GateVerdict
+ /** false → show no prediction at all */
+ predict: boolean
+ /** extrapolation budget this frame (0 when predict is false) */
+ horizonMs: number
+}
+
+export interface GateOptions {
+ minSamples?: number
+ /** px/ms below which the pen counts as parked (jitter zone) */
+ idleSpeedPxPerMs?: number
+ /** single turn above this (deg) kills prediction */
+ sharpTurnDeg?: number
+ /** oscillating turns above this (deg) count as jitter */
+ jitterTurnDeg?: number
+ /** mean turn above this (deg) shortens the horizon */
+ curveTurnDeg?: number
+ straightHorizonMs?: number
+ curveHorizonMs?: number
+}
+
+export const DEFAULT_GATE_OPTIONS: Required = {
+ minSamples: 2,
+ idleSpeedPxPerMs: 0.04,
+ sharpTurnDeg: 65,
+ jitterTurnDeg: 30,
+ curveTurnDeg: 12,
+ straightHorizonMs: 33,
+ curveHorizonMs: 17,
+}
+
+export const PREDICTION_MAX_HORIZON_MS = 36
+export const PREDICTION_STEP_MS = 11
+
+/** Gating and the KF only need the recent gesture — cap the sample history so a long stroke costs the same as a short one. */
+export const PREDICTION_HISTORY_CAP = 96
+
+const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v)
+
+/**
+ * Decide whether the current stroke moment may be extrapolated, and by how much.
+ * Pure; never mutates `samples`.
+ */
+export function gateSamples(samples: InkSample[], o: GateOptions = {}): GateResult {
+ const opt = { ...DEFAULT_GATE_OPTIONS, ...o }
+ const none: GateResult = { verdict: 'sparse', predict: false, horizonMs: 0 }
+ if (samples.length < opt.minSamples) return none
+
+ const vx: number[] = []
+ const vy: number[] = []
+ const speeds: number[] = []
+ for (let i = 1; i < samples.length; i++) {
+ const dt = samples[i].t - samples[i - 1].t
+ if (dt <= 0) continue
+ const dx = samples[i].x - samples[i - 1].x
+ const dy = samples[i].y - samples[i - 1].y
+ vx.push(dx / dt)
+ vy.push(dy / dt)
+ speeds.push(Math.hypot(dx, dy) / dt)
+ }
+ if (!speeds.length) return none
+ if (speeds[speeds.length - 1] < opt.idleSpeedPxPerMs) return { verdict: 'idle', predict: false, horizonMs: 0 }
+
+ // signed turn angles (deg) between successive velocity vectors
+ const turns: number[] = []
+ for (let i = 1; i < vx.length; i++) {
+ const a = Math.hypot(vx[i - 1], vy[i - 1])
+ const b = Math.hypot(vx[i], vy[i])
+ if (a < 1e-9 || b < 1e-9) continue
+ const cos = clamp((vx[i - 1] * vx[i] + vy[i - 1] * vy[i]) / (a * b), -1, 1)
+ const cross = vx[i - 1] * vy[i] - vy[i - 1] * vx[i]
+ turns.push((cross < 0 ? -1 : 1) * Math.acos(cos) * (180 / Math.PI))
+ }
+ const maxTurn = turns.length ? Math.max(...turns.map(Math.abs)) : 0
+ if (maxTurn > opt.sharpTurnDeg) return { verdict: 'sharp', predict: false, horizonMs: 0 }
+
+ // jitter: large zig-zag (two consecutive opposite-sign turns) or sustained
+ // recent oscillation. Flips only count in the last ~12 pairs and need BOTH
+ // turns above jitterTurnDeg/2 — pointer noise produces small random turns
+ // whose flips accumulate harmlessly over a long window (replay-eval finding).
+ const flipDeg = opt.jitterTurnDeg / 2
+ const recent = turns.slice(-12)
+ let flips = 0
+ for (let i = 1; i < recent.length; i++) {
+ if (Math.abs(recent[i]) > opt.jitterTurnDeg && Math.abs(recent[i - 1]) > opt.jitterTurnDeg && recent[i] * recent[i - 1] < 0)
+ return { verdict: 'jitter', predict: false, horizonMs: 0 }
+ if (Math.abs(recent[i]) >= flipDeg && Math.abs(recent[i - 1]) >= flipDeg && recent[i] * recent[i - 1] < 0) flips++
+ }
+ if (flips >= 3) return { verdict: 'jitter', predict: false, horizonMs: 0 }
+
+ // curve vs straight on a ROBUST statistic: the median turn, not the max —
+ // a noisy window always contains one large random turn, so a max-based test
+ // read every straight stroke as a curve (replay-eval finding)
+ const abs = turns.map(Math.abs).sort((a, b) => a - b)
+ const medianTurn = abs.length ? abs[abs.length >> 1] : 0
+ if (medianTurn > opt.curveTurnDeg) return { verdict: 'curve', predict: true, horizonMs: opt.curveHorizonMs }
+ return { verdict: 'straight', predict: true, horizonMs: opt.straightHorizonMs }
+}
+
+/** Minimal per-axis constant-velocity Kalman filter (state [p, v], measurement [p]). */
+export interface KF1D {
+ p: number
+ /** px/s */
+ v: number
+ p00: number
+ p01: number
+ p10: number
+ p11: number
+}
+
+/** Spectral density of the acceleration noise, px²/s⁴ — tuned for handwriting snaps. */
+export const KF_ACCEL_VAR = 9e6
+/** Pointer measurement variance, px². */
+export const KF_MEAS_VAR = 2
+
+export function kfInit(pos: number): KF1D {
+ // generous velocity prior so the filter adopts real speed within a few samples
+ return { p: pos, v: 0, p00: 40, p01: 0, p10: 0, p11: 1e5 }
+}
+
+export function kfPredict(s: KF1D, dtMs: number, accelVar = KF_ACCEL_VAR): KF1D {
+ const dt = dtMs / 1000
+ const q = accelVar
+ return {
+ p: s.p + s.v * dt,
+ v: s.v,
+ p00: s.p00 + 2 * dt * s.p01 + dt * dt * s.p11 + (q * dt ** 4) / 4,
+ p01: s.p01 + dt * s.p11 + (q * dt ** 3) / 2,
+ p10: s.p10 + dt * s.p11 + (q * dt ** 3) / 2,
+ p11: s.p11 + q * dt * dt,
+ }
+}
+
+export function kfUpdate(s: KF1D, z: number, measVar = KF_MEAS_VAR): KF1D {
+ const y = z - s.p
+ const k0 = s.p00 / (s.p00 + measVar)
+ const k1 = s.p10 / (s.p00 + measVar)
+ return {
+ p: s.p + k0 * y,
+ v: s.v + k1 * y,
+ p00: (1 - k0) * s.p00,
+ p01: (1 - k0) * s.p01,
+ p10: s.p10 - k1 * s.p00,
+ p11: s.p11 - k1 * s.p01,
+ }
+}
+
+export interface PredictOptions {
+ /** extrapolation budget, capped at PREDICTION_MAX_HORIZON_MS */
+ horizonMs?: number
+ stepMs?: number
+ /** KF acceleration noise override (default KF_ACCEL_VAR) — replay-eval knob, defaults unchanged */
+ qAcc?: number
+ /** KF measurement variance override (default KF_MEAS_VAR) — replay-eval knob, defaults unchanged */
+ measVar?: number
+}
+
+/**
+ * Fallback predictor: run the per-axis KF over the recent real samples, then
+ * step forward `horizonMs`. Pure — the input samples are never mutated, the
+ * result is a fresh array of display-only points beyond the last real sample.
+ */
+export function predictTail(samples: InkSample[], o: PredictOptions = {}): InkSample[] {
+ const horizonMs = Math.min(o.horizonMs ?? DEFAULT_GATE_OPTIONS.straightHorizonMs, PREDICTION_MAX_HORIZON_MS)
+ const stepMs = o.stepMs ?? PREDICTION_STEP_MS
+ const n = samples.length
+ if (n < 2) return []
+ if (!(samples[n - 1].t > samples[0].t)) return []
+
+ let kx = kfInit(samples[0].x)
+ let ky = kfInit(samples[0].y)
+ let t = samples[0].t
+ for (let i = 1; i < n; i++) {
+ const dt = samples[i].t - t
+ if (dt <= 0) continue // non-monotonic guard: keep the filter on the last good time
+ kx = kfUpdate(kfPredict(kx, dt, o.qAcc), samples[i].x, o.measVar)
+ ky = kfUpdate(kfPredict(ky, dt, o.qAcc), samples[i].y, o.measVar)
+ t = samples[i].t
+ }
+ const out: InkSample[] = []
+ for (let d = stepMs; d <= horizonMs + 1e-9; d += stepMs) {
+ out.push({ x: kfPredict(kx, d).p, y: kfPredict(ky, d).p, t: t + d })
+ }
+ return out
+}
+
+export interface PredictedEventLike {
+ clientX: number
+ clientY: number
+}
+
+export type PredictedProvider = {
+ getPredictedEvents?: () => PredictedEventLike[]
+}
+
+/**
+ * Native predicted events when the platform offers them (Chromium), else [].
+ * Coordinates stay in screen space; count is capped — the tail is a hint, not a
+ * path to commit.
+ */
+export function nativePredictedTail(e: PredictedProvider, maxPoints = 4): PredictedEventLike[] {
+ const fn = e.getPredictedEvents
+ if (typeof fn !== 'function') return []
+ let evs: PredictedEventLike[]
+ try {
+ evs = fn.call(e)
+ } catch {
+ return []
+ }
+ if (!Array.isArray(evs) || !evs.length) return []
+ return evs.slice(0, maxPoints).map((ev) => ({ clientX: ev.clientX, clientY: ev.clientY }))
+}
+
+// --- refresh-rate adaptive step/horizon -------------------------------------
+
+export const ADAPTIVE_MIN_FRAME_MS = 4
+export const ADAPTIVE_MAX_FRAME_MS = 33
+/** fall back to a 60 Hz assumption until rAF deltas come in */
+export const ADAPTIVE_DEFAULT_FRAME_MS = 16.7
+export const ADAPTIVE_MIN_STEP_MS = 3
+export const ADAPTIVE_MAX_STEP_MS = PREDICTION_STEP_MS // never coarser than the static 11 ms
+/** how many frames of lag the tail aims to cover */
+export const ADAPTIVE_FRAMES_AHEAD = 2
+/** curve verdicts get this fraction of the straight-line horizon */
+export const ADAPTIVE_CURVE_FRACTION = 0.5
+
+export interface AdaptiveOptions {
+ /** how many frames of lag the tail aims to cover (replay-eval knob, default ADAPTIVE_FRAMES_AHEAD) */
+ framesAhead?: number
+ /** curve verdicts get this fraction of the straight-line horizon (default ADAPTIVE_CURVE_FRACTION) */
+ curveFraction?: number
+}
+
+export interface AdaptivePrediction {
+ stepMs: number
+ horizonMs: number
+ curveHorizonMs: number
+}
+
+/**
+ * Scale the prediction step and horizon to the display's frame interval
+ * (estimated from rAF deltas): a 120 Hz panel gets a finer, shorter tail than a
+ * 60 Hz one, both under the absolute PREDICTION_MAX_HORIZON_MS cap. Degenerate
+ * intervals (first frame, background tab) clamp into a sane range.
+ */
+export function frameAdaptivePrediction(frameIntervalMs: number, o: AdaptiveOptions = {}): AdaptivePrediction {
+ const ahead = o.framesAhead ?? ADAPTIVE_FRAMES_AHEAD
+ const curveFraction = o.curveFraction ?? ADAPTIVE_CURVE_FRACTION
+ const f =
+ Number.isFinite(frameIntervalMs) && frameIntervalMs > 0
+ ? Math.min(ADAPTIVE_MAX_FRAME_MS, Math.max(ADAPTIVE_MIN_FRAME_MS, frameIntervalMs))
+ : ADAPTIVE_DEFAULT_FRAME_MS
+ const stepMs = Math.min(ADAPTIVE_MAX_STEP_MS, Math.max(ADAPTIVE_MIN_STEP_MS, f / 2))
+ const horizonMs = Math.min(PREDICTION_MAX_HORIZON_MS, Math.max(stepMs, f * ahead))
+ const curveHorizonMs = Math.max(stepMs, horizonMs * curveFraction)
+ return { stepMs, horizonMs, curveHorizonMs }
+}
+
+/**
+ * Display-only ghost path for the separately-rendered prediction tail: starts at
+ * the stroke tip (last smoothed point) and runs through the predicted points.
+ * Pure — neither input is mutated, and nothing here ever reaches saved data.
+ */
+export function predictionTailPath(basePts: number[], tail: number[]): number[] {
+ const n = basePts.length
+ if (n < 3) return tail.slice()
+ return [basePts[n - 3], basePts[n - 2], basePts[n - 1], ...tail]
+}
diff --git a/src/ink/replay.test.ts b/src/ink/replay.test.ts
new file mode 100644
index 0000000..a49fa57
--- /dev/null
+++ b/src/ink/replay.test.ts
@@ -0,0 +1,65 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { makeTrajectory, mulberry32, replayTrajectory, type ReplayCandidate } from './replay'
+
+test('mulberry32: deterministic and seed-sensitive', () => {
+ const a = mulberry32(42)
+ const b = mulberry32(42)
+ const seqA = Array.from({ length: 5 }, () => a())
+ const seqB = Array.from({ length: 5 }, () => b())
+ assert.deepEqual(seqA, seqB)
+ assert.notEqual(seqA[0], mulberry32(7)())
+})
+
+test('makeTrajectory: reproducible, monotonic time, noise bounded around exact truth', () => {
+ const t1 = makeTrajectory('straight', { rateHz: 60, noisePx: 0.6, seed: 42 })
+ const t2 = makeTrajectory('straight', { rateHz: 60, noisePx: 0.6, seed: 42 })
+ assert.deepEqual(t1.samples, t2.samples)
+ assert.equal(t1.samples.length, Math.round(1500 * 0.06) + 1) // duration × rate + 1
+ for (let i = 1; i < t1.samples.length; i++) assert.ok(t1.samples[i].t > t1.samples[i - 1].t)
+ for (const s of t1.samples) {
+ const truth = t1.truthAt(s.t)
+ // ~4σ bound for a 0.6px Gaussian
+ assert.ok(Math.hypot(s.x - truth.x, s.y - truth.y) < 0.6 * 4, 'sample strayed too far from truth')
+ }
+})
+
+test('replayTrajectory: deterministic and counts moments', () => {
+ const traj = makeTrajectory('straight', { rateHz: 60, seed: 42 })
+ const cand: ReplayCandidate = { name: 'A-现行默认' }
+ const s1 = replayTrajectory(traj, cand, 60)
+ const s2 = replayTrajectory(traj, cand, 60)
+ assert.deepEqual(s1, s2)
+ assert.equal(s1.predicted + s1.gated, s1.moments)
+ assert.equal(s1.moments, traj.samples.length - 8)
+ assert.ok(s1.predicted > s1.moments * 0.6, `straight stroke should mostly predict (got ${s1.predicted}/${s1.moments})`)
+ assert.ok(s1.meanErr >= 0 && Number.isFinite(s1.meanErr))
+})
+
+test('replayTrajectory: a never-predict candidate gates everything away', () => {
+ const traj = makeTrajectory('straight', { rateHz: 60, seed: 42 })
+ const s = replayTrajectory(traj, { name: 'off', gate: { minSamples: 1e9 } }, 60)
+ assert.equal(s.predicted, 0)
+ assert.equal(s.gated, s.moments)
+ assert.equal(s.meanErr, 0)
+ assert.equal(s.meanOvershoot, 0)
+})
+
+test('replayTrajectory: sharp turns and pauses get gated, slow ticks mostly gated', () => {
+ const turn = replayTrajectory(makeTrajectory('sharpTurn', { rateHz: 60, seed: 42 }), { name: 'A' }, 60)
+ assert.ok(turn.gated > 0, 'sharp turn should suppress prediction sometimes')
+ const pause = replayTrajectory(makeTrajectory('pause', { rateHz: 60, seed: 42 }), { name: 'A' }, 60)
+ assert.ok(pause.gated > 0, 'paused pen should be gated (idle)')
+ const tick = replayTrajectory(makeTrajectory('slowTick', { rateHz: 60, seed: 42 }), { name: 'A' }, 60)
+ assert.ok(tick.predicted < tick.moments * 0.5, `slow tick should mostly stay gated (predicted ${tick.predicted}/${tick.moments})`)
+})
+
+test('replayTrajectory: candidate knobs change the outcome', () => {
+ const traj = makeTrajectory('fastArc', { rateHz: 60, seed: 42 })
+ const a = replayTrajectory(traj, { name: 'A' }, 60)
+ const c = replayTrajectory(traj, { name: 'C', gate: { sharpTurnDeg: 75, jitterTurnDeg: 35, curveTurnDeg: 15 }, framesAhead: 2.5 }, 60)
+ assert.ok(a.predicted > 0)
+ // the aggressive set covers more lag → strictly larger horizon, not identical stats
+ assert.notDeepEqual(a, c)
+})
diff --git a/src/ink/replay.ts b/src/ink/replay.ts
new file mode 100644
index 0000000..c7029a0
--- /dev/null
+++ b/src/ink/replay.ts
@@ -0,0 +1,202 @@
+/**
+ * Offline replay evaluation for the ink-prediction experiment — pure Node, no DOM.
+ *
+ * SYNTHETIC, reproducible handwriting-like trajectories are replayed sample by
+ * sample through the exact gate + Kalman pipeline the Board uses; every
+ * predicted tail end is compared against the trajectory's exact (noise-free)
+ * ground truth at the tail's own timestamp.
+ *
+ * The numbers are STARTING-POINT CANDIDATES for on-device (iPad) tuning only —
+ * nothing here changes any default, and synthetic noise is not real ink.
+ */
+import { frameAdaptivePrediction, gateSamples, PREDICTION_HISTORY_CAP, predictTail, type GateOptions, type InkSample } from './predict'
+
+/** tiny deterministic PRNG (mulberry32) so every replay run is reproducible */
+export function mulberry32(seed: number): () => number {
+ let a = seed >>> 0
+ return () => {
+ a = (a + 0x6d2b79f5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+export type TrajectoryScenario = 'straight' | 'fastArc' | 'sharpTurn' | 'jitter' | 'pause' | 'slowTick'
+
+export const SCENARIO_LABELS: Record = {
+ straight: '直线',
+ fastArc: '快弧(小半径)',
+ sharpTurn: '急转',
+ jitter: '抖动',
+ pause: '停笔',
+ slowTick: '慢短笔',
+}
+
+const SCENARIO_DURATION_MS: Record = {
+ straight: 1500,
+ fastArc: 600,
+ sharpTurn: 1000,
+ jitter: 800,
+ pause: 1300,
+ slowTick: 500,
+}
+
+export interface ReplayTrajectory {
+ scenario: TrajectoryScenario
+ samples: InkSample[]
+ /** exact, noise-free position at time t (ms) */
+ truthAt: (t: number) => { x: number; y: number }
+}
+
+export interface TrajectoryOptions {
+ rateHz?: number
+ noisePx?: number
+ seed?: number
+}
+
+/**
+ * Build one synthetic trajectory. Ground truth stays parametric and exact;
+ * Gaussian noise is added to the samples only, like pointer-reporting jitter.
+ */
+export function makeTrajectory(scenario: TrajectoryScenario, o: TrajectoryOptions = {}): ReplayTrajectory {
+ const rateHz = o.rateHz ?? 60
+ const noisePx = o.noisePx ?? 0.6
+ const rnd = mulberry32(o.seed ?? 42)
+ const gauss = () => {
+ const u = Math.max(rnd(), 1e-9)
+ const v = rnd()
+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)
+ }
+ const dt = 1000 / rateHz
+ const duration = SCENARIO_DURATION_MS[scenario]
+
+ let truthAt: (t: number) => { x: number; y: number }
+ switch (scenario) {
+ case 'straight':
+ // 600 px/s to the right for 1.5 s
+ truthAt = (t) => ({ x: 120 + 0.6 * t, y: 200 })
+ break
+ case 'fastArc':
+ // tight fast arc (like the loop of a handwritten "e"): r=25, v=600 px/s
+ truthAt = (t) => {
+ const theta = (600 / 25) * (t / 1000)
+ return { x: 300 + 25 * Math.cos(theta), y: 240 + 25 * Math.sin(theta) }
+ }
+ break
+ case 'sharpTurn':
+ // 600 ms straight, then a hard 90° turn downwards
+ truthAt = (t) => (t < 600 ? { x: 120 + 0.6 * t, y: 200 } : { x: 480, y: 200 + 0.6 * (t - 600) })
+ break
+ case 'jitter':
+ // horizontal drag under a fast triangular wobble (alternating ~60° turns)
+ truthAt = (t) => {
+ const phase = (t % 80) / 80
+ return { x: 120 + 0.5 * t, y: 200 + 6 * (phase < 0.5 ? phase * 2 : 2 - phase * 2) }
+ }
+ break
+ case 'pause':
+ // write, hold still for 300 ms (device keeps reporting), write again
+ truthAt = (t) => {
+ if (t < 500) return { x: 120 + 0.6 * t, y: 200 }
+ if (t < 800) return { x: 420, y: 200 }
+ return { x: 420 + 0.6 * (t - 800), y: 200 }
+ }
+ break
+ case 'slowTick':
+ // a slow deliberate short tick: ~6 px over 500 ms (idle-speed territory)
+ truthAt = (t) => ({ x: 100 + 0.012 * t, y: 300 + 0.0024 * t })
+ break
+ }
+
+ const n = Math.round((duration * rateHz) / 1000) + 1
+ const samples: InkSample[] = []
+ for (let i = 0; i < n; i++) {
+ const t = i * dt
+ const p = truthAt(t)
+ samples.push({ x: p.x + gauss() * noisePx, y: p.y + gauss() * noisePx, t })
+ }
+ return { scenario, samples, truthAt }
+}
+
+export interface ReplayCandidate {
+ name: string
+ /** gate angle/horizon overrides (defaults = current constants) */
+ gate?: GateOptions
+ /** KF acceleration-noise override (default KF_ACCEL_VAR) */
+ qAcc?: number
+ /** KF measurement-variance override (default KF_MEAS_VAR) */
+ measVar?: number
+ /** frames of lag the tail covers (default ADAPTIVE_FRAMES_AHEAD) */
+ framesAhead?: number
+}
+
+export interface ReplayStats {
+ candidate: string
+ scenario: TrajectoryScenario
+ rateHz: number
+ /** evaluated moments (one per sample with enough history) */
+ moments: number
+ /** moments where the gate allowed a prediction */
+ predicted: number
+ /** moments where the gate suppressed the tail */
+ gated: number
+ /** |predicted tail end − ground truth| at the tail's own timestamp (px) */
+ meanErr: number
+ p95Err: number
+ maxErr: number
+ /** signed overshoot: error component along the travel direction, + = ahead of the true point (px) */
+ meanOvershoot: number
+}
+
+const MIN_HISTORY = 8
+
+/** Replay one trajectory under one candidate constant set. Pure w.r.t. inputs. */
+export function replayTrajectory(traj: ReplayTrajectory, cand: ReplayCandidate, rateHz: number): ReplayStats {
+ const frameMs = 1000 / rateHz
+ const adapt = frameAdaptivePrediction(frameMs, { framesAhead: cand.framesAhead })
+ const errs: number[] = []
+ const overshoots: number[] = []
+ let predicted = 0
+ let gated = 0
+ const samples = traj.samples
+ for (let i = MIN_HISTORY; i < samples.length; i++) {
+ const hist = samples.slice(Math.max(0, i - PREDICTION_HISTORY_CAP + 1), i + 1)
+ const gate = gateSamples(hist, cand.gate)
+ const last = hist[hist.length - 1]
+ if (!gate.predict) {
+ gated++
+ continue
+ }
+ const horizon = gate.verdict === 'curve' ? adapt.curveHorizonMs : adapt.horizonMs
+ const tail = predictTail(hist, { horizonMs: horizon, stepMs: adapt.stepMs, qAcc: cand.qAcc, measVar: cand.measVar })
+ if (!tail.length) {
+ gated++
+ continue
+ }
+ predicted++
+ const end = tail[tail.length - 1]
+ const truth = traj.truthAt(end.t)
+ errs.push(Math.hypot(end.x - truth.x, end.y - truth.y))
+ // overshoot = error component along the current travel direction (+ = past the true point)
+ const prev = hist[hist.length - 2]
+ const dx = last.x - prev.x
+ const dy = last.y - prev.y
+ const len = Math.max(Math.hypot(dx, dy), 1e-6)
+ overshoots.push(((end.x - truth.x) * dx + (end.y - truth.y) * dy) / len)
+ }
+ const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0)
+ const sorted = [...errs].sort((a, b) => a - b)
+ return {
+ candidate: cand.name,
+ scenario: traj.scenario,
+ rateHz,
+ moments: predicted + gated,
+ predicted,
+ gated,
+ meanErr: mean(errs),
+ p95Err: sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))] : 0,
+ maxErr: sorted.length ? sorted[sorted.length - 1] : 0,
+ meanOvershoot: mean(overshoots),
+ }
+}
diff --git a/src/ink/smooth.test.ts b/src/ink/smooth.test.ts
new file mode 100644
index 0000000..9f52b37
--- /dev/null
+++ b/src/ink/smooth.test.ts
@@ -0,0 +1,169 @@
+///
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ appendStrokePoint,
+ BEZIER_SAMPLES_PER_CURVE,
+ createIncrementalSmooth,
+ midpointBezierPolyline,
+ SMOOTH_MIN_DIST_DIP,
+ updateIncrementalSmooth,
+} from './smooth'
+
+const triple = (pts: number[], i: number) => [pts[i * 3], pts[i * 3 + 1], pts[i * 3 + 2]]
+
+test('appendStrokePoint drops near points (0.5 DIP default)', () => {
+ const s = appendStrokePoint([], { x: 10, y: 10, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1)
+ assert.equal(s.length, 3)
+ // 0.1 screen px away → skipped
+ const near = appendStrokePoint(s, { x: 10.1, y: 10, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1)
+ assert.equal(near, s) // same array when skipped
+ // 2 screen px away → appended
+ const far = appendStrokePoint(s, { x: 12.1, y: 10, pressure: 0.6 }, SMOOTH_MIN_DIST_DIP, 1)
+ assert.equal(far.length, 6)
+ assert.deepEqual(triple(far, 1), [12.1, 10, 0.6])
+})
+
+test('appendStrokePoint threshold is in screen px (world × scale)', () => {
+ const s = [0, 0, 0.5]
+ // world distance 1 at zoom 4 → 4 screen px → appended even though 1 < 0.5 is false
+ const at = appendStrokePoint(s, { x: 1, y: 0, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 4)
+ assert.equal(at.length, 6)
+ // world distance 0.1 at zoom 1 → 0.1 screen px → skipped
+ const skipped = appendStrokePoint(s, { x: 0.1, y: 0, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1)
+ assert.equal(skipped, s)
+})
+
+test('flag-off equivalence: appendStrokePoint at 0.8 reproduces the main inline loop', () => {
+ // literal port of the main-branch capture loop for comparison
+ const mainAppend = (pts: number[], x: number, y: number, pressure: number, scale: number) => {
+ const out = pts.slice()
+ const lx = out[out.length - 3] as number
+ const ly = out[out.length - 2] as number
+ if (Math.hypot(x - lx, y - ly) * scale < 0.8) return out
+ out.push(x, y, pressure)
+ return out
+ }
+ const events: [number, number, number, number][] = [
+ [0, 0, 1, 1],
+ [0.3, 0.4, 1, 1],
+ [0.6, 0.8, 1, 1],
+ [2, 3, 1, 1],
+ [2.1, 3.05, 1, 1],
+ [5, 7, 1, 1],
+ [5.4, 7.3, 1, 1],
+ [9, 9, 1, 2],
+ ]
+ let a: number[] = []
+ let b: number[] = []
+ for (const [x, y, pressure, scale] of events) {
+ a = appendStrokePoint(a, { x, y, pressure }, 0.8, scale)
+ b = mainAppend(b, x, y, pressure, scale)
+ }
+ assert.deepEqual(a, b)
+})
+
+test('midpointBezierPolyline keeps endpoints exact', () => {
+ const pts = [0, 0, 0.5, 10, 12, 0.5, 24, 2, 0.5, 40, 30, 0.5]
+ const out = midpointBezierPolyline(pts)
+ assert.deepEqual(triple(out, 0), triple(pts, 0))
+ const last = out.length / 3 - 1
+ assert.deepEqual(triple(out, last), triple(pts, pts.length / 3 - 1))
+ // 1 + (n-2)*samples + 1 points
+ assert.equal(out.length, (1 + 2 * BEZIER_SAMPLES_PER_CURVE + 1) * 3)
+})
+
+test('midpointBezierPolyline leaves dots and two-point strokes untouched', () => {
+ const dot = [3, 4, 0.5]
+ const line = [0, 0, 0.5, 10, 10, 0.7]
+ assert.equal(midpointBezierPolyline(dot), dot)
+ assert.equal(midpointBezierPolyline(line), line)
+})
+
+test('midpointBezierPolyline passes through sample midpoints (no corner cutting to NaN)', () => {
+ const pts = [0, 0, 0.5, 10, 0, 0.5, 20, 0, 0.5]
+ const out = midpointBezierPolyline(pts)
+ for (let i = 0; i < out.length; i++) assert.ok(Number.isFinite(out[i]), `non-finite at ${i}`)
+ // single curve segment: out[0] = P0, sample s lands at index s → t=0.5 is index 3,
+ // exactly on the control point (the original sample)
+ const mid = triple(out, BEZIER_SAMPLES_PER_CURVE / 2)
+ assert.deepEqual(mid, [10, 0, 0.5])
+})
+
+test('smoothing output is NaN-free for nasty finite inputs', () => {
+ const nasties = [
+ [0, 0, 0.5, 5, 5, 0.5, 5, 5, 0.5, 5, 5, 0.5, 20, 20, 0.5], // repeated points
+ [0, 0, 0, 1, 0, 1, 2, 0, 0, 3, 0, 1, 4, 0, 0], // zig-zag pressure
+ [1e6, -1e6, 0.5, 1e6 + 0.001, 1e6, 0.5, 2e6, 2e6, 0.5], // huge spans
+ ]
+ for (const pts of nasties) {
+ const out = midpointBezierPolyline(pts)
+ for (let i = 0; i < out.length; i++) assert.ok(Number.isFinite(out[i]), `non-finite at ${i}`)
+ }
+})
+
+test('pressure is interpolated within the neighbouring range', () => {
+ const pts = [0, 0, 0.2, 10, 0, 0.8, 20, 0, 0.4]
+ const out = midpointBezierPolyline(pts)
+ for (let i = 2; i < out.length; i += 3) {
+ assert.ok(out[i] >= 0.2 && out[i] <= 0.8, `pressure out of range: ${out[i]}`)
+ }
+})
+
+// --- incremental wet-ink smoothing ---
+
+/** synthetic wavy stroke with n points (same shape family as the benchmark) */
+const wavy = (n: number): number[] => {
+ const pts: number[] = []
+ for (let i = 0; i < n; i++) {
+ const t = i / (n - 1 || 1)
+ pts.push(t * 800, 300 + Math.sin(t * Math.PI * 6) * 120, 0.5)
+ }
+ return pts
+}
+
+test('incremental smoothing matches the full resample at every prefix', () => {
+ const pts = wavy(200)
+ const st = createIncrementalSmooth()
+ for (let k = 1; k <= 200; k++) {
+ const partial = pts.slice(0, k * 3)
+ const out = updateIncrementalSmooth(st, partial)
+ assert.deepEqual(out.pts, midpointBezierPolyline(partial), `wet/dry mismatch at ${k} points`)
+ assert.equal(out, st) // same state object, mutated in place
+ }
+})
+
+test('incremental smoothing: cold start mid-stroke still matches', () => {
+ const pts = wavy(120)
+ const st = createIncrementalSmooth()
+ const out = updateIncrementalSmooth(st, pts) // attached to a stroke already in progress
+ assert.deepEqual(out.pts, midpointBezierPolyline(pts))
+})
+
+test('incremental smoothing: <3 samples pass through by identity, then grow', () => {
+ const st = createIncrementalSmooth()
+ const dot = [3, 4, 0.5]
+ assert.equal(updateIncrementalSmooth(st, dot).pts, dot)
+ const line = [0, 0, 0.5, 10, 10, 0.5]
+ assert.equal(updateIncrementalSmooth(st, line).pts, line)
+ const grown = updateIncrementalSmooth(st, [0, 0, 0.5, 10, 10, 0.5, 20, 4, 0.5])
+ assert.deepEqual(grown.pts, midpointBezierPolyline([0, 0, 0.5, 10, 10, 0.5, 20, 4, 0.5]))
+})
+
+test('incremental smoothing: unchanged stroke is a no-op', () => {
+ const pts = wavy(50)
+ const st = createIncrementalSmooth()
+ updateIncrementalSmooth(st, pts)
+ const snapshot = st.pts.slice()
+ const out = updateIncrementalSmooth(st, pts)
+ assert.equal(out.pts.length, snapshot.length)
+ assert.deepEqual(out.pts, snapshot)
+})
+
+test('incremental smoothing: input array is never mutated', () => {
+ const pts = wavy(30)
+ const snapshot = pts.slice()
+ const st = createIncrementalSmooth()
+ updateIncrementalSmooth(st, pts)
+ assert.deepEqual(pts, snapshot)
+})
diff --git a/src/ink/smooth.ts b/src/ink/smooth.ts
new file mode 100644
index 0000000..72701f5
--- /dev/null
+++ b/src/ink/smooth.ts
@@ -0,0 +1,127 @@
+/**
+ * Ink smoothing primitives — pure functions.
+ *
+ * Approach (idea learned from studying established whiteboard behaviour, not code):
+ * drop near-duplicate samples, then treat the stroke as the midpoint quadratic
+ * Bézier — adjacent sample midpoints are the curve ends, the original sample is
+ * the control point. Endpoints stay pinned so taps and dots are untouched.
+ */
+
+export interface InkPoint {
+ x: number
+ y: number
+ pressure: number
+}
+
+/** Near-point threshold in DIP (CSS px) for the smoothing experiment (main uses a looser 0.8). */
+export const SMOOTH_MIN_DIST_DIP = 0.5
+
+/** How many polyline samples each quadratic curve segment is subdivided into. */
+export const BEZIER_SAMPLES_PER_CURVE = 6
+
+/**
+ * Append one real sample to a flat [x, y, pressure, ...] stroke, skipping points
+ * closer than `minScreenDist` screen px to the current tip (world coords + view
+ * scale → screen distance, same rule main applies inline with 0.8).
+ * Pure: returns a new array, or the same array when the point is skipped.
+ */
+export function appendStrokePoint(pts: number[], p: InkPoint, minScreenDist: number, scale: number): number[] {
+ const n = pts.length
+ if (n >= 3) {
+ const dx = p.x - pts[n - 3]
+ const dy = p.y - pts[n - 2]
+ if (Math.hypot(dx, dy) * scale < minScreenDist) return pts
+ }
+ return [...pts, p.x, p.y, p.pressure]
+}
+
+const quad = (c0: number, c1: number, c2: number, t: number) => {
+ const u = 1 - t
+ return u * u * c0 + 2 * u * t * c1 + t * t * c2
+}
+
+/** Piecewise-linear pressure between the three control samples of one curve segment. */
+const quadPressure = (p0: number, p1: number, p2: number, t: number) =>
+ t <= 0.5 ? p0 + (p1 - p0) * t * 2 : p1 + (p2 - p1) * (t - 0.5) * 2
+
+/**
+ * Push the samples of curve segment i (control point P[i], ends at the adjacent
+ * midpoints) into `out`. Shared by the whole-stroke resample and the incremental
+ * cache, so wet (incremental) and dry (resampled) shapes are identical by
+ * construction, not just by coincidence of math.
+ */
+function pushSegmentSamples(pts: number[], i: number, samplesPerCurve: number, out: number[]): void {
+ const ax = (pts[(i - 1) * 3] + pts[i * 3]) / 2
+ const ay = (pts[(i - 1) * 3 + 1] + pts[i * 3 + 1]) / 2
+ const bx = (pts[i * 3] + pts[(i + 1) * 3]) / 2
+ const by = (pts[(i + 1) * 3 + 1] + pts[(i + 1) * 3 + 1]) / 2
+ const cx = pts[i * 3]
+ const cy = pts[i * 3 + 1]
+ const pa = pts[(i - 1) * 3 + 2]
+ const pc = pts[i * 3 + 2]
+ const pb = pts[(i + 1) * 3 + 2]
+ for (let s = 1; s <= samplesPerCurve; s++) {
+ const t = s / samplesPerCurve
+ out.push(quad(ax, cx, bx, t), quad(ay, cy, by, t), quadPressure(pa, pc, pb, t))
+ }
+}
+
+/**
+ * Sample the midpoint quadratic Bézier through the stroke as a flat
+ * [x, y, pressure, ...] polyline. The first and last samples are preserved
+ * exactly (value and identity of the array when there is nothing to smooth);
+ * pressure is interpolated between samples. Strokes with fewer than 3 samples
+ * (dots, two-point lines) are returned unchanged.
+ */
+export function midpointBezierPolyline(pts: number[], samplesPerCurve = BEZIER_SAMPLES_PER_CURVE): number[] {
+ const n = pts.length / 3
+ if (n < 3) return pts
+ const out: number[] = [pts[0], pts[1], pts[2]]
+ for (let i = 1; i < n - 1; i++) pushSegmentSamples(pts, i, samplesPerCurve, out)
+ out.push(pts[(n - 1) * 3], pts[(n - 1) * 3 + 1], pts[(n - 1) * 3 + 2])
+ return out
+}
+
+// --- incremental wet-ink smoothing -------------------------------------------
+//
+// A midpoint-Bézier segment for control point P[i] only ever depends on
+// P[i-1..i+1], so each segment is final the moment P[i+1] arrives: the smoothed
+// prefix never changes as the stroke grows. The incremental cache exploits that
+// to render wet ink with O(1) work per pointer event instead of resampling the
+// whole stroke every frame, while staying bit-identical to the dry bake.
+
+export interface IncrementalSmoothState {
+ /** smoothed polyline so far (flat triples); === the input array while < 3 samples */
+ pts: number[]
+ /** curve segments already emitted (segments 1..emitted are final) */
+ emitted: number
+}
+
+export function createIncrementalSmooth(): IncrementalSmoothState {
+ return { pts: [], emitted: 0 }
+}
+
+/**
+ * Feed the (full, growing) stroke into the cache and return it. The result's
+ * `pts` equals `midpointBezierPolyline(pts)` for every prefix — wet and dry
+ * shapes match exactly at every frame. Mutates and returns `state`; `pts` is
+ * only read. Calling it again with an unchanged stroke is a no-op.
+ */
+export function updateIncrementalSmooth(state: IncrementalSmoothState, pts: number[], samplesPerCurve = BEZIER_SAMPLES_PER_CURVE): IncrementalSmoothState {
+ const n = pts.length / 3
+ if (n < 3) {
+ state.pts = pts
+ state.emitted = 0
+ return state
+ }
+ if (state.emitted === 0) {
+ // cold start (also covers being attached to a stroke already in progress)
+ state.pts = [pts[0], pts[1], pts[2]]
+ } else {
+ state.pts.length -= 3 // drop the previous trailing endpoint
+ }
+ for (let i = state.emitted + 1; i <= n - 2; i++) pushSegmentSamples(pts, i, samplesPerCurve, state.pts)
+ state.emitted = n - 2
+ state.pts.push(pts[(n - 1) * 3], pts[(n - 1) * 3 + 1], pts[(n - 1) * 3 + 2])
+ return state
+}
diff --git a/src/ink/tolerance.test.ts b/src/ink/tolerance.test.ts
new file mode 100644
index 0000000..69d728c
--- /dev/null
+++ b/src/ink/tolerance.test.ts
@@ -0,0 +1,72 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ DRAG_THRESHOLD_DIP,
+ HIT_TOLERANCE_DIP,
+ TAP_MAX_DURATION_MS,
+ dragThresholdWorld,
+ hasRealPressure,
+ hitToleranceWorld,
+ isTapStroke,
+ toPointerKind,
+} from './tolerance'
+
+test('pointer kind mapping: mouse / touch / pen, unknown → mouse', () => {
+ assert.equal(toPointerKind('mouse'), 'mouse')
+ assert.equal(toPointerKind('touch'), 'touch')
+ assert.equal(toPointerKind('pen'), 'pen')
+ assert.equal(toPointerKind(''), 'mouse')
+ assert.equal(toPointerKind('fingerprint'), 'mouse')
+})
+
+test('thresholds come in the three flavours (mouse / touch / pen)', () => {
+ assert.deepEqual(DRAG_THRESHOLD_DIP, { mouse: 1, touch: 16, pen: 4 })
+ assert.deepEqual(HIT_TOLERANCE_DIP, { mouse: 3, touch: 10, pen: 5 })
+})
+
+test('drag threshold is DIP divided by the current zoom', () => {
+ assert.equal(dragThresholdWorld('pen', 2), 2) // 4 DIP at zoom 2 → 2 world units → 4 screen px
+ assert.equal(dragThresholdWorld('mouse', 4), 0.25) // tight at high zoom
+ assert.equal(dragThresholdWorld('touch', 0.5), 32) // loose when zoomed out
+})
+
+test('hit tolerance is DIP divided by the current zoom', () => {
+ assert.equal(hitToleranceWorld('touch', 0.5), 20)
+ assert.equal(hitToleranceWorld('pen', 1), 5)
+ assert.equal(hitToleranceWorld('mouse', 2), 1.5)
+})
+
+test('pressure: constant 0.5 or 0 means a pressure-less device', () => {
+ assert.equal(hasRealPressure([]), false)
+ assert.equal(hasRealPressure([0, 0, 0.5, 10, 10, 0.5]), false)
+ assert.equal(hasRealPressure([0, 0, 0, 10, 10, 0]), false)
+ assert.equal(hasRealPressure([0, 0, 0, 10, 10, 0.5]), false) // mix of 0 and 0.5 is still pressure-less
+ assert.equal(hasRealPressure([0, 0, 0.5, 10, 10, 0.72]), true)
+ assert.equal(hasRealPressure([0, 0, 0.12]), true)
+})
+
+test('tap detection: whole gesture inside the drag threshold', () => {
+ const threshold = 4 // pen at zoom 1
+ assert.equal(isTapStroke([10, 10, 0.5], threshold), true) // single point
+ assert.equal(isTapStroke([10, 10, 0.5, 10.5, 10.4, 0.5, 10.9, 10.2, 0.5], threshold), true) // micro jitter
+ assert.equal(isTapStroke([10, 10, 0.5, 10.5, 10.4, 0.5, 18, 12, 0.5], threshold), false) // real drag
+ // exactly at the threshold counts as a drag (threshold is exclusive)
+ assert.equal(isTapStroke([0, 0, 0.5, 4, 0, 0.5], 4), false)
+ assert.equal(isTapStroke([0, 0, 0.5, 3.99, 0, 0.5], 4), true)
+})
+
+test('tap detection requires short displacement AND a quick press', () => {
+ const threshold = 4
+ const microJitter = [10, 10, 0.5, 10.5, 10.4, 0.5, 10.9, 10.2, 0.5]
+ // quick press inside the threshold → tap
+ assert.equal(isTapStroke(microJitter, threshold, 80), true)
+ // same tiny displacement but the pen rested: a deliberate tick stays a stroke
+ assert.equal(isTapStroke(microJitter, threshold, 400), false)
+ // boundary is inclusive on the duration
+ assert.equal(isTapStroke(microJitter, threshold, TAP_MAX_DURATION_MS), true)
+ assert.equal(isTapStroke(microJitter, threshold, TAP_MAX_DURATION_MS + 1), false)
+ // quick but beyond the drag threshold → drag, not tap
+ assert.equal(isTapStroke([0, 0, 0.5, 8, 0, 0.5], threshold, 50), false)
+ // no duration given → old displacement-only rule
+ assert.equal(isTapStroke(microJitter, threshold), true)
+})
diff --git a/src/ink/tolerance.ts b/src/ink/tolerance.ts
new file mode 100644
index 0000000..ba26e13
--- /dev/null
+++ b/src/ink/tolerance.ts
@@ -0,0 +1,66 @@
+/**
+ * Per-pointer-type tolerances — pure functions.
+ *
+ * Idea learned from studying established whiteboard behaviour (not their code):
+ * mice want tight tolerances, fingers need room, pens sit in between. The drag
+ * threshold (tap vs. drag) and the eraser hit tolerance each come in three
+ * flavours, and the drag threshold is specified in DIP so it must be divided by
+ * the current zoom to become a world-space distance.
+ */
+
+export type PointerKind = 'mouse' | 'touch' | 'pen'
+
+/** Map a DOM pointerType onto the three kinds; anything unknown behaves like a mouse. */
+export function toPointerKind(pointerType: string): PointerKind {
+ return pointerType === 'touch' || pointerType === 'pen' ? pointerType : 'mouse'
+}
+
+/** Tap-vs-drag thresholds in DIP (mouse / touch / pen). */
+export const DRAG_THRESHOLD_DIP: Record = { mouse: 1, touch: 16, pen: 4 }
+
+/** Eraser hit tolerances in DIP (mouse / touch / pen). */
+export const HIT_TOLERANCE_DIP: Record = { mouse: 3, touch: 10, pen: 5 }
+
+/**
+ * Drag threshold in world units — DIP divided by the current zoom, so the
+ * on-screen distance stays constant while zooming. `scale` is the board's view
+ * scale (clamped to [0.2, 4] by the app).
+ */
+export function dragThresholdWorld(kind: PointerKind, scale: number): number {
+ return DRAG_THRESHOLD_DIP[kind] / scale
+}
+
+/** Eraser hit tolerance in world units, same DIP ÷ zoom rule. */
+export function hitToleranceWorld(kind: PointerKind, scale: number): number {
+ return HIT_TOLERANCE_DIP[kind] / scale
+}
+
+/**
+ * Does any sample carry a real pressure value? Constant 0.5 (main's "no
+ * pressure" fill) or constant 0 mean a pressure-less device — render and think
+ * of the stroke as pressure-free, never as pressure-varying.
+ */
+export function hasRealPressure(pts: number[]): boolean {
+ for (let i = 2; i < pts.length; i += 3) if (pts[i] !== 0.5 && pts[i] !== 0) return true
+ return false
+}
+
+/** A press shorter than this counts as a tap even if it barely moved — deliberate short ticks take longer. */
+export const TAP_MAX_DURATION_MS = 250
+
+/**
+ * Is this stroke a tap rather than a drag? Two conditions, both required:
+ * every sample stays within `thresholdWorld` of the pen-down point AND the
+ * press was quick (≤ TAP_MAX_DURATION_MS) — a slow, deliberate short tick stays
+ * a stroke. `durationMs` is the press duration (pointerdown → pointerup);
+ * without it the old displacement-only rule applies. Single-point strokes are
+ * always taps.
+ */
+export function isTapStroke(pts: number[], thresholdWorld: number, durationMs?: number): boolean {
+ const x0 = pts[0]
+ const y0 = pts[1]
+ for (let i = 0; i < pts.length; i += 3) {
+ if (Math.hypot(pts[i] - x0, pts[i + 1] - y0) >= thresholdWorld) return false
+ }
+ return durationMs === undefined || durationMs <= TAP_MAX_DURATION_MS
+}
From 99f26b26a4040418324c283134ac57f4cccd35e2 Mon Sep 17 00:00:00 2001
From: DNT_OF <3174600270@qq.com>
Date: Fri, 13 Nov 2026 09:48:30 +0800
Subject: [PATCH 2/9] wip(ink): English labels in the hidden ink debug panel
(i18n smoke)
---
src/ink/InkDebugPanel.tsx | 26 +++++++++++++-------------
src/ink/replay.test.ts | 2 +-
src/ink/replay.ts | 12 ++++++------
3 files changed, 20 insertions(+), 20 deletions(-)
diff --git a/src/ink/InkDebugPanel.tsx b/src/ink/InkDebugPanel.tsx
index 3f49fef..44374d3 100644
--- a/src/ink/InkDebugPanel.tsx
+++ b/src/ink/InkDebugPanel.tsx
@@ -10,12 +10,12 @@ import { inkFlagsStore, type InkFlags } from './flags'
*/
const SWITCHES: { key: keyof InkFlags; label: string }[] = [
- { key: 'smoothing', label: '平滑(去近点+中点贝塞尔)' },
- { key: 'prediction', label: '预测显示' },
- { key: 'predictionGhost', label: '预测尾浅色渲染' },
- { key: 'capsuleEraser', label: '扫掠胶囊橡皮' },
- { key: 'pointerTolerance', label: '按指针类型容差' },
- { key: 'wetIncremental', label: '湿墨增量重绘' },
+ { key: 'smoothing', label: 'Smoothing (near-point drop + midpoint Bezier)' },
+ { key: 'prediction', label: 'Prediction' },
+ { key: 'predictionGhost', label: 'Prediction ghost tail' },
+ { key: 'capsuleEraser', label: 'Swept capsule eraser' },
+ { key: 'pointerTolerance', label: 'Per-pointer tolerance' },
+ { key: 'wetIncremental', label: 'Incremental wet ink' },
]
const Row = ({ k, v }: { k: string; v: string }) => (
@@ -59,7 +59,7 @@ export function InkDebugPanel() {
data-no-board
className="absolute bottom-3 left-3 z-40 w-[300px] rounded-xl border border-black/10 bg-[#f8f2e4]/95 p-3 font-mono text-[11px] leading-relaxed text-kraft-800 shadow-[0_10px_28px_rgba(60,40,20,0.25)]"
>
- 墨迹实验面板(?ink-debug=1)
+ Ink experiments (?ink-debug=1)
{SWITCHES.map(({ key, label }) => (
-
-
-
-
- 0 ? ` ≈ ${(1000 / frameMs).toFixed(0)} Hz` : ''}`} />
-
+
+
+
+
+ 0 ? ` ≈ ${(1000 / frameMs).toFixed(0)} Hz` : ''}`} />
+
)
diff --git a/src/ink/replay.test.ts b/src/ink/replay.test.ts
index a49fa57..6d66b81 100644
--- a/src/ink/replay.test.ts
+++ b/src/ink/replay.test.ts
@@ -27,7 +27,7 @@ test('makeTrajectory: reproducible, monotonic time, noise bounded around exact t
test('replayTrajectory: deterministic and counts moments', () => {
const traj = makeTrajectory('straight', { rateHz: 60, seed: 42 })
- const cand: ReplayCandidate = { name: 'A-现行默认' }
+ const cand: ReplayCandidate = { name: 'A-current-default' }
const s1 = replayTrajectory(traj, cand, 60)
const s2 = replayTrajectory(traj, cand, 60)
assert.deepEqual(s1, s2)
diff --git a/src/ink/replay.ts b/src/ink/replay.ts
index c7029a0..d5d9d27 100644
--- a/src/ink/replay.ts
+++ b/src/ink/replay.ts
@@ -25,12 +25,12 @@ export function mulberry32(seed: number): () => number {
export type TrajectoryScenario = 'straight' | 'fastArc' | 'sharpTurn' | 'jitter' | 'pause' | 'slowTick'
export const SCENARIO_LABELS: Record = {
- straight: '直线',
- fastArc: '快弧(小半径)',
- sharpTurn: '急转',
- jitter: '抖动',
- pause: '停笔',
- slowTick: '慢短笔',
+ straight: 'straight line',
+ fastArc: 'fast arc (small radius)',
+ sharpTurn: 'sharp turn',
+ jitter: 'jitter',
+ pause: 'pause',
+ slowTick: 'slow short tick',
}
const SCENARIO_DURATION_MS: Record = {
From 6f50aaf47e03fa045403cc95572a9c023e66b44e Mon Sep 17 00:00:00 2001
From: DNT_OF <3174600270@qq.com>
Date: Fri, 13 Nov 2026 09:48:31 +0800
Subject: [PATCH 3/9] ios: unsigned IPA path for TrollStore/jailbreak sideload;
no MCP listener on mobile
package-ios.sh --unsigned runs tauri ios build --no-sign, optionally ldid fake-signs, and writes MathScrap--ios-unsigned.ipa plus SHA256SUMS. The signed --device path is unchanged. The generated AppIcon set is replaced with the committed opaque square icons. package-ios.yml defaults to unsigned and is callable from package.yml. The loopback MCP hub is cfg(desktop) only.
---
.github/workflows/package-ios.yml | 45 ++++++++++++++++---
scripts/package-ios.sh | 75 ++++++++++++++++++++++++++++++-
src-tauri/src/lib.rs | 16 +++++--
3 files changed, 123 insertions(+), 13 deletions(-)
diff --git a/.github/workflows/package-ios.yml b/.github/workflows/package-ios.yml
index cb0b3e9..e57e3b4 100644
--- a/.github/workflows/package-ios.yml
+++ b/.github/workflows/package-ios.yml
@@ -1,16 +1,23 @@
name: package-ios
-# Manual only. A macOS runner is required and this file does not run on push.
+# Manual, or called by package.yml. A macOS runner is required.
+# unsigned: device IPA with no Apple signature, for TrollStore or a jailbroken device only.
on:
workflow_dispatch:
inputs:
target:
- description: simulator builds a .app for the iOS Simulator. device exports an IPA only when signing secrets are set.
+ description: unsigned = device IPA without an Apple signature (TrollStore / jailbreak sideload). simulator = .app for the iOS Simulator. device = signed IPA, only when signing secrets are set.
type: choice
options:
+ - unsigned
- simulator
- device
- default: simulator
+ default: unsigned
+ workflow_call:
+ inputs:
+ target:
+ type: string
+ default: unsigned
permissions:
contents: read
@@ -18,6 +25,7 @@ permissions:
jobs:
ios:
runs-on: macos-latest
+ timeout-minutes: 90
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
@@ -31,9 +39,23 @@ jobs:
- uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- - name: CocoaPods
- run: brew install cocoapods
+ - name: Build tools
+ run: |
+ brew install cocoapods xcodegen
+ brew install ldid || echo "ldid is unavailable; the IPA will carry no ad-hoc signature."
- run: npm ci
+ - name: Unsigned IPA
+ if: inputs.target == 'unsigned'
+ run: bash scripts/package-ios.sh --unsigned
+ - name: Check the unsigned IPA
+ if: inputs.target == 'unsigned'
+ run: |
+ cd packaging/out
+ ls -l
+ shasum -a 256 -c SHA256SUMS
+ ipa="$(ls *-ios-unsigned.ipa)"
+ unzip -l "$ipa" | grep -E 'Payload/[^/]+\.app/(Info\.plist|AppIcon)' | head -20
+ cat PROVENANCE-ios.txt
- name: Simulator app
if: inputs.target == 'simulator'
run: bash scripts/package-ios.sh --simulator
@@ -48,10 +70,19 @@ jobs:
APPLE_API_KEY_PATH: ${{ secrets.APPLE_API_KEY_PATH }}
run: bash scripts/package-ios.sh --device
- uses: actions/upload-artifact@v4
- if: always() && hashFiles('packaging/out/**') != ''
+ if: inputs.target == 'unsigned'
with:
name: mathscrap-ios
+ path: |
+ packaging/out/*.ipa
+ packaging/out/PROVENANCE-ios.txt
+ packaging/out/SHA256SUMS
+ if-no-files-found: error
+ - uses: actions/upload-artifact@v4
+ if: always() && inputs.target != 'unsigned' && hashFiles('packaging/out/**') != ''
+ with:
+ name: mathscrap-ios-${{ inputs.target }}
path: |
packaging/out/*
src-tauri/gen/apple/**/*.app
- if-no-files-found: warn
+ if-no-files-found: warn
\ No newline at end of file
diff --git a/scripts/package-ios.sh b/scripts/package-ios.sh
index 4f7a7a2..f44feaa 100755
--- a/scripts/package-ios.sh
+++ b/scripts/package-ios.sh
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
-# iOS Simulator .app, or a signed IPA when Apple signing inputs are present.
+# iOS Simulator .app, a signed IPA when Apple signing inputs are present,
+# or (--unsigned) an unsigned device IPA for TrollStore / jailbroken sideloading.
# This script never enrolls in the Apple Developer Program and never creates a certificate.
set -euo pipefail
cd "$(dirname "$0")/.."
@@ -9,9 +10,10 @@ for arg in "$@"; do
case "$arg" in
--simulator) target="simulator" ;;
--device) target="device" ;;
+ --unsigned) target="unsigned" ;;
*)
echo "Unknown argument: $arg" >&2
- echo "Usage: scripts/package-ios.sh [--simulator|--device]" >&2
+ echo "Usage: scripts/package-ios.sh [--simulator|--device|--unsigned]" >&2
exit 2
;;
esac
@@ -71,6 +73,27 @@ if [[ ! -d src-tauri/gen/apple ]]; then
npx tauri ios init --ci
fi
+# The generated project starts with the template icon. Copy the committed opaque
+# square icons (made from packaging/logo/app-icon.png) over it. iOS applies the
+# rounded mask itself, so no transparent corners are baked in.
+iconset="src-tauri/gen/apple/Assets.xcassets/AppIcon.appiconset"
+if [[ -d "$iconset" ]]; then
+ copied=0
+ for png in "$iconset"/*.png; do
+ [[ -e "$png" ]] || continue
+ src="src-tauri/icons/ios/$(basename "$png")"
+ if [[ -f "$src" ]]; then
+ cp "$src" "$png"
+ copied=$((copied + 1))
+ fi
+ done
+ if [[ "$copied" -eq 0 ]]; then
+ echo "No AppIcon file in $iconset matched src-tauri/icons/ios. Refusing to ship the template icon." >&2
+ exit 4
+ fi
+ echo "app icon: copied $copied files from src-tauri/icons/ios"
+fi
+
version="$(node -p "require('./package.json').version")"
mkdir -p packaging/out
@@ -82,6 +105,54 @@ if [[ "$target" == "simulator" ]]; then
exit 0
fi
+if [[ "$target" == "unsigned" ]]; then
+ # Archive without code signing; tauri wraps Payload/MathScrap.app into an .ipa.
+ npx tauri ios build --target aarch64 --no-sign --ci
+ built="$(find src-tauri/gen/apple/build -type f -name '*.ipa' | sort | head -1)"
+ if [[ -z "$built" ]]; then
+ echo "tauri ios build --no-sign finished but no .ipa was found under src-tauri/gen/apple/build." >&2
+ exit 1
+ fi
+ work="$(mktemp -d)"
+ unzip -q "$built" -d "$work"
+ app="$(find "$work/Payload" -maxdepth 1 -type d -name '*.app' | head -1)"
+ if [[ -z "$app" ]]; then
+ echo "The IPA has no Payload/*.app." >&2
+ exit 1
+ fi
+ exe="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app/Info.plist")"
+ minos="$(/usr/libexec/PlistBuddy -c 'Print :MinimumOSVersion' "$app/Info.plist" 2>/dev/null || echo unknown)"
+ bundle_id="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Info.plist")"
+ echo "bundle $bundle_id executable $exe MinimumOSVersion $minos"
+ # Optional ad-hoc "fake" signature so TrollStore keeps the entitlements. Not an Apple signature.
+ fakesign="none"
+ if command -v ldid >/dev/null 2>&1; then
+ ent="$(find src-tauri/gen/apple -maxdepth 2 -name '*.entitlements' | head -1)"
+ if [[ -n "$ent" ]]; then
+ ldid -S"$ent" "$app/$exe"
+ else
+ ldid -S "$app/$exe"
+ fi
+ fakesign="ldid"
+ fi
+ dest="packaging/out/MathScrap-${version}-ios-unsigned.ipa"
+ rm -f "$dest"
+ (cd "$work" && zip -qry "$OLDPWD/$dest" Payload)
+ rm -rf "$work"
+ {
+ echo "ios_ipa=$(basename "$dest")"
+ echo "ios_signing=unsigned (no Apple certificate or provisioning profile)"
+ echo "ios_fakesign=$fakesign"
+ echo "ios_bundle_id=$bundle_id"
+ echo "ios_minimum_os=$minos"
+ echo "ios_install=TrollStore or a jailbroken device only; stock iOS refuses it"
+ } > packaging/out/PROVENANCE-ios.txt
+ node scripts/checksum-artifacts.mjs packaging/out
+ echo "artifact $dest"
+ echo "This IPA is unsigned. It installs only through TrollStore or on a jailbroken device."
+ exit 0
+fi
+
signed=0
if [[ -n "${IOS_CERTIFICATE:-}" && -n "${IOS_CERTIFICATE_PASSWORD:-}" && -n "${IOS_MOBILE_PROVISION:-}" ]]; then
signed=1
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 54d56c1..4d2b52c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -3,7 +3,9 @@ use mcpserve::Hub;
pub fn mcp_stdio() {
mcpserve::stdio_main();
}
-use tauri::{Emitter, Manager};
+#[cfg(desktop)]
+use tauri::Emitter;
+use tauri::Manager;
fn close_mcp(app: &impl Manager) {
if let Some(hub) = app.try_state::() {
@@ -38,9 +40,15 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.setup(|app| {
- let handle = app.handle().clone();
- let dispatch = std::sync::Arc::new(move |job: serde_json::Value| handle.emit("mcp-call", job).is_ok());
- let hub = Hub::start(dispatch).unwrap_or_else(|_| Hub::disabled());
+ // The loopback MCP listener is a desktop feature. iOS and Android never open it.
+ #[cfg(desktop)]
+ let hub = {
+ let handle = app.handle().clone();
+ let dispatch = std::sync::Arc::new(move |job: serde_json::Value| handle.emit("mcp-call", job).is_ok());
+ Hub::start(dispatch).unwrap_or_else(|_| Hub::disabled())
+ };
+ #[cfg(mobile)]
+ let hub = Hub::disabled();
app.manage(hub);
Ok(())
})
From 28cc88229fdc0ccb3ed2d1b9948b6cb81668200b Mon Sep 17 00:00:00 2001
From: DNT_OF <3174600270@qq.com>
Date: Fri, 13 Nov 2026 09:48:31 +0800
Subject: [PATCH 4/9] icons: rounded-corner desktop and web icons; iOS keeps
the opaque square master
---
packaging/logo/SHA256SUMS.txt | 1 +
packaging/logo/app-icon-rounded.png | Bin 0 -> 916496 bytes
public/favicon.png | Bin 63191 -> 66863 bytes
scripts/make-rounded-icon.mjs | 41 ++++++++++++++++++++++++++
src-tauri/icons/128x128.png | Bin 19033 -> 20781 bytes
src-tauri/icons/128x128@2x.png | Bin 63191 -> 66863 bytes
src-tauri/icons/32x32.png | Bin 1975 -> 2242 bytes
src-tauri/icons/64x64.png | Bin 6046 -> 6722 bytes
src-tauri/icons/Square107x107Logo.png | Bin 14090 -> 15562 bytes
src-tauri/icons/Square142x142Logo.png | Bin 22572 -> 24578 bytes
src-tauri/icons/Square150x150Logo.png | Bin 24686 -> 26869 bytes
src-tauri/icons/Square284x284Logo.png | Bin 76366 -> 80255 bytes
src-tauri/icons/Square30x30Logo.png | Bin 1771 -> 1992 bytes
src-tauri/icons/Square310x310Logo.png | Bin 89525 -> 93850 bytes
src-tauri/icons/Square44x44Logo.png | Bin 3276 -> 3736 bytes
src-tauri/icons/Square71x71Logo.png | Bin 7186 -> 7949 bytes
src-tauri/icons/Square89x89Logo.png | Bin 10463 -> 11491 bytes
src-tauri/icons/StoreLogo.png | Bin 4025 -> 4563 bytes
src-tauri/icons/icon.icns | Bin 1306437 -> 1333794 bytes
src-tauri/icons/icon.ico | Bin 79127 -> 84583 bytes
src-tauri/icons/icon.png | Bin 224699 -> 232056 bytes
21 files changed, 42 insertions(+)
create mode 100644 packaging/logo/app-icon-rounded.png
create mode 100644 scripts/make-rounded-icon.mjs
diff --git a/packaging/logo/SHA256SUMS.txt b/packaging/logo/SHA256SUMS.txt
index 0d88221..b5855fd 100644
--- a/packaging/logo/SHA256SUMS.txt
+++ b/packaging/logo/SHA256SUMS.txt
@@ -1 +1,2 @@
b61b9160596a0f4e7fa1a9a9296d341687b3a158e24fdf082f24c1bb208c57bf app-icon.png
+a84717bac33d0e3a566e025e77a51e8c2bd40cbb487dec26090d9dd4d5339509 app-icon-rounded.png
diff --git a/packaging/logo/app-icon-rounded.png b/packaging/logo/app-icon-rounded.png
new file mode 100644
index 0000000000000000000000000000000000000000..da17fb99b23bd245d5a906a6759b156cba68babc
GIT binary patch
literal 916496
zcmXt>3tUxo*8aWUl~Rvl5oF$Sdm%JaMuY$n5s`Ba8&DyfFmn265;zG2f_L&*QtE-c
z1adzIR0evzFd{JO8S7N~_B!KbGDPagWF{9U0VVl=*LMCi7Q#Mz|MvQ=^{i(-YwbO|
z^veQ=4|#4#uU@@|2Q6M`?A5Cu-}dV@XaN7ocwySMUc(<>3tH%_CilMgx3A5gHy>Dj
z`|R5By>@OM_S`tjtXF0~^TL+Tdgr|Kr=))CKlUn~y?JMD{_Og1!U8tGTRW!iYDL}U
z6Lgjnf&+G#
z?7>#OXHo2rxwkCcclx&W?P(pjv8az|Gxg(i*NiD2
zn(~d6mXG+i2iN%b?!$#u;gy!|H~u(XN!4Xq4u@4*?uDI)-URT8vdrMhe@4U`8e*5&6WtjPx$zOe_Ec5sz<6*#)U3O!_9=nH97^||j
z1!jNN#+7$2u^9~>D#t169>X}DzhghYG
z)5K{QQM>6ywg^tIOV!2K&QNrxN;I3F<%q>Qme~B&VdjfQwr*i@Y_*w?op$c@BKIV_=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