Add stats collection and first-run on-glasses onboarding app

This commit is contained in:
James Babcock committed 2026-10-10 17:33:32 -07:00
1 parent 84baee9c76
commit 406cefe0c5
73 files changed
+3906 -98

No files matched your search

Binary file not shown.
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Locate the LVGL font descriptors that app/g2/firmware-fonts.ts extracts.
Usage: scripts/find-firmware-fonts.py <stock EVENOTA .bin> [<another .bin>...]
Scans the main-app component (ota/s200_firmware_ota.bin, loaded at 0x438000
after a 0x20-byte preamble) for lv_font_fmt_txt_dsc_t structs with 4 bpp,
bitmap format 3 and a plausible cmap table, and prints one row per font. After
a firmware rebase, match rows to FONT_SPECS by cmap count / code-point count
(the EvenHub fallback chain is n=12/8081, n=9/9566, n=4/11590) and copy the
new `dsc` addresses into firmware-fonts.ts.
"""
import struct, sys
BASE=0x438000
def mainapp(path):
d=open(path,'rb').read()
for i in range(8):
toc=0x40+i*16; off=struct.unpack_from('<I',d,toc+4)[0]
if not off or off>len(d): continue
size=struct.unpack_from('<I',d,off+8)[0]
name=d[off+48:off+128].split(b'\0')[0]
if name==b'ota/s200_firmware_ota.bin':
p=off+128+0x20; return d[p:p+size-0x20]
class Img:
def __init__(s,b): s.b=b; s.end=BASE+len(b)
def ok(s,a,n=4): return BASE<=a and a+n<=s.end
def u32(s,a): return struct.unpack_from('<I',s.b,a-BASE)[0]
def u16(s,a): return struct.unpack_from('<H',s.b,a-BASE)[0]
def i16(s,a): return struct.unpack_from('<h',s.b,a-BASE)[0]
def find_dscs(img):
out=[]
for off in range(0,len(img.b)-20,4):
a=BASE+off
bm,gd,cm,kd=struct.unpack_from('<IIII',img.b,off)
if not(img.ok(bm) and img.ok(gd) and img.ok(cm)): continue
if kd!=0 and not img.ok(kd): continue
packed=img.u16(a+18); n=packed&0x1ff; bpp=(packed>>9)&0xf; fmt=(packed>>14)&3
if bpp!=4 or fmt!=3 or n==0 or n>64: continue
# cmap entries 20 bytes: range_start u32, range_length u16, glyph_id_start u16, list ptr, list ptr, list_length u16, type u8
good=True; total=0
for i in range(n):
c=cm+i*20
if not img.ok(c,20): good=False;break
rs=img.u32(c); rl=img.u16(c+4); t=img.b[c-BASE+19]
if t>3 or rl==0 or rs>0x10FFFF: good=False;break
total+=rl
if not good: continue
out.append((a,bm,gd,cm,kd,n,total))
return out
for path in sys.argv[1:]:
print("==",path); img=Img(mainapp(path))
for a,bm,gd,cm,kd,n,total in find_dscs(img):
print(f"dsc 0x{a:08x} bitmap 0x{bm:08x} glyphs 0x{gd:08x} cmaps 0x{cm:08x} n={n} codepoints={total}")
+9
View File
@@ -20,4 +20,13 @@ if command -v ruby >/dev/null 2>&1; then
fi
node scripts/install-hooks.cjs
# NativeScript otherwise guesses the signing team from installed provisioning
# profiles; once a free team's profile expires and Xcode deletes it, the guess
# is null and the generated project gets an unloadable DEVELOPMENT_TEAM.
if [[ -n "${IOS_TEAM_ID:-}" && " $* " != *" --teamId"* ]]; then
case "${1:-}" in
build|run|debug|deploy) set -- "$@" --teamId "$IOS_TEAM_ID" ;;
esac
fi
exec ns "$@"
+2 -1
View File
@@ -4,7 +4,8 @@
# pre-onboarding state, for testing the onboarding flow repeatedly.
#
# By default this only clears the onboarding-related preference keys
# (onboarding.complete, onboarding.previewOnly, ...) and leaves everything
# (onboarding.complete, onboarding.previewOnly, the on-glasses onboarding's
# onboarding.glassesFinishedVersion, ...) and leaves everything
# else — notably the saved glasses/ring MAC addresses — intact, so you don't
# have to re-scan devices on every test pass. Pass --all to wipe ALL app data
# (a true fresh-install state, addresses included).
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""Annotate a pulled faceclaw_settings.xml with placeholders for unset settings.
Settings that have never been configured are absent from the SharedPreferences
file, which makes it unclear what keys exist or where to add them. This script
scans the app's TypeScript source for ConfigSetting declarations (the settings
catalog) and appends a commented-out XML node for every setting not already
present in the file, so pull_config.sh -> edit -> push_config.sh is a
convenient way to configure things like API keys.
Usage: annotate_config.py [settings-xml] [app-src-dir]
Defaults: faceclaw_settings.xml, <repo>/app (relative to this script).
"""
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
def find_setting_blocks(source: str):
"""Yield (kind, block_text) for each `new ConfigSetting*({...})` in source."""
for match in re.finditer(
r"new\s+ConfigSetting(Boolean|Enum|String)(?:<[^>(]*>)?\s*\(\s*\{", source
):
kind = match.group(1)
# Walk to the matching close brace of the options object literal.
depth = 1
pos = match.end()
while pos < len(source) and depth > 0:
ch = source[pos]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
pos += 1
yield kind, source[match.end() : pos - 1]
STRING_LITERAL = r'"((?:[^"\\]|\\.)*)"'
def unescape(literal: str) -> str:
return re.sub(r"\\(.)", r"\1", literal)
def field_string(block: str, name: str):
m = re.search(rf"{name}:\s*{STRING_LITERAL}", block)
return unescape(m.group(1)) if m else None
def field_string_or_ident(block: str, name: str):
"""Return ('literal', value) or ('ident', name) or None."""
m = re.search(rf"{name}:\s*(?:{STRING_LITERAL}|([A-Za-z_][A-Za-z0-9_]*))", block)
if not m:
return None
if m.group(1) is not None:
return ("literal", unescape(m.group(1)))
return ("ident", m.group(2))
def parse_string_array(text: str):
return [unescape(m.group(1)) for m in re.finditer(STRING_LITERAL, text)]
def build_constant_tables(sources):
"""Map identifier -> string value, and identifier -> list of strings."""
string_consts = {}
array_consts = {}
for source in sources:
for m in re.finditer(
rf"const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*{STRING_LITERAL}", source
):
string_consts[m.group(1)] = unescape(m.group(2))
for m in re.finditer(
r"const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\[([^\]]*)\]", source, re.S
):
values = parse_string_array(m.group(2))
if values:
array_consts[m.group(1)] = values
return string_consts, array_consts
def collect_settings(app_dir: Path):
sources = [p.read_text(encoding="utf-8") for p in sorted(app_dir.rglob("*.ts"))]
string_consts, array_consts = build_constant_tables(sources)
settings = []
for source in sources:
for kind, block in find_setting_blocks(source):
key_ref = field_string_or_ident(block, "storageKey")
if key_ref is None:
continue
key = key_ref[1] if key_ref[0] == "literal" else string_consts.get(key_ref[1])
if key is None:
print(
f"warning: could not resolve storageKey {key_ref[1]}",
file=sys.stderr,
)
continue
if kind == "Boolean":
m = re.search(r"defaultValue:\s*(true|false)", block)
default = m.group(1) if m else "false"
else:
default = field_string(block, "defaultValue") or ""
values = None
if kind == "Enum":
m = re.search(r"values:\s*(?:\[([^\]]*)\]|([A-Za-z_][A-Za-z0-9_]*))", block, re.S)
if m and m.group(1) is not None:
values = parse_string_array(m.group(1))
elif m:
values = array_consts.get(m.group(2))
settings.append(
{
"key": key,
"kind": kind,
"default": default,
"label": field_string(block, "label"),
"description": field_string(block, "description"),
"values": values,
}
)
return settings
def xml_escape(text: str) -> str:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def comment_safe(text: str) -> str:
# "--" is illegal inside an XML comment.
return re.sub(r"-{2,}", "-", text)
def placeholder_comment(setting) -> str:
lines = []
title = setting["label"] or setting["key"]
desc = f": {setting['description']}" if setting["description"] else ""
lines.append(f"{title}{desc}")
if setting["values"]:
lines.append(f"Allowed values: {', '.join(setting['values'])}")
if setting["kind"] == "Boolean":
node = f'<boolean name="{setting["key"]}" value="{setting["default"]}" />'
else:
node = f'<string name="{setting["key"]}">{xml_escape(setting["default"])}</string>'
lines.append(node)
body = "\n ".join(comment_safe(line) for line in lines)
return f" <!-- {body} -->"
def main() -> int:
xml_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("faceclaw_settings.xml")
app_dir = (
Path(sys.argv[2]) if len(sys.argv) > 2 else Path(__file__).resolve().parent.parent / "app"
)
content = xml_path.read_text(encoding="utf-8")
present = {
child.get("name")
for child in ET.fromstring(content)
if child.get("name") is not None
}
missing = [s for s in collect_settings(app_dir) if s["key"] not in present]
if not missing:
return 0
missing.sort(key=lambda s: s["key"])
close_tag = content.rfind("</map>")
if close_tag < 0:
print(f"error: no </map> in {xml_path}", file=sys.stderr)
return 1
header = (
" <!-- Settings below have never been set on the device and show their\n"
" default values. To configure one, uncomment its node (keep it\n"
" inside <map>), fill in the value, and run scripts/push_config.sh. -->\n"
)
block = header + "\n".join(placeholder_comment(s) for s in missing) + "\n"
xml_path.write_text(content[:close_tag] + block + content[close_tag:], encoding="utf-8")
print(f"Added placeholders for {len(missing)} unset setting(s) to {xml_path}")
return 0
if __name__ == "__main__":
sys.exit(main())
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env node
/**
* Preprocess Even's extracted 20px firmware fonts into a single asset Faceclaw
* bundles and renders (app/fonts/evenhub/evenhub-20.json).
*
* Source: reverse-engineered LVGL lv_font_fmt_txt glyph data under
* g2/downloads/s200_embedded_fonts/{background_latin_20, background_greek_
* cyrillic_20, shared_emoji_20}. The Chinese font is intentionally excluded
* (we will substitute an OFL font for CJK later).
*
* Only glyph BITMAPS + boxes are taken from here; text SIZING/KERNING at
* runtime comes from @evenrealities/pretext, whose advance tables these
* bitmaps were cross-validated against. The three fonts are merged with the
* EvenHub fallback priority (latin > greek/cyrillic > emoji); the first font
* that owns a codepoint wins, matching pretext's chain.
*
* Bitmaps are 4bpp, high-nibble-first, row stride = floor(box_w/2)+1 (Even's
* pipeline pads every row by a nibble). The UI fonts are effectively 1-bit
* (nibbles are 0 or 0xF) but we keep 4bpp verbatim so any anti-aliasing
* survives.
*
* Output JSON:
* { lineHeight, baseline, glyphs: { "<cp>": [boxW, boxH, ofsX, ofsY, off, len] },
* bitmapBase64 }
* where off/len index the decoded bitmap blob. lineHeight/baseline come from
* the latin font (the layout reference; pretext uses the same 27px height).
*/
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const FONT_SRC = join(here, "../../downloads/s200_embedded_fonts");
const OUT = join(here, "../app/fonts/evenhub/evenhub-20.json");
// Priority order = EvenHub fallback chain (minus cn).
const FONTS = ["background_latin_20", "background_greek_cyrillic_20", "shared_emoji_20"];
function rowStride(boxW) {
return Math.floor(boxW / 2) + 1;
}
const merged = new Map(); // codepoint -> {boxW,boxH,ofsX,ofsY,bytes:Uint8Array}
for (const font of FONTS) {
const dir = join(FONT_SRC, font);
const glyphs = JSON.parse(readFileSync(join(dir, "glyphs.json"), "utf8"));
const bitmap = readFileSync(join(dir, "glyph_bitmap.bin"));
for (const g of glyphs) {
if (g.codepoint === undefined) continue; // reserved / unmapped glyph slots
if (merged.has(g.codepoint)) continue; // earlier font in the chain wins
const len = g.box_height > 0 && g.box_width > 0 ? rowStride(g.box_width) * g.box_height : 0;
// Guard against the known slightly-truncated bitmap tails: pad short reads.
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = bitmap[g.bitmap_index + i] ?? 0;
merged.set(g.codepoint, {
boxW: g.box_width,
boxH: g.box_height,
ofsX: g.offset_x,
ofsY: g.offset_y,
bytes,
});
}
}
// Layout metrics from the latin font (also what pretext uses: 27px line).
const latinFont = JSON.parse(readFileSync(join(FONT_SRC, "background_latin_20", "manifest.json"), "utf8"));
const lineHeight = latinFont.line_height; // 27
const baseline = lineHeight - latinFont.base_line; // 27 - 5 = 22 (px below line top)
// ---------------------------------------------------------------------------
// Symbol / fullwidth glyphs from the CJK flash font (s200_font.bin).
//
// The three embedded UI fonts above cover latin/greek/emoji only, so grid-
// graphics apps come out blank: snake draws its board from U+3000 (ideographic
// space), U+25A6/U+25C6 (pieces) and fullwidth forms; block/box-drawing bars
// use U+2500-259F. Those glyphs live only in the SourceHanSans CJK font on the
// separate flash partition. We pull just the non-Han SYMBOL ranges from it
// (not the 21k ideographs — those wait for the OFL substitute) so grid UIs
// render. pretext already returns 20px advances for these, so only the bitmaps
// were missing. Format per notes/font-formats.txt (LVGL lv_font_fmt_txt in the
// "ZZZZ" flash wrapper, memory-mapped at 0x80100000).
const CJK_FONT = join(here, "../../downloads/s200_font.bin");
const CJK_MMAP_BASE = 0x80100000;
// Non-Han symbol ranges grid/graphics apps rely on (inclusive).
const SYMBOL_RANGES = [
[0x2000, 0x206f], // general punctuation (incl. various spaces/dashes)
[0x2100, 0x214f], // letterlike symbols (℃ ℉ №, etc.)
[0x2190, 0x21ff], // arrows
[0x2200, 0x22ff], // mathematical operators
[0x2500, 0x257f], // box drawing
[0x2580, 0x259f], // block elements
[0x25a0, 0x25ff], // geometric shapes (snake pieces)
[0x2600, 0x26ff], // miscellaneous symbols
[0x2700, 0x27bf], // dingbats
[0x3000, 0x303f], // CJK symbols & punctuation (ideographic space)
[0xff00, 0xffef], // halfwidth & fullwidth forms
];
function loadCjkSymbols(existing) {
let added = 0;
const cjk = readFileSync(CJK_FONT);
const off = (ptr) => ptr - CJK_MMAP_BASE;
const descPtr = cjk.readUInt32LE(0x34);
const cjkLineHeight = cjk.readUInt16LE(0x38);
const cjkBaseLine = cjk.readUInt16LE(0x3a);
const cjkBaseline = cjkLineHeight - cjkBaseLine; // 25 - 6 = 19
// Our single composite baseline differs, so shift ofsY to keep the glyph's
// designed vertical placement when drawn against our baseline.
const baselineShift = baseline - cjkBaseline;
let d = off(descPtr);
const glyphBitmapOff = off(cjk.readUInt32LE(d));
const glyphDscOff = off(cjk.readUInt32LE(d + 4));
const cmapOff = off(cjk.readUInt32LE(d + 8));
// kerning ptr (d+12) is null; packed field after gives cmap_num.
const packed = cjk.readUInt16LE(d + 18);
const cmapNum = packed & 0x1ff;
// Parse the cmap table into lookup records.
const cmaps = [];
for (let i = 0; i < cmapNum; i++) {
const base = cmapOff + i * 20;
cmaps.push({
rangeStart: cjk.readUInt32LE(base),
rangeLength: cjk.readUInt16LE(base + 4),
glyphIdStart: cjk.readUInt16LE(base + 6),
unicodeListPtr: cjk.readUInt32LE(base + 8),
glyphIdOfsListPtr: cjk.readUInt32LE(base + 12),
listLength: cjk.readUInt16LE(base + 16),
type: cjk.readUInt8(base + 18),
});
}
const glyphIdFor = (cp) => {
for (const c of cmaps) {
if (cp < c.rangeStart || cp >= c.rangeStart + c.rangeLength) continue;
const rel = cp - c.rangeStart;
if (c.type === 2) return c.glyphIdStart + rel; // contiguous
if (c.type === 0) {
// u8 glyph-id-offset array
return c.glyphIdStart + cjk.readUInt8(off(c.glyphIdOfsListPtr) + rel);
}
if (c.type === 3) {
// sparse: u16 unicode-delta list; index in the list is the glyph offset
const listOff = off(c.unicodeListPtr);
for (let k = 0; k < c.listLength; k++) {
if (cjk.readUInt16LE(listOff + k * 2) === rel) {
const gid = c.glyphIdOfsListPtr
? cjk.readUInt8(off(c.glyphIdOfsListPtr) + k)
: k;
return c.glyphIdStart + gid;
}
}
return 0;
}
}
return 0;
};
for (const [start, end] of SYMBOL_RANGES) {
for (let cp = start; cp <= end; cp++) {
if (existing.has(cp)) continue; // don't override latin/greek/emoji
const gid = glyphIdFor(cp);
if (!gid) continue;
const dsc = glyphDscOff + gid * 16;
const bitmapIndex = cjk.readUInt32LE(dsc);
const boxW = cjk.readUInt16LE(dsc + 8);
const boxH = cjk.readUInt16LE(dsc + 10);
const ofsX = cjk.readInt16LE(dsc + 12);
const ofsY = cjk.readInt16LE(dsc + 14);
const len = boxW > 0 && boxH > 0 ? rowStride(boxW) * boxH : 0;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = cjk[glyphBitmapOff + bitmapIndex + i] ?? 0;
existing.set(cp, { boxW, boxH, ofsX, ofsY: ofsY + baselineShift, bytes });
added++;
}
}
return added;
}
const cjkAdded = loadCjkSymbols(merged);
// Concatenate bitmaps and record offsets.
const chunks = [];
let offset = 0;
const glyphRecords = {};
for (const [cp, g] of [...merged].sort((a, b) => a[0] - b[0])) {
chunks.push(g.bytes);
glyphRecords[cp] = [g.boxW, g.boxH, g.ofsX, g.ofsY, offset, g.bytes.length];
offset += g.bytes.length;
}
const blob = Buffer.concat(chunks.map((c) => Buffer.from(c)));
const asset = {
lineHeight,
baseline,
glyphs: glyphRecords,
bitmapBase64: blob.toString("base64"),
};
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, JSON.stringify(asset));
console.log(
`wrote ${OUT}: ${merged.size} glyphs (${cjkAdded} from CJK symbols), ` +
`${blob.length} bitmap bytes, ${(JSON.stringify(asset).length / 1024).toFixed(1)} KiB json`,
);
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env node
/**
* Pack a web-app directory into an EvenHub .ehpk, dependency-free (Node >= 22.15
* for node:zlib zstd). Format reverse-engineered in
* ../../ehpk-unpacker/ehpk_unpack.py and consumed by app/apps/evenhub/ehpk.ts:
*
* header "EHPK" | u16 major=1 | u16 minor=1 | u32 firstRecord=20
* | u32 recordCount | u32 reserved=0
* FILE E4 BA A9 BA | u32 compLen | u32 uncompLen | u16 tag=0xB701
* | u16 nameLen | xor(path) | xor(zstd(content))
* DIR E5 BA A9 BA | u16 tag=0xAABD | u16 nameLen | xor(path)
* FOOTER E3 BA A9 BA | sha512 of every byte before this record
*
* Paths and content are XORed with the repeating key "EVEN REALITIES".
* The manifest is stored as "app.json", project files under "dist/".
*
* Usage: node scripts/pack-ehpk.mjs <app.json> <projectDir> [-o out.ehpk]
*/
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { zstdCompressSync } from "node:zlib";
const KEY = Buffer.from("EVEN REALITIES", "ascii");
function xor(buf) {
const out = Buffer.from(buf);
for (let i = 0; i < out.length; i++) out[i] ^= KEY[i % KEY.length];
return out;
}
function fileRecord(path, content) {
const comp = xor(zstdCompressSync(content));
const name = xor(Buffer.from(path, "utf8"));
const head = Buffer.alloc(16);
head.writeUInt32LE(0xbaa9bae4, 0);
head.writeUInt32LE(comp.length, 4);
head.writeUInt32LE(content.length, 8);
head.writeUInt16LE(0xb701, 12);
head.writeUInt16LE(name.length, 14);
return Buffer.concat([head, name, comp]);
}
function dirRecord(path) {
const name = xor(Buffer.from(path, "utf8"));
const head = Buffer.alloc(8);
head.writeUInt32LE(0xbaa9bae5, 0);
head.writeUInt16LE(0xaabd, 4);
head.writeUInt16LE(name.length, 6);
return Buffer.concat([head, name]);
}
function walk(dir, archivePrefix, records) {
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.name.startsWith(".") || entry.name.endsWith(".ehpk")) continue;
const archivePath = `${archivePrefix}/${entry.name}`;
if (entry.isDirectory()) {
records.push(dirRecord(archivePath));
walk(join(dir, entry.name), archivePath, records);
} else if (entry.isFile()) {
records.push(fileRecord(archivePath, readFileSync(join(dir, entry.name))));
}
}
}
const args = process.argv.slice(2);
const outIndex = args.indexOf("-o");
const output = outIndex >= 0 ? args.splice(outIndex, 2)[1] : "out.ehpk";
const [manifestPath, projectDir] = args;
if (!manifestPath || !projectDir) {
console.error("usage: pack-ehpk.mjs <app.json> <projectDir> [-o out.ehpk]");
process.exit(1);
}
const records = [fileRecord("app.json", readFileSync(manifestPath)), dirRecord("dist")];
walk(projectDir, "dist", records);
const header = Buffer.alloc(20);
header.write("EHPK", 0, "ascii");
header.writeUInt16LE(1, 4);
header.writeUInt16LE(1, 6);
header.writeUInt32LE(20, 8);
header.writeUInt32LE(records.length + 1, 12); // + footer
header.writeUInt32LE(0, 16);
const body = Buffer.concat([header, ...records]);
const footerHead = Buffer.alloc(4);
footerHead.writeUInt32LE(0xbaa9bae3, 0);
const footer = Buffer.concat([footerHead, createHash("sha512").update(body).digest()]);
writeFileSync(output, Buffer.concat([body, footer]));
console.log(`${output}: ${records.length + 1} records, ${body.length + footer.length} bytes`);
+302
View File
@@ -0,0 +1,302 @@
// Headless verification harness for the pinball worker's table geometry and
// physics. Ported 1:1 from app/workers/pinball-app.worker.ts (keep in sync by
// hand if the worker changes). Renders the table plus simulated trajectories
// to grayscale PGM files and logs events/anomalies.
const fs = require("fs");
// --- geometry (must match worker) ---
const LEFT = 10, RIGHT = 260, TOP = 4, BOTTOM = 256, LANE_X = 232;
const BALL_R = 6;
const PLUNGER_X = (LANE_X + RIGHT) / 2, PLUNGER_Y = 240;
const GRAVITY = 240, DRAG_PER_S = 0.12, MAX_SPEED = 600, PHYSICS_DT = 1 / 120;
const LAUNCH_SPEEDS = [320, 380, 440, 500, 560];
const BUMPER_KICK = 340, SLING_KICK = 300;
const FLIPPER_LEN = 37, FLIPPER_R = 5;
const FLIPPER_REST_DEG = 32, FLIPPER_UP_DEG = -34;
const FLIPPER_RISE_DEG_PER_S = 950, FLIPPER_FALL_DEG_PER_S = 480;
const FLIPPER_HOLD_MS = 140, FLIPPER_E = 0.4;
function seg(x0, y0, x1, y1, e, shade = 150, kind = "wall") {
return { x0, y0, x1, y1, e, kind, shade };
}
function chain(points, e, shade = 150) {
const out = [];
for (let i = 1; i < points.length; i++)
out.push(seg(points[i - 1][0], points[i - 1][1], points[i][0], points[i][1], e, shade));
return out;
}
const SEGMENTS = [
...chain([[LEFT, BOTTOM], [LEFT, 54], [16, 24], [34, 8], [58, TOP]], 0.45, 160),
seg(58, TOP, 210, TOP, 0.45, 160),
...chain([[210, TOP], [236, 10], [254, 26], [RIGHT, 56]], 0.35, 160),
seg(RIGHT, 56, RIGHT, BOTTOM, 0.3, 160),
seg(LANE_X, BOTTOM, RIGHT, BOTTOM, 0.3, 160),
seg(LANE_X, 66, LANE_X, BOTTOM, 0.3, 140),
seg(RIGHT, 56, 226, 68, 0.2, 90, "gate"),
seg(103, 20, 103, 46, 0.35, 130),
seg(139, 20, 139, 46, 0.35, 130),
seg(LEFT, 184, 83, 230.5, 0.35, 150),
seg(LANE_X, 184, 159, 230.5, 0.35, 150),
seg(58, 166, 84, 204, 0.4, 170, "sling"),
seg(58, 166, 58, 196, 0.4, 130),
seg(58, 196, 84, 204, 0.4, 130),
seg(184, 166, 158, 204, 0.4, 170, "sling"),
seg(184, 166, 184, 196, 0.4, 130),
seg(158, 204, 184, 196, 0.4, 130),
];
const BUMPERS = [
{ x: 75, y: 78, r: 13 },
{ x: 167, y: 78, r: 13 },
{ x: 121, y: 128, r: 13 },
];
const ROLLOVERS = [{ x: 85, y: 34 }, { x: 121, y: 34 }, { x: 157, y: 34 }];
const FLIPPER_PIVOTS = [
{ x: 76, y: 232, mirror: 1 },
{ x: 166, y: 232, mirror: -1 },
];
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
function makeState() {
return {
ballX: PLUNGER_X, ballY: PLUNGER_Y, ballVx: 0, ballVy: 0,
flippers: FLIPPER_PIVOTS.map((p) => ({
pivotX: p.x, pivotY: p.y, mirror: p.mirror,
angleDeg: FLIPPER_REST_DEG, state: "rest", holdUntilMs: 0,
})),
nowMs: 0, events: [], drained: false,
};
}
function flipperOmega(f) {
if (f.state === "rising") return (-FLIPPER_RISE_DEG_PER_S * Math.PI) / 180;
if (f.state === "falling") return (FLIPPER_FALL_DEG_PER_S * Math.PI) / 180;
return 0;
}
function stepFlippers(s, dt) {
for (const f of s.flippers) {
switch (f.state) {
case "rising":
f.angleDeg -= FLIPPER_RISE_DEG_PER_S * dt;
if (f.angleDeg <= FLIPPER_UP_DEG) {
f.angleDeg = FLIPPER_UP_DEG; f.state = "hold"; f.holdUntilMs = s.nowMs + FLIPPER_HOLD_MS;
}
break;
case "hold":
if (s.nowMs >= f.holdUntilMs) f.state = "falling";
break;
case "falling":
f.angleDeg += FLIPPER_FALL_DEG_PER_S * dt;
if (f.angleDeg >= FLIPPER_REST_DEG) { f.angleDeg = FLIPPER_REST_DEG; f.state = "rest"; }
break;
}
}
}
function collideSegment(s, segment) {
const dx = segment.x1 - segment.x0, dy = segment.y1 - segment.y0;
const lengthSq = dx * dx + dy * dy;
const t = clamp(((s.ballX - segment.x0) * dx + (s.ballY - segment.y0) * dy) / lengthSq, 0, 1);
const cx = segment.x0 + t * dx, cy = segment.y0 + t * dy;
const offX = s.ballX - cx, offY = s.ballY - cy;
const dist = Math.hypot(offX, offY);
if (dist >= BALL_R || dist === 0) return;
const nx = offX / dist, ny = offY / dist;
if (segment.kind === "gate" && ny > -0.3) return;
s.ballX += nx * (BALL_R - dist);
s.ballY += ny * (BALL_R - dist);
const vn = s.ballVx * nx + s.ballVy * ny;
if (vn >= 0) return;
if (segment.kind === "sling") {
s.ballVx = s.ballVx - vn * nx + nx * SLING_KICK;
s.ballVy = s.ballVy - vn * ny + ny * SLING_KICK;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s sling`);
return;
}
s.ballVx -= (1 + segment.e) * vn * nx;
s.ballVy -= (1 + segment.e) * vn * ny;
}
function collideFlipper(s, f) {
const angle = (f.angleDeg * Math.PI) / 180;
const dirX = f.mirror * Math.cos(angle), dirY = Math.sin(angle);
const relX = s.ballX - f.pivotX, relY = s.ballY - f.pivotY;
const t = clamp(relX * dirX + relY * dirY, 0, FLIPPER_LEN);
const cx = f.pivotX + t * dirX, cy = f.pivotY + t * dirY;
const offX = s.ballX - cx, offY = s.ballY - cy;
const dist = Math.hypot(offX, offY);
const reach = BALL_R + FLIPPER_R;
if (dist >= reach || dist === 0) return;
const nx = offX / dist, ny = offY / dist;
s.ballX += nx * (reach - dist);
s.ballY += ny * (reach - dist);
const omega = flipperOmega(f);
const surfaceVx = -t * omega * f.mirror * dirY;
const surfaceVy = t * omega * f.mirror * dirX;
const relVn = (s.ballVx - surfaceVx) * nx + (s.ballVy - surfaceVy) * ny;
if (relVn >= 0) return;
s.ballVx -= (1 + FLIPPER_E) * relVn * nx;
s.ballVy -= (1 + FLIPPER_E) * relVn * ny;
}
function collideBumpers(s) {
for (const b of BUMPERS) {
const offX = s.ballX - b.x, offY = s.ballY - b.y;
const dist = Math.hypot(offX, offY);
const reach = BALL_R + b.r;
if (dist >= reach || dist === 0) continue;
const nx = offX / dist, ny = offY / dist;
s.ballX += nx * (reach - dist);
s.ballY += ny * (reach - dist);
const tangential = s.ballVx * -ny + s.ballVy * nx;
s.ballVx = nx * BUMPER_KICK + -ny * tangential * 0.3;
s.ballVy = ny * BUMPER_KICK + nx * tangential * 0.3;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s bumper`);
}
}
function stepPhysics(s) {
const dt = PHYSICS_DT;
s.nowMs += dt * 1000;
stepFlippers(s, dt);
if (s.drained) return;
s.ballVy += GRAVITY * dt;
const drag = Math.max(0, 1 - DRAG_PER_S * dt);
s.ballVx *= drag; s.ballVy *= drag;
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed > MAX_SPEED) { s.ballVx *= MAX_SPEED / speed; s.ballVy *= MAX_SPEED / speed; }
s.ballX += s.ballVx * dt;
s.ballY += s.ballVy * dt;
for (let pass = 0; pass < 2; pass++) {
for (const segment of SEGMENTS) collideSegment(s, segment);
for (const f of s.flippers) collideFlipper(s, f);
collideBumpers(s);
}
if (s.ballY > BOTTOM + 2 * BALL_R || s.ballY < TOP - 40 || s.ballX < LEFT - 40 || s.ballX > RIGHT + 40) {
s.drained = true;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s DRAIN at x=${s.ballX.toFixed(0)}`);
}
}
// --- rendering ---
const W = 276, H = 276;
function render(trailPoints, label) {
const px = new Uint8Array(W * H);
const line = (x0, y0, x1, y1, v) => {
const steps = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 2 + 1;
for (let i = 0; i <= steps; i++) {
const x = Math.round(x0 + ((x1 - x0) * i) / steps);
const y = Math.round(y0 + ((y1 - y0) * i) / steps);
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = v;
}
};
for (const s of SEGMENTS) line(s.x0, s.y0, s.x1, s.y1, s.shade);
for (const b of BUMPERS)
for (let a = 0; a < 120; a++) {
const x = Math.round(b.x + b.r * Math.cos((a / 120) * 2 * Math.PI));
const y = Math.round(b.y + b.r * Math.sin((a / 120) * 2 * Math.PI));
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = 130;
}
for (const r of ROLLOVERS)
for (let a = 0; a < 40; a++) {
const x = Math.round(r.x + 5 * Math.cos((a / 40) * 2 * Math.PI));
const y = Math.round(r.y + 5 * Math.sin((a / 40) * 2 * Math.PI));
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = 110;
}
for (const f of FLIPPER_PIVOTS) {
const a = (FLIPPER_REST_DEG * Math.PI) / 180;
line(f.x, f.y, f.x + f.mirror * FLIPPER_LEN * Math.cos(a), f.y + FLIPPER_LEN * Math.sin(a), 255);
}
for (const [x, y] of trailPoints) {
const xi = Math.round(x), yi = Math.round(y);
if (xi >= 0 && yi >= 0 && xi < W && yi < H) px[yi * W + xi] = Math.max(px[yi * W + xi], 220);
}
const header = Buffer.from(`P5\n${W} ${H}\n255\n`);
fs.writeFileSync(`${__dirname}/pinball-${label}.pgm`, Buffer.concat([header, Buffer.from(px)]));
}
// --- scenarios ---
function runScenario(label, power, flipPolicy, maxSeconds = 40) {
const s = makeState();
s.ballY = PLUNGER_Y - 2;
s.ballVy = -LAUNCH_SPEEDS[power - 1];
const trail = [];
let stuckMs = 0, stuckReported = null, minY = 999;
const steps = Math.round(maxSeconds / PHYSICS_DT);
for (let i = 0; i < steps && !s.drained; i++) {
stepPhysics(s);
minY = Math.min(minY, s.ballY);
if (!Number.isFinite(s.ballX) || !Number.isFinite(s.ballY)) {
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s NON-FINITE POSITION`);
break;
}
if (i % 4 === 0) trail.push([s.ballX, s.ballY]);
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed < 6) stuckMs += PHYSICS_DT * 1000; else stuckMs = 0;
// A slow ball near the flippers may just be trapped on one (legitimate);
// fire the flippers and only call it stuck if that fails to eject it.
if (stuckMs > 1200 && Math.round(stuckMs) % 600 < PHYSICS_DT * 1000) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
if (stuckMs > 2500 && !stuckReported) {
stuckReported = `STUCK ~2.5s at (${s.ballX.toFixed(0)},${s.ballY.toFixed(0)})`;
s.events.push(stuckReported);
}
flipPolicy(s);
}
render(trail, label);
const outcome = s.drained ? "drained" : stuckReported ? "stuck" : "still live at timeout";
console.log(`\n=== ${label} (power ${power}): ${outcome}, minY=${minY.toFixed(0)}, ${(s.nowMs / 1000).toFixed(1)}s sim ===`);
const counts = {};
for (const e of s.events) {
const kind = e.split(" ")[1] || e;
counts[kind] = (counts[kind] || 0) + 1;
}
console.log("events:", JSON.stringify(counts));
console.log("last events:", s.events.slice(-6).join(" | "));
}
const noFlips = () => {};
// Flip both flippers whenever the ball descends into the flipper zone.
function reactiveFlips(s) {
if (s.ballVy > 0 && s.ballY > 195 && s.ballY < 235 && s.ballX > 55 && s.ballX < 190) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
}
runScenario("p1-noflip", 1, noFlips);
runScenario("p3-noflip", 3, noFlips);
runScenario("p5-noflip", 5, noFlips);
runScenario("p4-flips", 4, reactiveFlips, 90);
runScenario("p2-flips", 2, reactiveFlips, 90);
// Randomized robustness sweep: random power, jittery/erratic flipping.
let bad = 0;
for (let run = 0; run < 30; run++) {
const power = 1 + Math.floor(Math.random() * 5);
const policy = (s) => {
if (Math.random() < 0.004) {
const f = s.flippers[Math.floor(Math.random() * 2)];
if (f.state === "rest") f.state = "rising";
}
reactiveFlips(s);
};
const s = makeState();
s.ballY = PLUNGER_Y - 2;
s.ballVy = -LAUNCH_SPEEDS[power - 1];
let stuckMs = 0, failed = null;
for (let i = 0; i < Math.round(120 / PHYSICS_DT) && !s.drained; i++) {
stepPhysics(s);
if (!Number.isFinite(s.ballX) || !Number.isFinite(s.ballY)) { failed = "non-finite"; break; }
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed < 6) stuckMs += PHYSICS_DT * 1000; else stuckMs = 0;
if (stuckMs > 1200 && Math.round(stuckMs) % 600 < PHYSICS_DT * 1000) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
if (stuckMs > 2500) { failed = `stuck at (${s.ballX.toFixed(0)},${s.ballY.toFixed(0)})`; break; }
policy(s);
}
if (failed) { bad++; console.log(`run ${run} power ${power}: ${failed}`); }
}
console.log(`\nrandom sweep: ${bad}/30 runs failed`);
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
#
# resetAndRun.sh — rebuild Faceclaw and put a phone into an approximately
# never-had-faceclaw state for onboarding-flow testing, then install and
# launch the fresh build. Unlike resetOnboarding.sh this also forgets the
# glasses/ring Bluetooth pairings, and takes the target device explicitly
# (we test on several phones now, so no hardcoded default).
#
# Steps: build → uninstall → install → unpair "EVEN R1*" / "Even G2*" bonds
# → wipe app data + reset BLUETOOTH_CONNECT to undecided → launch.
#
# Usage:
# scripts/resetAndRun.sh <adb-device-id> # serial or host:port
#
# Android has no adb command to remove a Bluetooth bond, so the unpair step
# works through FaceclawDebugUnpairReceiver inside the app: we install the
# fresh build first, temporarily `pm grant` BLUETOOTH_CONNECT, broadcast the
# unpair request, then `pm clear` + revoke so the app still looks
# freshly-installed when it launches.
set -euo pipefail
PACKAGE="com.faceclaw.app"
UNPAIR_PREFIXES="EVEN R1,Even G2"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
APK="$ROOT/platforms/android/app/build/outputs/apk/debug/app-debug.apk"
if [ $# -ne 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
exit 2
fi
DEVICE_ID="$1"
# Match build.sh's tool locations so adb is on PATH even from a bare shell.
export ANDROID_HOME="${ANDROID_HOME:-/Users/jbabcock/Library/Android/sdk}"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
ADB="adb -s $DEVICE_ID"
# Network devices (host:port) need an explicit connect first.
case "$DEVICE_ID" in
*:*) adb connect "$DEVICE_ID" >/dev/null ;;
esac
if ! $ADB get-state >/dev/null 2>&1; then
echo "error: adb device '$DEVICE_ID' not connected." >&2
echo " Connected devices:" >&2
adb devices -l | sed '1d' >&2
exit 1
fi
echo "==> Building..."
"$ROOT/build.sh"
[ -f "$APK" ] || { echo "error: build produced no APK at $APK" >&2; exit 1; }
echo "==> Uninstalling $PACKAGE..."
$ADB uninstall "$PACKAGE" >/dev/null 2>&1 || echo " (was not installed)"
echo "==> Installing $(basename "$APK")..."
$ADB install "$APK"
echo "==> Unpairing Bluetooth devices matching: $UNPAIR_PREFIXES"
# The receiver needs BLUETOOTH_CONNECT; grant it just for this step. The
# whole remote command must be ONE quoted string — adb flattens multi-arg
# commands, which would lose the quoting around the space-containing extras.
$ADB shell pm grant "$PACKAGE" android.permission.BLUETOOTH_CONNECT
UNPAIR_OUT="$($ADB shell "am broadcast -n $PACKAGE/.FaceclawDebugUnpairReceiver \
-a com.faceclaw.app.action.DEBUG_UNPAIR --es prefixes '$UNPAIR_PREFIXES'")"
UNPAIR_RESULT="$(printf '%s\n' "$UNPAIR_OUT" | sed -n 's/.*data="\(.*\)".*/\1/p')"
echo " ${UNPAIR_RESULT:-no result from unpair receiver: $UNPAIR_OUT}"
case "$UNPAIR_RESULT" in
error:*|"") echo " WARNING: unpair step did not run cleanly; pairings may remain." >&2 ;;
esac
# Return the app to fresh-install state: the broadcast booted the app process
# (which may have written data), and the grant above must not leak into the
# onboarding permissions test. clear-permission-flags removes the user-set
# mark pm revoke leaves, so the permission dialog is still allowed to appear.
echo "==> Resetting app data and permissions to fresh-install state..."
$ADB shell am force-stop "$PACKAGE"
$ADB shell pm clear "$PACKAGE" >/dev/null
$ADB shell pm revoke "$PACKAGE" android.permission.BLUETOOTH_CONNECT
$ADB shell pm clear-permission-flags "$PACKAGE" \
android.permission.BLUETOOTH_CONNECT user-set user-fixed
echo "==> Launching..."
$ADB shell am start -n "$PACKAGE/com.tns.NativeScriptActivity" >/dev/null
echo "Done. Faceclaw should be starting its first-run onboarding."
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
adb shell settings put secure show_ime_with_hard_keyboard 1