tft: script tokens, global variables, timers, control flow

build-tft now reproduces 35 Editor-made samples byte for byte: assignments,
arithmetic, 27 commands, system variables and colours, attribute references,
Program.s globals, all page/hotspot/timer events, if/else/while/for.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Fable 5.2 committed 2026-11-16 18:23:14 +01:00
1 parent f66c902443
commit 99a5240af0
7 files changed
+511 -50

No files matched your search

+85 -25
View File
@@ -14,6 +14,7 @@ import struct
from . import tft, tft_code
from .container import HMIFile
from .page import Page
from .checksum import word_per_byte_crc
from .tft_code import Unsupported
FIRMWARE_FILES = ("input.bin", "asp0.dll", "cd0.dll", "qr0.bin", "syscom.bin", "h0-0.dll", "h1-0.dll")
@@ -22,7 +23,7 @@ SUPPORTED_MODEL = 0xB23BC018 # NX4832T035_011, the only model measured
BLOCK = 0x10000
# attribute map positions in the object record (u16 table at +0x38)
MAP = {"vscope": 1, "sta": 2, "bco": 4, "val": 20, "x": 42, "y": 43, "endx": 44, "endy": 45, "w": 46, "h": 47,
MAP = {"vscope": 1, "sta": 2, "bco": 4, "val": 20, "tim": 33, "en": 34, "x": 42, "y": 43, "endx": 44, "endy": 45, "w": 46, "h": 47,
"id": 49, "type": 62}
# attribute record templates: name -> (slot, kind, size, max, min)
_COMMON = {"type": (0, 0x01, 1, 255, 0), "id": (1, 0x01, 1, 255, 0), "vscope": (3, 0x01, 1, 1, 0)}
@@ -37,6 +38,8 @@ TYPES = {
52: dict(name="variable", slots=11, flag=0x07, group=16,
const={**_COMMON, "sta": (7, 0x01, 1, 1, 0)},
ram={"val": (8, 0x39, 4, 2147483647, -2147483648)}, owner=False),
51: dict(name="timer", slots=11, flag=0x27, group=16, const=dict(_COMMON),
ram={"tim": (7, 0x32, 2, 65534, 50), "en": (8, 0x31, 1, 1, 0)}, owner=True, action={"tim": 1, "en": 2}),
}
@@ -93,28 +96,64 @@ def resource_area(hmi: HMIFile, editor_dir: str) -> tuple[bytes, dict]:
def compile_pages(pages: list[Page], program: str):
"""-> (code blob, attribute records, page table, object records, program offset)."""
"""-> (code blob, global variable descriptors, attribute records, page table, object records,
program offset)."""
names = sorted((tft.name_hash(p.components[0].get("objname")), i) for i, p in enumerate(pages))
n = len(pages)
blob = bytearray(struct.pack("<10I", 0x24 + 6 * n, 3, 0x1C, 4, 0x20, 4, 0x24, 6 * n, 0, 0))
decl, program_lines = tft_code.declarations(tft_code.statements(program.splitlines()))
if any(v < 0 for v in decl.values()):
raise Unsupported("global variables with a negative initial value")
g = 4 * len(decl)
blob = bytearray(struct.pack("<8I", 0x24 + g + 6 * n, 3, 0x1C, 4, 0x20, 4 + g, 0x24 + g, 6 * n))
blob += bytes(4) + b"".join(struct.pack("<I", v) for v in decl.values()) + bytes(4)
for h, i in names:
blob += struct.pack("<IH", h, i)
program_off = len(blob)
ctx = tft_code.Context()
offsets = {name: 4 * i for i, name in enumerate(decl)}
descriptors = b"".join(struct.pack("<III", h, o, 9) for h, o in
sorted((word_per_byte_crc(name.encode("latin-1")), o) for name, o in offsets.items()))
# record numbers are needed before any script is compiled: number them first
where, base_rec = {}, 0 # (page name, component name) -> (first record, type)
for page in pages:
pname = page.components[0].get("objname")
for c in page.components:
tid = _u(c.attr("type"))
if tid not in TYPES:
raise Unsupported("component type %d (%s)" % (tid, c.get("objname")))
where[(pname, c.get("objname"))] = (base_rec, TYPES[tid])
base_rec += TYPES[tid]["slots"]
current = [None]
def attr(path):
if len(path) == 3:
key, name = (path[0], path[1]), path[2]
elif len(path) == 2:
key, name = (current[0], path[0]), path[1]
else:
return None
if key not in where:
return None
first, t = where[key]
slot = {**t["const"], **t["ram"]}.get(name)
return None if slot is None else first + slot[0]
ctx = tft_code.Context(offsets, {k[1] for k in where}, attr)
def section(lines, label=None):
if label:
blob.extend(_chunk(label))
for ln in lines:
blob.extend(_chunk(tft_code.compile_line(ln, ctx)))
for c in tft_code.compile_lines(lines, ctx):
blob.extend(_chunk(c))
blob.extend(_chunk(b""))
section(tft_code.statements(program.splitlines()) + ["page 0"])
section(program_lines + ["page 0"])
records, objects, table, rec_base = bytearray(), bytearray(), [], 0
for pi, page in enumerate(pages):
ram = bytearray(b"\xff" * 8)
prec, first_obj, comp_names, init = bytearray(), len(objects) // tft.OBJ_SIZE, [], []
page_bco = 0
pre, post = [], []
current[0] = page.components[0].get("objname")
for ci, c in enumerate(page.components):
a = {x.name: x for x in c.attrs()}
tid = _u(a["type"])
@@ -130,14 +169,16 @@ def compile_pages(pages: list[Page], program: str):
cid = _u(a["id"])
owner = struct.pack("<BB", pi, cid) if t["owner"] else b"\xff\xff"
slot0 = len(prec) // tft.REC_SIZE
group = g + 4 + (4 if tid == 121 else len(ram)) # RAM address of the component's data
recs = [bytes(tft.REC_SIZE)] * t["slots"]
amap = [0xFFFF] * 88
for name, (slot, kind, size, hi, lo) in t["const"].items():
recs[slot] = struct.pack("<Iiii2sHBBH", t["group"], _s(a[name], lo < 0), hi, lo, owner, 0, kind, size, 0)
recs[slot] = struct.pack("<Iiii2sBBBBH", group, _s(a[name], lo < 0), hi, lo, owner, 0, 0, kind, size, 0)
amap[MAP[name]] = slot0 + slot
for name, (slot, kind, size, hi, lo) in t["ram"].items():
ram += bytes(-len(ram) % min(size, 4))
recs[slot] = struct.pack("<Iiii2sHBBH", t["group"], len(ram) + 4, hi, lo, owner, 0, kind, size, 0)
recs[slot] = struct.pack("<Iiii2sBBBBH", group, g + 4 + len(ram), hi, lo, owner, 0,
t.get("action", {}).get(name, 0), kind, size, 0)
amap[MAP[name]] = slot0 + slot
if name == "bco" and tid == 121:
page_bco = rec_base + slot0 + slot
@@ -153,7 +194,7 @@ def compile_pages(pages: list[Page], program: str):
if tid == 121:
draw = len(blob)
blob += _chunk(fill)
section(ev.get("codesload", []))
section([])
section([])
else:
section([])
@@ -161,29 +202,48 @@ def compile_pages(pages: list[Page], program: str):
erase = len(blob)
blob += _chunk(fill)
section([])
if t["flag"] & 0x10:
section(ev.get("codesdown", []), b"down")
section(ev.get("codesup", []), b"up")
code_at = [0xFFFFFFFF] * 4 # down, up, timer, unload (object +0x0C..)
for i, (label, group_name, wanted) in enumerate((
(b"down", "codesdown", t["flag"] & 0x10), (b"up", "codesup", t["flag"] & 0x10),
(None, None, False), (b"unload", "codesunload", tid == 121))):
if wanted:
if ev.get(group_name):
code_at[i] = len(blob) + 4 + len(label)
section(ev.get(group_name, []), label)
if tid == 121:
section(ev.get("codesunload", []), b"unload")
init = ev.get("codesloadend", [])
pre, post = ev.get("codesload", []), ev.get("codesloadend", [])
if tid == 51:
# event: label, "S <1>", the event lines; registered by two init lines
blob += _chunk(b"timer")
code_at[2] = len(blob)
blob += _chunk(b"S \x03" + struct.pack("<I", 1))
first = rec_base + slot0
init.append(b"\x09\x22\x08\x01" + struct.pack("<I", first + 8) + (",%d," % cid).encode()
+ b"\x01" + struct.pack("<I", first + 7) + b",0")
init.append(b"L \x03" + struct.pack("<I", len(blob)))
section(ev.get("codestimer", []))
obj = bytearray(b"\xff" * tft.OBJ_SIZE)
struct.pack_into("<BBBBII", obj, 0, tid, cid, 0, t["flag"], draw, erase)
struct.pack_into("<IHBBI6HI", obj, 0x1C, t["group"], 0, 0x7F, 0, 0, *rect, start)
struct.pack_into("<4I", obj, 0x0C, *code_at)
struct.pack_into("<IHBBI6HI", obj, 0x1C, group, 0, 0x7F, 0, 0, *rect, start)
struct.pack_into("<88H", obj, 0x38, *amap)
objects += obj
comp_names.append((tft.name_hash(c.get("objname")), cid))
names_off = len(blob)
blob += _chunk(b"".join(struct.pack("<IH", h, i) for h, i in sorted(comp_names)))
blob += _chunk(bytes(ram) + bytes(8))
for raw in init:
blob += _chunk(raw)
for c in tft_code.compile_lines(pre, ctx):
blob += _chunk(c)
blob += _chunk(b"\x09\x21\x08")
section(init)
section(post)
table.append((first_obj, len(page.components), names_off, rec_base, len(ram)))
records += prec
rec_base += len(prec) // tft.REC_SIZE
code_size = len(blob)
ptable = b"".join(struct.pack("<HHIII", f, cnt, no, code_size + rb * tft.REC_SIZE, rs) for f, cnt, no, rb, rs in table)
return bytes(blob), bytes(records), ptable, bytes(objects), program_off
rec_off = len(blob) + len(descriptors)
ptable = b"".join(struct.pack("<HHIII", f, cnt, no, rec_off + rb * tft.REC_SIZE, rs) for f, cnt, no, rb, rs in table)
return bytes(blob), descriptors, bytes(records), ptable, bytes(objects), program_off
def build_tft(hmi: HMIFile, editor_dir: str = DEFAULT_EDITOR_DIR) -> bytes:
@@ -197,10 +257,10 @@ def build_tft(hmi: HMIFile, editor_dir: str = DEFAULT_EDITOR_DIR) -> bytes:
raise Unsupported("display direction %d" % pm["direction"])
w, h = project_size(hmi)
pages = [Page.parse(hmi.read(name)) for rtype, name in pm["resources"] if rtype == "pa"]
blob, records, ptable, objects, program_off = compile_pages(pages, hmi.read("Program.s").decode("latin-1"))
blob, descriptors, records, ptable, objects, program_off = compile_pages(pages, hmi.read("Program.s").decode("latin-1"))
area, info = resource_area(hmi, editor_dir)
base = tft.RES_START + len(area)
body = blob + records + ptable + objects
body = blob + descriptors + records + ptable + objects
body += b"\xff" * (-len(body) % 4)
head = bytearray(b"\xff" * tft.RES_START)
head[:0x70] = bytes(0x70)
@@ -213,9 +273,9 @@ def build_tft(hmi: HMIFile, editor_dir: str = DEFAULT_EDITOR_DIR) -> bytes:
head[0x32:0x3C] = bytes.fromhex("2100000001000c000000")
struct.pack_into("<II", head, 0x3C, base + len(body) + 4, len(area))
head[0x4C:0x54] = b"\xff" * 8
struct.pack_into("<I", head, 0x58, len(blob) + len(records))
pt = base + len(blob) + len(records)
layout = [len(blob), len(blob), 0, len(blob), tft.RES_START, base, pt, pt + len(ptable),
struct.pack_into("<I", head, 0x58, len(blob) + len(descriptors) + len(records))
pt = base + len(blob) + len(descriptors) + len(records)
layout = [len(blob), len(blob), len(descriptors) // 12, len(blob) + len(descriptors), tft.RES_START, base, pt, pt + len(ptable),
tft.RES_START + info["pictures"], 0, 0, 0, tft.RES_START + info["fonts"], program_off,
len(pages) | (len(objects) // tft.OBJ_SIZE) << 16, info["npics"], 0, info["nfonts"], 3]
for i, v in enumerate(layout):