UW1 PORT -- OBJECT RENDERING IN THE 3D DUNGEON VIEW
(branch `objects`. Companion to tile-rendering-findings.txt.)

STATUS: not on screen yet. Objects now load their real 16x16 OBJECTS.GR
sprites and their billboard quads project onto the 3D viewport with a valid
texture, but paint no pixels -- the quad carries no U/V texcoords so the
span sampler only ever hits texel (0,0) (transparent). See "STATUS ... (2)"
at the bottom for the current, corrected picture; the two middle sections
("WHY THE BILLBOARDS ARE INVISIBLE" texptr theory) are superseded.

═══════════════════════════════════════════════════════════════════════════
WHERE OBJECTS WOULD RENDER
═══════════════════════════════════════════════════════════════════════════
render_dungeon_view (was FUN_00012970) draws TILE geometry only -- view
matrix, visibility walk, vertex transform, near-clip, render_visible_tile_list.
There is NO object pass in it.

Objects are meant to be emitted from process_visible_tile_cell (was
FUN_0005e604), which for each visible tile calls:

    if (getenv("UW_ENABLE_TILE_FEATURES") != NULL) {
      FUN_00065394(puVar23 + 1);       // <-- was hard-disabled
    }

FUN_00065394 = "render this tile's animated features and the objects sitting
on it (doors, switches, bridges, item billboards)". It:
  1. drains a deferred-object queue (DAT_0023b940[...]),
  2. walks the tile's object chain (resolve_object_link(param_1)),
     classifying each object and deferring some to adjacent tiles,
  3. sorts the survivors by depth (FUN_00064ec8 / FUN_00064e3c /
     FUN_00065128 / FUN_0006508c -- insertion/bubble sort on DAT_0023b8c8[]),
  4. for each, computes screen X/Y/Z (DAT_0023b904 / DAT_0023b920 /
     DAT_0023b91c) and a shade byte (DAT_0023bc88), then calls
     FUN_00060aa0(object) to emit the billboard.

FUN_00060aa0 (~uw.c:47775) appends draw opcode 0xae + slot + sprite/pos data
into the draw-command list DAT_00110fc0 (cursor; base DAT_0023aed0, rewound
by draw_command_list_rewind). It also fills parallel slot tables
DAT_0023b676[] / DAT_0023b4f4[] indexed by the billboard counter DAT_0023b830.

═══════════════════════════════════════════════════════════════════════════
FIXED ON THIS BRANCH (commits 73c8b73, 7647424)
═══════════════════════════════════════════════════════════════════════════
- FUN_00065394: two dropped Ghidra call args
    * `FUN_000535fc()` in the deferred loop  -> FUN_000535fc(slot id)
      (defaulted to 0 -> NULL record -> FUN_00065210 NULL deref)
    * `resolve_object_link()` at the loop tail -> resolve_object_link(param_1)
      (object chain was never advanced)
- FUN_0003671c + 3 siblings: `pcVar[-0x13ad30] = c` copy of DAT_0023c698 ->
  DAT_00101968 -- baked global-delta constant, a wild pointer in the
  recompile. Replaced with a bounded indexed strcpy. (Was blocking ASan
  testing of this whole area -- demo_dungeon_room hit it deterministically.)
- DAT_0023b848 / DAT_0023b8c8(+c9) / DAT_0023bb98(+99+9a): Ghidra split
  these object-sort scratch arrays into lone scalars; the indexed
  writes/reads landed on different memory -> EXC_BAD_ACCESS the instant
  UW_ENABLE_TILE_FEATURES was set. Now backed with real `static` arrays +
  field #defines (uw.c ~line 3382).

Result: `UW_ENABLE_TILE_FEATURES=1` + demo_dungeon_room runs clean
(regression-clean). ON/OFF screenshots are byte-identical -- see the
"WHY THE BILLBOARDS ARE INVISIBLE" section below for the traced reason
(it is NOT the 0xae draw-command list; class-0 objects render through the
same DAT_000a85d8[] mesh list as tiles).

═══════════════════════════════════════════════════════════════════════════
OPEN / NEXT STEPS
═══════════════════════════════════════════════════════════════════════════
1. Fix the object per-record texture pointer -- see "WHY THE BILLBOARDS ARE
   INVISIBLE". Pin down which counter indexes the DAT_000a85d8[] record
   near_clip_visible_tiles reads, and publish FUN_00040770's decoded sprite
   buffer through g_tile_texptr_emit[] at that index.
2. The 0xae / draw-command list (DAT_0023aed0..DAT_00110fc0) is a SEPARATE
   channel FUN_00060aa0 also feeds (opcodes 0x7a, 0xae, 0xb2, 2). Its
   consumer was not located -- likely only matters for render classes 1-3
   (class 0, the spawn objects incl. the bag, uses the mesh list). Not
   needed for the first objects on screen.
3. Once the texptr is correct, verify object quad screen coords / winding /
   size (class-0 scales by DAT_00202508 x DAT_002022f8 = sprite w x h) and
   painter's-order depth vs tiles.
4. Pre-existing latent bugs in the way of ASan testing this area:
   - set_player_tile_position uw.c:~27199: object_list_unlink on
     DAT_002029cc + DAT_00202080*4 + 2 faults (BUS) from main_menu_loop
     when DAT_00202080 is uninitialised-positive; needs a real range guard.
   The non-ASan build tolerates both; ASan does not.

═══════════════════════════════════════════════════════════════════════════
WHY THE BILLBOARDS ARE INVISIBLE  (traced 2026-09-07)
═══════════════════════════════════════════════════════════════════════════
Instrumented demo_dungeon_room at the natural spawn (UW_ENABLE_TILE_FEATURES=1):

- FUN_00065394 is called for ~75 visible tiles; many have objects (tile
  (16,0) has 4). All objects at spawn are render class 0
  ((&DAT_00202c9a)[type*0xd] & 3 == 0): type 0x80 (the bag), 0xc1-0xd5,
  0x140, 0x177.
- FUN_00060aa0's class-0 branch runs for each: emits opcode 0x7a + screen
  X/Y/Z into DAT_00110fc0, calls FUN_00040770 to decode the sprite, then
  builds a 4-vertex quad into DAT_000a85d8[] and bumps the geom record
  count (DAT_000a85d4 / DAT_0023b83c).
- render_dungeon_view: geom records 70 (tiles only, OFF) -> 84 (ON), and
  near_clip_visible_tiles keeps 70 -> 80. So ~10 object quads DO reach
  render_visible_tile_list.
- render_visible_tile_list rasterises all 80. Screenshot ON == OFF
  byte-for-byte -> the 10 object quads draw NOTHING.

Root cause: the per-record texture pointer. render_visible_tile_list reads
`g_tile_texptr_out[record]` (the side channel added because the in-record
4-byte texture field truncates on 64-bit). process_visible_tile_cell writes
`g_tile_texptr_emit[DAT_0023b83c] = get_texture_page(...)` for tiles.
FUN_00060aa0 / FUN_00040770 do NOT write that side channel for objects, so
object records read a stale/tile texptr (or null) -> null-texture span ->
no pixels.

The obvious fix (publish FUN_00040770's decoded sprite buffer via
g_tile_texptr_emit[DAT_0023b83c]) does NOT work as-is: at FUN_00040770 time
DAT_0023b83c is small (observed 6, 19, 22, 29, 38, 45, 61) while the same
object record shows up in near_clip's list at emit-index 70+. So there are
(at least) two record counters that have diverged:
  DAT_0023b83c  -- bumped by process_visible_tile_cell AND FUN_00060aa0
  DAT_000a85d4  -- the count near_clip_visible_tiles iterates
FUN_00060aa0 keeps them "in sync" with `DAT_0023b83c = DAT_000a85d4 = X+1`
at the end of class 0/1, but the value seen mid-function is not the list
index. Need to pin down exactly which counter indexes the DAT_000a85d8[]
record that near_clip reads, and write g_tile_texptr_emit at THAT index
(and confirm near_clip's emit->out remap carries it).

Once the texptr is correct, also verify: object quad screen coords /
winding / size are sane (the class-0 path scales by DAT_00202508 x
DAT_002022f8 = sprite w x h and a -6/-4 * 0.5 offset), and depth ordering
vs tiles (painter's order -- objects emitted after tiles should draw on
top).

═══════════════════════════════════════════════════════════════════════════
STATUS 2026-09-07 (2): sprites load + project, still no pixels
═══════════════════════════════════════════════════════════════════════════
DONE this pass:
- DAT_0023c7a0 undefined4 -> void*[0x140]. FUN_00040770's Ordinal_1041
  sprite buffer was truncated to 32 bits.
- LAB_000415d0 / LAB_00041610 / LAB_00041670 -- FUN_000417b4's per-entry
  post-process callbacks -- were no-op `return 1` stubs. They are the
  REGISTRARS: every .GR loaded through them (QUESTION/VIEWS/ANIMO/BUTTONS/
  CURSORS/3DWIN/OBJECTS/TMFLAT/TMOBJ) was read into a malloc'd buffer that
  was never put into DAT_0024e090[] (FUN_000408fc's table). Implemented
  them to register at DAT_0024e090[(base + entry_idx)*8] like FUN_00041708.
- FUN_00040770: forward the two dropped args (sprite id, shade); resolve
  the id via FUN_00040aa8; publish the decoded buffer through
  g_tile_texptr_emit[DAT_0023b83c] (the record index IS DAT_0023b83c --
  the "out of sync" note above was a misread of a >=70-filtered trace).
- FUN_00040aa8: the id<0x1000 branch indexed DAT_0024d090, an object-type
  remap table never populated in this decompile -> return the id directly
  (OBJECTS.GR is registered at absolute frame indices; frame N == type N).

Now: in-view objects decode their real 16x16 OBJECTS.GR sprites (bag =
type 0x80, format 8 RLE, palette 3) and FUN_00060aa0 class-0 builds a
billboard quad that near_clip_visible_tiles projects onto the viewport
(traced: rec 68 verts (202,109)(202,151)(248,151)(248,109) -- a clean
on-screen 46x42 quad with a valid sprite texptr). raster_triangle is
called for it. Still zero pixels: ON == OFF screenshot byte-for-byte.

LAST GAP -- texture coordinates. render_visible_tile_list samples the
sprite via per-vertex texcoords the near_clip output record carries at
piVar14[0x10..0x13]. For tiles, process_visible_tile_cell writes each
vertex's src texcoord into the DAT_000a85d8[]-region float triple
(offsets +0,+4,+8 of the 0xc-byte vertex: x, ?, y) and near_clip
interpolates +0x3008 / +0x300c (projected x' / a ref coord) through the
clip. FUN_00060aa0 class-0/1 writes each billboard vertex's x/y/depth but
NO u,v -- so raster_textured_span samples only texel (0,0), which for an
OBJECTS.GR sprite is the transparent corner -> whole quad transparent.

Next: work out the exact vertex-record layout near_clip expects for the
texcoord (compare a tile vertex write in process_visible_tile_cell around
uw.c:46960-47010 with the FUN_00060aa0 class-0 write around
uw.c:47955-48110), and set (0,0)-(w,h) uv on the four billboard corners.
Also verify winding vs raster_triangle and painter's-order depth.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-07 (3): objects render
═══════════════════════════════════════════════════════════════════════════
FUN_00040770 also dropped FUN_000129f8's 3rd arg -- the .GR entry
compression mode (*pcVar3, 6/8/0xa). The decoder took its param_3==0 path
and returned an all-transparent bitmap (traced: bag = 0/256 nonzero
bytes). Forwarding `*pcVar3` fixes it. Commit 19d98ce.

The spawn container/bag (object type 0x80) now paints on the floor at the
lower-right of the 3D viewport with UW_ENABLE_TILE_FEATURES=1. See
milestones/objects-render-in-3d-view.bmp.

REMAINING (quality, not blocking):
- No explicit U/V on the billboard quad -> raster_textured_span samples by
  projected screen position, so the sprite looks blocky/stretched rather
  than a crisp 16x16. Add (0,0)-(w,h) uv to FUN_00060aa0's class-0/1 quad
  corners in the layout near_clip carries at output-record [0x10..0x17].
- Object depth vs walls (painter's order) not verified.
- Render classes 1-3 (doors/switches/bridges) and the 0xae draw-command
  path still untested -- only class 0 (item billboards) confirmed.
- UW_ENABLE_TILE_FEATURES is still a gate; flip it on by default once
  classes 1-3 and depth are checked.
  [DONE 2026-09-08, commit 4fcb168: now default ON; opt out with
  UW_DISABLE_TILE_FEATURES. Classes 1-3 / depth still only lightly
  exercised but nothing crashes with it on.]

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-07 (4): transparency + palette fixed
═══════════════════════════════════════════════════════════════════════════
The user's two observations were the format-8 RLE decode:
- FUN_000129f8's 3rd arg (compression mode, *pcVar3) was dropped, so it
  took its param_3==0 path -> all-transparent bitmap.  FIXED commit 19d98ce.
- With the mode restored it takes the format-8 branch, whose RLE fill
  (FUN_000132c4) looks run colours up through DAT_000b4610.
  blit_sprite_row_remapped (the setup helper) RESETS DAT_000b4610 to the
  0x0a-filled scratch DAT_000842ac on the way out, so every run resolved
  to palette index 0x0a (a flat tan) and there were no transparent
  (index 0) pixels.  FIX: point DAT_000b4610 at the aux palette (param_2)
  before FUN_000132c4.  commit 9f21ca3.

Now: bag (type 0x80) decodes 134/256 opaque px, real palette, transparent
background; walls/door show through. milestones/objects-render-fmt8-palette.bmp.
demos/demo_objects.txt frames a room with several objects.

REMAINING:
- No explicit U/V on the billboard quad. render_visible_tile_list takes
  the per-vertex texcoord from the near_clip output record [0x10..0x17],
  which near_clip fills from the vertex's PROJECTED position
  (iVar7 + 0x3008 / +0x300c). For a world-locked tile texture that works;
  for a sprite it means the 16x16 is sampled by screen position, so a few
  (mostly wall-mounted) object sprites still show garbled -- red glyph-like
  specks. Needs a real change: either a per-record "billboard" flag that
  makes near_clip emit 0..w / 0..h uv for the 4 corners, or write the uv
  into a field project_verts_through_view_matrix does not overwrite.
- Floor items render small; billboard scale (FUN_00060aa0 class-0's
  sprite_w * -6 * 0.5) may need tuning.
- Object vs wall depth (painter's order) not verified.
- Render classes 1-3 (doors as geometry / switches / bridges) still only
  lightly exercised.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11: THE RENDER-CLASS DISPATCH MECHANISM, PRECISELY
═══════════════════════════════════════════════════════════════════════════
This has come up enough times above ("render classes 1-3", "class-0 objects
render through the mesh list") that it's worth nailing down exactly what
decides which code path an object takes. Short answer: it is a static
per-object-*type* property table, NOT a function-pointer table -- a
different mechanism from the frame/mode dispatch tables this project found
hidden elsewhere (DAT_00085668, DAT_00085728, PTR_FUN_00087220 -- see
memory.md's "HOW WE GOT THE DISPATCH TABLES POPULATED"). Don't conflate the
two; this one really is just an if-chain reading a data field, confirmed
fresh from Ghidra, not a lost jump table.

THE TABLE: comobj.dat, loaded once at startup into DAT_00202c90 (uw.c
~41163-41184). 512 fixed records, one per object *type* ID (0x000-0x1ff),
indexed directly as `(&DAT_00202c9X)[type_id * 0xd]`. On disk each record
is 11 bytes; in memory the stride is 13 (0xd) bytes, so offsets 4 and 0xc
are real, permanent padding (confirmed: comobj.dat is exactly 512*11+2 =
5634 bytes; the loader's own read calls only ever touch 11 of the 13
bytes per iteration, uw.c ~41173-41181). This is a PER-TYPE table --
separate from each individual placed object's own live record (tile
position, heading, quality/flags), which is walked from each tile's object
chain and holds per-*instance* state. Rendering always needs both: the type
record says what KIND of thing this is and how to draw it; the instance
record says where.

THE DISPATCH FIELD: byte offset 0xa of the type record (DAT_00202c9a). Its
low 2 bits are the "render class" read at the top of emit_tile_objects
(was FUN_00060aa0), uw.c ~49659 (`bVar13 = (&DAT_00202c9a)[(id&0x1ff)*0xd]
& 3`):
  0 -- mesh/sprite billboard quad (LAB_emit_mesh_sprite_quad) -- the
       default path; ordinary items, the spawn sack, and (as of this
       session) the OLD boulder behavior before it got its own special
       case.
  1 -- critter: animated, direction-octant sprite via CRxxPAGE.Nxx +
       ASSOC.ANM (resolve_critter_sprite_tier / decode_critter_sprite_page).
  2 -- door / wall-sign -- both rerouted into the SAME class-0 quad path
       (`goto LAB_emit_mesh_sprite_quad`), split apart *inside* that branch
       by the object's own `id & 0x30` (door vs TMOBJ sign/plaque), not by
       anything in comobj.dat.
  3 -- light/quantity-flagged special billboards (torches, thrown-weapon /
       muzzle-flash effects) via emit_object_billboard(0x14 or 0x16, ...).
Bits 2-5 of this SAME byte are read elsewhere (uw.c:41305, `>>2 & 0xf`) for
an apparently unrelated purpose (looks light-radius-shaped) -- the byte is
multiplexed, "render class" is only ever its bottom two bits.

ONE FUNCTION, NOT SEVERAL: before touching any of this for the Models work
below, got a FRESH Ghidra decompile of the real emit_tile_objects
(FUN_00060aa0) specifically to check whether the class dispatch was secretly
a jump/function-pointer table Ghidra had collapsed into an if-chain (the
exact bug class DAT_00085668 turned out to be). It is not -- the real
binary's dispatch is a genuine, exhaustive 2-bit if/else, matching our
recovered uw.c exactly, no drift from past sessions' editing. So in this
codebase, "different object types get dispatched to different render
functions" really means: ONE function, called once per object as each
visible tile's chain is walked, branching internally on this 2-bit field,
with FURTHER hardcoded object-ID special cases layered inside each branch
on top of that (id 0x160-0x16f == TMOBJ signs; id & 0x30 == door vs sign;
id 0x153-0x156 == boulder-model lookup, added this session, see below).
There is no clean single table that fully answers "what renders this
object" -- it's the comobj.dat class byte PLUS a growing pile of id-range
checks hardcoded directly in emit_tile_objects.

THE NEGATIVE FINDING THAT MATTERS MOST: this 2-bit field tops out at 4
values, and there is no 5th "true 3D model" case anywhere in this Pocket PC
build -- not a lost/masked bit, genuinely absent (see the Models
investigation below, which checked this thoroughly rather than assuming
it). Whatever mechanism the original PC version may have used to select
real vertex-model objects, this WinCE port's object dispatch never had
that case; everything funnels into one of the four billboard-shaped paths
above. Reviving true 3D model rendering therefore could not be "find the
dropped case" -- it required bolting on a brand new object-id special case
that intercepts specific IDs before this dispatch even runs.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-11: MODELS -- FIRST REAL 3D-MODEL OBJECT ON SCREEN
(boulder family; companion investigation to the class-dispatch writeup above)
═══════════════════════════════════════════════════════════════════════════
Repro used throughout: `SETPLAYERPOS 9.53 3.66 64 181 16` in a demo script
(a real position captured live via sync_camera_from_player's always-on
`[playerpos]` console print) -- a boulder is supposed to sit in front of
the player here; the 3D viewport showed only an empty dead-end alcove.

FINDING THE BOULDER: `UW_DUMP_NAMES=1` (new debug hook, brute-forces every
(page,id) pair through FUN_0007863c and prints non-empty results) found
page 4 is the real object-name table (comobj.dat's own "name" data is just
damage-adjective prefixes like "ruined"/"broken" -- a dead end): 0x153/
0x154 = "a_large boulder", 0x155 = "a_boulder", 0x156 = "a_small boulder".
A companion `UW_DUMP_ALL_OBJECTS=1` hook (every object's tile/id/flags/full
13-byte comobj.dat row) found id=0x154 sitting right at the repro tile with
renderclass=2 -- routed through the door/sign quad reroute and projecting
to scrx=4208, wildly outside the ~224px viewport. Invisible, not absent.

DUE DILIGENCE BEFORE BUILDING ANYTHING NEW: data/DATA3D/*.E holds 29 real
3D-model files (text format: BEGIN/POINTS/PARTS/.../END), already parsed at
startup by FUN_00038680 (uw.c ~24980) calling FUN_00020a74 (uw.c ~13195)
into 29 persistent buffers (DAT_00114c1c..DAT_0017e0ec) -- but nothing in
this decompile ever read them afterward. Rather than assume "dead code,
build a renderer from scratch," did the same due diligence this project's
history says to do for suspiciously-dead data (see the DAT_00085668 writeup
in memory.md): a real Ghidra reference search against UU.exe found ZERO
consumers of any of the 29 buffer addresses anywhere in the binary except
the loader (InspectModelBuffers.java, scratchpad); a raw-byte-pattern scan
across every initialized memory block for those same 29 addresses (in case
a compile-time pointer table held them without a Ghidra-recognized
reference -- the exact DAT_00085668 bug class) found nothing
(FindPointerTables.java); a full .text undefined-byte-gap scan found zero
gaps larger than 16 bytes anywhere in the executable region, so there's no
room for an undiscovered consumer function either (CheckUndefinedGaps.java);
the fresh emit_tile_objects decompile above ruled out a collapsed dispatch
case; and comobj.dat's loader (see the dispatch writeup above) confirmed
its "extra" padding bytes are real padding, not a dropped model-index
field. CONCLUSION, checked rather than assumed: this Pocket PC port shipped
the model loader but never wired a renderer to it. Reviving it meant
writing a real consumer, not unstubbing a hidden one.

A REAL BUG FOUND ALONG THE WAY: while instrumenting the loaded buffers
(UW_DUMP_MODEL_RAW=1) to reverse-engineer the output format, every parsed
point's first float came out as a constant 3.0 while Y/Z matched the
source .E text exactly. Root cause: FUN_00020a74's POINTS-parsing loop
calls Ordinal_2032() (int->float) for X with the argument dropped, while
the next two lines convert Y and Z correctly -- the same "dropped
argument, ARM register-leftover idiom doesn't survive a literal recompile"
bug class as everywhere else in this file, just never caught before
because nothing consumed the output. Fixed (uw.c ~13427). This had been
silently corrupting the X coordinate of every point in all 29 loaded
models the whole time, independent of whether a renderer existed.

FUN_00020a74's OUTPUT BUFFER LAYOUT (recovered empirically, by dumping and
diffing against the real .E text, after the X-coordinate fix): offset 0 =
point count (int); offset 4 = part count (int, with an occasional spurious
trailing 1-vertex entry -- filtered by requiring 3 <= vcount <= 4); points
at `8 + i*0xc` as 3 back-to-back little-endian floats (X, Y-up, Z-depth,
matching the .E file's own axis order); parts at `0xc14 + p*0x60`: a vertex
count (int) then that many vertex-index ints (into the points array)
starting at `+4`.

THE RENDERER: emit_model_object (new, uw.c, just above emit_tile_objects)
pushes each model FACE as its own record into the shared
DAT_000a85d0_backing arena (doc comment ~uw.c:116) that tile wall/floor
geometry already uses, and lets the EXISTING
translate_verts_to_camera_space / project_verts_through_view_matrix /
near_clip_visible_tiles / render_visible_tile_list pipeline do real
per-vertex 3D transform and N-gon-fan rasterization -- confirmed
render_visible_tile_list was already generic over a record's point count,
not hardcoded to 4 (quads), so this needed zero rasterizer changes. This
reuses the real 3D transform pipeline rather than extending the
class-0 quad path's screen-space billboard-extrusion trick (which only
ever places one flat rectangle around an already-projected 2D anchor, and
would not have given genuine per-vertex 3D projection at different
distances/angles).

Model points are rotated by the object's heading (0-7, 45-degree steps)
and added to the object's already-computed world anchor (DAT_0023b904/
91c/920 -- despite being printed as "scrx/scry/scrz" by an earlier debug
hook, these are pre-translate WORLD-ish coordinates in the same
256-units/tile scale as tile geometry, not final screen pixels) in the
same (X, height, depth) field order process_visible_tile_cell uses for
real tile vertices. UW_MODEL_SCALE (default 8.0) converts the model's
small local .E units (a rock spans roughly -18..24) into that world scale.
Faces render texture-less (texptr left 0, a flat constant shade) rather
than solving real UV/material mapping in this pass -- see "LAST GAP" above
(the still-open 2D-sprite UV problem) and Open below; both need the same
fix eventually.

Object-id -> model lookup (lookup_boulder_model, small switch, same shape
as the existing door/sign id-based special-casing in emit_tile_objects's
class-2 branch): 0x156 "a_small boulder" -> ROCKSMAL, 0x155 "a_boulder" ->
ROCKMED, 0x153/0x154 "a_large boulder" -> ROCKBIG. No id->model field
exists anywhere in comobj.dat or the binary (see due diligence above) --
this is a hand-built table, not a recovered one, intercepted at the very
top of emit_tile_objects (right after the object id is read) so boulders
skip the normal render-class dispatch entirely. UW_DISABLE_MODEL_RENDER=1
reverts to the old billboard-quad behavior for comparison.

RESULT: screenshot at the exact repro position (defaults only, no env
overrides) shows a real, recognizable, flat-shaded polygonal boulder
resting in the room ahead of the player -- multiple facets at different
angles and shading, not a flat billboard. Zero crashes across the repro
run or the full .E-model-loading startup sequence. UW_DEBUG_MODEL=1 prints
each model emission's heading, anchor, point/part counts, and how many
faces passed the vertex-index sanity check (52/53 for the ROCKBIG boulder
used in the repro, one part filtered for an out-of-range vertex count).
Committed a89ae5a on branch `objects`.

OPEN / ROUGH FOR NEXT TIME:
- Height calibration is a hand-tuned constant (UW_MODEL_YOFF, default
  -200), not derived from the tile's real floor-height field the way tile
  geometry computes it (process_visible_tile_cell's `*(byte*)(...)*0x40`
  lookup, uw.c ~48621-48624). Untested at a second boulder / different
  floor height -- don't trust -200 as universal yet.
- No texture/material. Every face is flat, untextured, one shade.
  EXTENDED_COLORS in the .E format (a per-part RGB triple) is parsed by
  FUN_00020a74 into scratch memory but never carried into the per-model
  output buffer this session traced -- needs its own offset-recovery pass,
  same technique as points/parts above. Solving this and the still-open
  2D-sprite UV gap ("LAST GAP" section above) likely share a fix.
- Only the boulder family is wired. lookup_boulder_model is a 4-entry
  table; extending it to doors/chests/tables/beds/etc (all 29 loaded .E
  files, load order in FUN_00038680, uw.c ~24980) is a small table
  addition using the same mechanism -- but each family needs its own
  UW_DUMP_NAMES + UW_DUMP_ALL_OBJECTS id-hunting pass (no id->model field
  exists anywhere to just read off) and possibly its own height offset.
- Arena headroom: emit_model_object guards the same ~512-vertex/~490-record
  arena cap the tile/quad paths already do, sized to the specific model's
  real point/part counts rather than a fixed budget -- untested with
  multiple model objects visible in the same room at once.
- Debug hooks added this session, env-gated, safe to leave in place:
  UW_DUMP_ALL_OBJECTS, UW_DUMP_NAMES, UW_DUMP_MODEL_RAW (superseded now
  that the buffer format is documented in code, kept for future
  model-family work), UW_DEBUG_MODEL, UW_MODEL_SCALE, UW_MODEL_YOFF,
  UW_DISABLE_MODEL_RENDER.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (2): BRIDGES, SHRINE, DOOR FRAMES+LEAVES WIRED UP
═══════════════════════════════════════════════════════════════════════════
Extended the boulder mechanism (previous section) to 3 more families.
lookup_boulder_model -> lookup_object_model, now table-driven
(g_model_map[]: id, model buffer, name, per-entry scale/yoff/y_clip, plus
an optional second model+local-X-offset for composites) instead of a bare
switch, so the render dispatch and UW_DUMP_OBJECTS_FILE's "model" column
share one source of truth. Ids found via UW_DUMP_OBJECTS_FILE (much
faster than the old stderr scans): 0x164="a_bridge", 0x157="a_shrine",
0x140-0x145/0x147="a_door"/"a_secret door" (closed), 0x148-0x14d/0x14f=
"an_open door"/open secret door.

KEY LESSON -- scale is NOT universal, read each .E file's real POINTS
range before guessing: boulders needed scale=8 (local points span roughly
-20..25 on every axis, a model-specific small unit); FBRIDGE/SHRINE/
DFRAME/DOOR's points already span real tile-sized ranges (FBRIDGE's X/Z
run exactly -128..128 = one 256-unit tile; DOOR.E's 128-unit width
matches DFRAME's inner opening exactly) -- these are authored directly in
world units, scale=1. Confirmed empirically: scale=8 on DFRAME (which has
POINTS up to local Y=1024) made it ~32 tiles tall and rendered as
nothing; scale=1 immediately gave a plausible door-sized shape.

DFRAME.E ALSO has deliberately over-tall "riser" parts (2 of 11, local Y
up to 1024 vs the real frame's Y 0-208) -- likely meant to be clipped
against each room's real ceiling by the original renderer so the frame
never shows a gap regardless of room height. No ceiling clip here, so
emit_model_object gained a y_clip param (UW_MODEL_YCLIP to override):
drops whole faces if any vertex's LOCAL Y exceeds the cutoff, rather than
drawing the risers unclipped. 300 for DFRAME, 0 (disabled) elsewhere.

COMPOSITE OBJECTS -- user feedback mid-session: a door is really two
DATA3D models, not one. DFRAME.E (frame) + DOOR.E (leaf), the latter
loaded twice by FUN_00038680 (indices 13/14, identical content --
presumably two runtime instances of one leaf mesh). emit_model_object
gained xoff_local (added to each vertex's local X before rotation):
DOOR.E's own points span local X 0..128, DFRAME's inner opening spans
-64..64 (also 128 wide) -- xoff_local=-64 centers the leaf in the frame's
gap. ModelMapEntry gained optional model2/name2/x_off2; closed door ids
get both frame+leaf, open ids get the frame only (no real swing-angle/
pivot data for an opened leaf -- an empty doorway is less wrong than a
leaf floating in the frame's own plane).

RESULT: door screenshot at tile (24,7) shows real geometry filling the
doorway (vs. plain dark passage with UW_DISABLE_MODEL_RENDER=1) -- though
adding the DOOR.E leaf visibly changed the silhouette from one solid
panel to a smaller shape near the bottom, most likely z-fighting between
the frame's and leaf's coplanar/overlapping faces (no depth bias
implemented). Bridge confirmed clearly -- a recognizable flat railing/
deck structure, visible from an oblique downward angle (the head-on view
faced an unlit chasm beyond the bridge and correctly rendered black, not
a bug -- verified by checking 4 headings from the same spot, only the
one facing away from the chasm showed a lit corridor).

SHRINE (0x157): wired identically, confirmed EMITTING real geometry
(UW_DEBUG_MODEL: 76/77 faces from a 101-point model, matching SHRINE.E's
real size) but never visually confirmed on screen. Tried 8 headings from
one adjacent tile, a second standing tile on the opposite side, and 5
different UW_MODEL_YOFF values (-50..-400, each producing a different,
non-identical screenshot but never showing the shrine) -- a pure Y
miscalibration should have swept through some visible position across
that range, so the likely explanation is the standing tile picked from
the object census just doesn't have real line-of-sight to the shrine's
tile (tile adjacency in the census doesn't guarantee an open wall
between them). Needs a real walk-there-and-look repro next time instead
of more SETPLAYERPOS-from-adjacency guessing.

NEW DEBUG HOOK: UW_DEBUG_FLOORZ (demo_set_player_pos) prints a tile's
real floor-derived Z before SETPLAYERPOS's explicit Z overrides it.
Building repro positions by guessing Z (like the original boulder repro's
z=64, which turned out to be specific to that one room) doesn't
generalize -- this session's door/bridge/shrine repros all used the real
per-tile value from this hook; the earlier attempts at a guessed z=64 for
the door/bridge rendered solid black (camera underground/in a wall at the
wrong height) until switching to the tile's real floor z fixed it
immediately.

ALSO OBSERVED, NOT EXPLAINED: the object world anchor (DAT_0023b904/91c/
920) landed within roughly 4200-4500 on the X axis across every test
this session (boulder, door, shrine, bridge), despite those objects' real
tile X coordinates ranging from 9 to 46 -- reinforces the existing "not a
plausible absolute pixel column" note from the boulder milestone, and
suggests these are camera/scan-relative values recomputed fresh per
object per frame rather than translatable to a tile number by any simple
formula. Didn't block this session (relative placement between objects
in the same frame was still correct -- three adjacent bridge segments'
anchors differed by exactly 256, matching their real one-tile spacing)
but worth remembering before trying to derive absolute world position
from it directly.

New/changed debug hooks: UW_DEBUG_FLOORZ, UW_MODEL_YCLIP.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (3): MODEL HEADING WAS MISSING THE CAMERA-QUADRANT FIX
═══════════════════════════════════════════════════════════════════════════
User question: "doors can have different directions, is the object heading
wired up for models?" Short answer at the time: heading WAS read and used
to rotate the model (param_1[1]>>6&7, the same field critters/signs/doors
all read elsewhere), but it was missing a correction this exact codebase
already had to learn was necessary for this exact field, in the sibling
door/sign billboard-angle-override code (class-2 branch, uw.c ~50536-50550
and ~50647-50653): the raw stored heading is in a fixed world-compass
frame, but the whole rendering pipeline (tile walk, wall/floor geometry,
AND the object world anchor DAT_0023b904/91c/920 this session's model code
places its vertices relative to) operates in a frame pre-rotated by
DAT_0023b4a0 -- the camera's current 90-degree screen-rotation quadrant
(0-3, recomputed every frame in build_frame_draw_list from the camera's
own yaw). That existing code's own comment: "this same file rotates every
OTHER object's stored orientation-ish fields by it... but this heading
read never did" -- confirmed live at the time to cause 90-degree-off /
invisible rendering depending on camera stance. This session's new model
code reproduced the identical class of bug.

FIX: `_heading = (_raw_heading - 2*(int)DAT_0023b4a0) & 7` at the model
interception point in emit_tile_objects (uw.c, right before both
emit_model_object calls), matching the sibling code's formula (without
its extra "+1 compass step" -- that correction was specific to the
billboard quad's own sin/cos lookup-table convention for extending a 2D
quad, not obviously applicable to a real 3D rotation matrix; not applied
here since nothing so far indicates a 45-degree-off symptom for the 3D
models -- revisit if one shows up).

VERIFIED via UW_DEBUG_MODEL's new heading log line
([model-heading] id=... raw=... quadrant=... compensated=...): the SAME
physical door (id 0x140 at tile 24,7) logged raw=5/quadrant=0 and
raw=1/quadrant=2 in the same demo run (quadrant fluctuated briefly while
the camera settled after SETPLAYERPOS) -- both resolve to the SAME
compensated=5 after the fix, confirming the door's apparent orientation
is now stable regardless of which camera quadrant it's viewed from,
rather than silently flipping depending on incidental camera state (the
bug this fix removes). Boulder regression-checked too (same shared code
path applies to every model family, not just doors): its heading is
usually raw=0 (default, unrotated per its .E authoring) but came out
compensated=4 (180 degrees) at the boulder repro position, since the
camera happened to be in quadrant 2 there -- screenshot confirms it still
renders as a plausible, undistorted 3D rock, just a different facet
silhouette than before (expected and harmless for an asymmetric loose
rock; would matter more for a wall-aligned object like a door, which is
exactly where this was found).

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (4): MODELS ALSO NEEDED A 45-DEGREE STEP, BUT THE OPPOSITE SIGN FROM SIGNS/DOORS
═══════════════════════════════════════════════════════════════════════════
User question: "does the model heading need the same +1 compass-step fix
signs/doors needed?" Good instinct -- yes, but the sign was wrong to
assume it'd be the SAME correction.

The sign/door billboard-angle-override code (uw.c ~50670-50680) applies
`((quadrant_heading + 1) & 7) * 45` -- a "+1 compass step" on top of the
quadrant compensation, confirmed live in that code's own comment ("45
degrees off from flush -- one compass step correction"). Assumed at
first this would carry over unchanged to the new 3D model code. Tested
it properly instead of assuming: added a temporary UW_MODEL_HEADING_
OFFSET env override and screenshotted the door repro (tile 24,7) across
all 8 possible compass-step offsets (-3 through +2 tested explicitly,
the rest by symmetry). Result: offset 0 and +1 (the sign/door value)
BOTH rendered as a thin, nearly edge-on sliver -- the frame's broad face
turned almost perpendicular to the camera, barely visible; +2 was a
visibly skewed parallelogram; -2/-3 were skewed or thin again; -1 was
the ONLY offset that produced a clean, axis-aligned rectangle flush with
the doorway, matching the surrounding wall geometry exactly.

So the correction is real (confirms the user's instinct), but its SIGN
is the opposite of the billboard code's +1 -- makes sense once you
think about WHY: the billboard code rotates a 2D quad-extension
direction through a sin/cos LOOKUP TABLE (DAT_000d9ed8/DAT_000d9930),
while this session's model code applies a real rotation MATRIX
(cos/sin computed directly) to actual 3D model-space vertices. Those
are two different rotation conventions/senses that happen to share the
same underlying "quadrant compensation" need but not the same fixed
offset on top of it -- porting the sign code's exact constant without
re-testing would have been wrong. Baked in as the new default (`_step =
-1` in the model heading block, uw.c, right after the quadrant
compensation), with UW_MODEL_HEADING_OFFSET still available as an
override for future tuning. Boulder and bridge regression-checked with
the new default -- both still render as plausible, undistorted shapes
(expected: boulder is asymmetric so any rotation looks like "a rock";
bridge's own heading happened to not visibly change orientation at its
repro spot).

Tried to also confirm on a second, independently-placed door (tile 9,10,
a different raw stored heading than the repro door) as a generalization
check -- inconclusive, not a contradiction: the debug log showed multiple
different raw heading values for "the same" id 0x140 within one static
demo run, which is more likely 2+ separate door objects in view at that
busier corridor position (not tracked apart in the quick test) than a
real per-frame heading change, and no obvious door silhouette was visible
in that screenshot at all (possibly occluded/edge-on from that specific
stance). Given the first test's result was unambiguous across a clean,
isolated single-object sweep, treated that as sufficient rather than
chasing a messier second repro -- but this is the natural next thing to
verify if a differently-oriented door ever looks wrong.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (5): DOOR FRAME WAS MISSING ITS CONNECTING HEADER -- CLAMP, DON'T DROP
═══════════════════════════════════════════════════════════════════════════
User: "the door frame locations look off. Test what they look like with
just the door frame, without the door." Added UW_MODEL_NO_LEAF=1 (skips
model2 only) to isolate DFRAME.E from DOOR.E and screenshotted it alone.
Result made the bug obvious: two short, disconnected grey blocks sitting
at floor level in the left/right of the opening, with plain background
wall visible above AND between them -- not a real archway. Raising the
whole thing 32 units (UW_MODEL_YOFF=-68) just floated both stumps up
slightly with a new gap opening at the floor; they still never connected
at the top, which ruled out a simple vertical-offset problem.

ROOT CAUSE: the y_clip mechanism added in UPDATE (2) dropped a whole PART
if ANY of its vertices exceeded the cutoff -- but DFRAME.E's two "riser"
parts (indices 4-5) aren't purely over-tall junk: their BOTTOM edge sits
at local Y=208 (exactly the top of the real frame posts) and their TOP
edge at Y=1024 (the over-tall part). That bottom edge is the header panel
that visually connects the two posts across the top of the doorway.
Dropping the whole face because of its (correctly excluded) top edge also
silently deleted the (wanted) connecting geometry -- explains the
disconnected-stumps look exactly.

FIX: clamp each vertex's local Y to the cutoff during the vertex-transform
pass (before parts are built), instead of skip-testing whole faces in the
parts loop. Safe per-vertex here because DFRAME.E's Y=1024 points aren't
shared with any other, correctly-sized part. Result: emitted face count
back to 11/12 (was 9/12 with the drop approach), and the frame now
screenshots as a real connected archway -- a header spanning the top of
the opening with the passage clearly open below it, not two floating
stumps. Composite (with DOOR.E leaf restored) now reads as an actual
door: header up top, leaf filling most of the opening beneath it.

User follow-up: "those header pieces should stretch to the tile height --
set the y_clip heights to the ceiling height" instead of the arbitrary
300 guess from UPDATE (2). Looked for a real per-tile ceiling-height field
to read instead of a constant: collision code's floor-height sampler
(collision_sample_floor_height, uw.c ~39962) and the tile-height envelope
function (collision_height_envelope, uw.c ~40537) both only ever compute
FLOOR height from per-tile/per-corner data; the "ceiling clearance"
concept that does exist (_DAT_0008699f, reticle_object_pick) is a
movement/physics headroom check seeded from a large sentinel (0x7f) and
narrowed only by specific nearby overhead objects, not a per-tile
geometry field. Cross-checked against this project's own earlier tile-
rendering investigation (memory.md, UPDATE 18): "UW1's ceiling is a fixed
per-level texture, no per-tile ceiling bits" -- and the same investigation's
collision work found floor-height bytes read per-tile as "open ~80-96,
solid rock 128" in a raw sub-unit scale. No per-tile ceiling HEIGHT field
exists anywhere in this decompile to read -- matches the texture finding
that ceilings aren't a per-tile geometry concept in this game's format at
all, presumably a uniform one-slab-per-level height instead.

Given that, used the best-grounded proxy available rather than another
arbitrary guess: one full tile height (256 world units -- the same scale
confirmed via FBRIDGE.E's own X/Z point range running exactly -128..128)
divided by the model's own scale factor. For DFRAME (scale=1.0) that's
y_clip=256.0, replacing the old 300.0 guess (visually near-identical, but
now traceable to the game's actual world-unit convention instead of "a
number that looked okay"). Documented as an approximation, not a real
per-tile lookup, since no such field was found -- a genuinely tall or
multi-level room would still cap short at this height; worth revisiting
if that's ever observed.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (6): TEXTURING MODELS -- REAL TEXTURE DATA, ZERO VISIBLE DETAIL
═══════════════════════════════════════════════════════════════════════════
Next-work ask: "use the object's sprite as the door model texture; use
the tile's wall texture as the frame model's texture." Wired both up
using the exact mechanisms already proven correct elsewhere in this file
-- got real, valid texture data into the pipeline for both -- but NEITHER
produces visible texture detail on screen. This section is a full record
of what was tried and what was learned, because the actual blocker turned
out to be much deeper than "wire up a texture pointer."

WHAT WAS BUILT:
- emit_model_object gained a `texptr` parameter. Each record it creates
  now publishes through g_tile_texptr_emit[rec] (the same side-channel
  array every other texture consumer in this file already uses to work
  around the in-record field truncating a 64-bit pointer to 4 bytes) --
  texptr==0 keeps the old flat-shaded fallback unchanged.
- LEAF (door): reused the closed-door billboard branch's own already-
  correct sprite frame formula, `DAT_00202734 + (raw_type_word & 7) +
  0x30`, fed through FUN_00040770 (the same real sprite decoder the 2D
  billboard path uses) to decode it, then captured the resulting buffer
  from g_tile_texptr_emit[DAT_0023b83c] right after the call (rather than
  relying on index timing) so it could be stamped onto every record the
  leaf's several faces create, not just one.
- FRAME (door): found the tile's OWN real wall-texture index by reading
  DAT_0023b4ec[2] & 0x3f (DAT_0023b4ec is the raw tile record currently
  being walked; this exact field is documented a few hundred lines above
  emit_tile_objects, in the tile-wall-rendering code itself: "UW1 tile
  word2 (bytes 2-3) bits 0-5 = wall texture index"), added 0x3a (the same
  offset that same wall-rendering code adds before calling
  get_texture_page() for the 16x16 wall-sized arena slot specifically, as
  opposed to the unmodified value used for the 64x64 floor/ceiling case),
  and called get_texture_page() with it -- the identical call the real
  wall renderer makes for this exact tile.

BOTH TEXTURE POINTERS ARE GENUINELY VALID. Added a debug pixel-histogram
check (same technique the critter sprite decoder's own UW_DEBUG_CRITTER
hook already used) -- the leaf's decoded sprite came back 1408/2048
nonzero pixels, a real 32x64 door graphic, not garbage or an empty
buffer. The frame's wall texture pointer resolved to a real, non-null
get_texture_page() result too.

RESULT: applying the leaf's sprite texture made the leaf DISAPPEAR
entirely (worse than flat-shaded) -- consistent with object-rendering-
findings.txt's own much older "LAST GAP" finding (top of this file, from
the original 2D sprite-billboard work): render_visible_tile_list derives
each vertex's texture-sample coordinate from its PROJECTED SCREEN
POSITION (near_clip_visible_tiles, offsets +0x3008/+0x300c off a per-
vertex projected-coordinate cache), not a real per-vertex UV. That
happens to look fine for a large, continuously-tiling WALL texture
(screen position lands somewhere valid no matter what), but a small
finite sprite bitmap mostly samples outside its own bounds -> reads as
transparent -> the whole leaf vanishes. This is the SAME root cause the
2D billboard sprite path has always had, just newly confirmed to affect
3D models too, since they ride the identical rendering pipeline. Reverted
to opt-in only (UW_MODEL_LEAF_TEXTURE=1); default stays untextured
(unchanged from before this session's texture work).

Applying the frame's wall texture did NOT make it disappear (a wall
texture is large enough that screen-position sampling always lands
somewhere valid) -- but it also didn't show any real texture DETAIL: a
zoomed crop of the rendered header and leaf both show perfectly flat,
uniform color, no brick/stone graining at all, before and after the
texture was applied. Chased one specific lead: real wall-rendering code
(uw.c ~49025-49032, literally the block right before emit_tile_objects
in this same function) writes the texture's tile size (DAT_0023b824 --
16 for walls, 64 for floor/ceiling) into two record fields (rb+0x0,
rb+0x4) that emit_model_object was unconditionally zeroing. Fixed that
(now writes 16 for any textured record) -- no visible change. Went one
step further and read the SAME wall-rendering code's actual raw-VERTEX
writes (uw.c ~49048-49060) expecting to confirm the vertex's 2nd/3rd
float fields are plain world Y/Z (what emit_model_object assumes and
what already works correctly for position) -- they are NOT, for walls:
those fields are computed as `Ordinal_2032((position + DAT_00086bb0/
bb1[wall_segment_index]) * 0x100)`, blending the position with a texture-
repeat lookup table indexed by which wall segment this is. Wall geometry
has its OWN specialized vertex-encoding scheme with texture-tiling baked
directly into the position fields via that table -- it is not a generic
"any 3D triangle can be textured this way" mechanism, and does not appear
to generalize to arbitrary-oriented model geometry (which needs its raw
X/Y/Z to stay literal world coordinates for POSITION to keep working,
which it does, confirmed by every model screenshot in this file).

CONCLUSION: texturing arbitrary 3D model geometry in this renderer is a
substantially deeper problem than "find the right texture pointer and
publish it" -- every existing texture consumer in this codebase (tile
walls, floor/ceiling, 2D object billboards) is tightly special-cased to
its own geometry shape, and none of those special cases were built to
generalize. Solving it for real would mean reverse-engineering how
near_clip_visible_tiles' projected-coordinate cache (+0x3008/+0x300c)
actually turns into a texture sample for the RASTERIZER'S span-drawing
code (not yet traced this session), likely requiring either a genuinely
new per-vertex UV field nothing currently writes, or replicating wall
geometry's position/texture-blending trick for a rotated model (which
doesn't obviously make sense for non-axis-aligned surfaces). This is
project-sized work on the same order as the original "get 3D models
rendering at all" investigation, not a small follow-up -- flagging
clearly rather than continuing to guess-and-check further this session.

CURRENT STATE: the frame's wall-texture wiring is left ACTIVE (harmless
-- visually identical to the untextured flat-shade fallback it already
had, and the plumbing -- g_tile_texptr_emit publishing, the texsize
field fix -- is real, correct infrastructure worth keeping even though
it doesn't yet produce a visible result). The leaf's sprite-texture
wiring is left build-time-present but OPT-IN via UW_MODEL_LEAF_
TEXTURE=1 (default off), because applying it actively regresses (leaf
disappears) rather than merely failing to improve.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (7): THE .E PARSER COMPUTES A REAL FACE NORMAL -- AND THROWS IT AWAY
═══════════════════════════════════════════════════════════════════════════
Traced parse_e_model_file (was FUN_00020a74) end to end looking for
per-face normal data, prompted by the texturing dead-end above. Right
after reading each PARTS entry's vertex-index list, the parser calls:

    vec3_sub(P[v0], P[v1], edge1);    // was FUN_000137c0
    vec3_sub(P[v0], P[v2], edge2);
    vec3_cross(edge2, edge1, normal); // was FUN_00013904, real cross product

confirmed via the exact formula each helper computes (vec3_sub =
elementwise param_2-param_1; vec3_cross = the textbook 3-float cross
product, including the Y term's required sign flip) -- a genuine,
deliberate per-face normal computation, not a coincidence.

That result is never referenced again anywhere in the function. To rule
out a dropped-store decompile bug (this project's most common bug class),
pulled the REAL ARM disassembly from UU.exe at the call site
(0x00021aa4): `bl 0x00013904` is immediately followed by unrelated
vertex-count bookkeeping (`ldr r3,[sp,#0x38]; cmp r3,#0x4...`), no store
of the result anywhere in between. This is the real shipped binary, not
a decompile artifact -- the original game computes this normal and then
genuinely never uses it. There is no per-face normal data anywhere in
the final parsed model buffer emit_model_object reads from.

Separately confirmed while in there: the existing shading pipeline has
no per-face-normal concept to plug one into anyway -- every writer of the
render record's shade byte across this whole file (tile walls, floors,
doors, signs, emit_model_object) pulls from one shared ambient/light-
proximity global (DAT_000da47c), never anything geometry-derived. Real
per-face lighting variation would be new behavior, not a gap-fill.

═══════════════════════════════════════════════════════════════════════════
UPDATE 2026-09-11 (8): NO UV DATA EITHER -- THE FORMAT WAS NEVER TEXTURE-MAPPED
═══════════════════════════════════════════════════════════════════════════
Same investigation, extended to UV/texture coordinates (the direct
follow-up to UPDATE (6)'s texturing dead-end). Read the rest of
parse_e_model_file (PARTS through EXTENDED_COLORS/CLUSTERS/NODES/ANIMATE
and its final cleanup pass) end to end. Conclusion: no UV data exists
anywhere, in the file format or the parser -- more clear-cut than the
normal, which was at least computed.

- The .E format's only blocks, across every model file in DATA3D/: BEGIN/
  VERSION/NAMES/POINTS/PARTS/CLUSTERS/NODES/EXTENDED_COLORS/SCALE_SHIFT/
  END. No UV/TEXCOORD/MAPPING block anywhere.
- Each PARTS line has exactly 4 header fields before the vertex-index
  list: a flag (always 0 in every real file -- a `local_23c==4` "got
  bitmap" branch exists for a nonzero flag but is dead in practice),
  a 1-character code, a sequential part index, and a color value. No room
  for texture coordinates. The 1-character code is NOT UV-related either
  -- confirmed via the parser's own debug string: 'A' triggers a "making
  backside of %d %d" branch that duplicates a face with reversed winding
  (a double-sided-face flag), 'N' is the ordinary default. ('F'/'X' are
  two more recognized codes seen earlier in the function, for reversed
  vertex order and an unused "explicit bitmap" escape hatch respectively
  -- also not UV.)
- Went further than the normal check: even per-face COLOR -- both the raw
  hex material index and the EXTENDED_COLORS RGB entry (matched against
  g_model_known_ext_colors, was DAT_00084678, a 32-entry known-RGB table)
  -- suffers the identical fate as the normal. Traced the function's
  literal last operation before it returns (a scratch-to-scratch color-
  inheritance pass for parts that share a color with another part,
  gated by DAT_000db494) -- it writes back into scratch memory, never
  into the final output buffer. The only things that survive into what
  emit_model_object actually reads are point positions and each part's
  vertex-index list; normal, color, and (never-attempted) UV are all
  absent from the persisted model data.

Reframes the UPDATE (6) texturing dead-end: this was very likely never a
texture-mapped format to begin with. Its real design intent looks like
flat-per-face color (refined by the EXTENDED_COLORS palette-index
system), the way low-poly models from this era commonly worked, not
bitmap UV mapping. That's consistent with why chasing a UV system for it
hit a wall -- there was never one to find, not a bug to fix.

Also noted, not chased further (flagged rather than renamed): DAT_000db480,
DAT_000db470, and DAT_000db494 (the flags gating the 'A' backside logic
and the EXTENDED_COLORS resolution) have NO WRITER anywhere in this
decompile -- always BSS-zero, making that whole EXTENDED_COLORS-resolution
path dead code today regardless of whether a model file has the block.
Same "hidden writer, not yet Ghidra-checked" shape as DAT_00085668 and
friends from earlier in this project, but not run down this session --
worth a real Ghidra reference/byte-pattern search before trusting either
"always off" or "a real writer exists" as the answer.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27: CLEAN REIMPLEMENTATION ON A NEW BRANCH (3d-objects)
═══════════════════════════════════════════════════════════════════════════
A separate investigation this session (on branch e-model-texturing, off
this same main) found that emit_object_billboard/tick_anim_record --
the object catalog's ordinary "flat sprite" renderer -- has a second,
genuine native capability: tick_anim_record's own address-walk formula
resolves a "catalog" id to the exact same 29 real .E model buffers the
hand-built g_model_map hack (this file's MILESTONE 2026-09-11 above)
independently reloads from scratch. That's a real mechanism the original
binary had; g_model_map was always a workaround for not having found it
yet. Once found, e-model-texturing fixed 6 real bugs to get it working
end to end (a buffer-address-walk fix, 2 pointer-truncation crashes, a
texture side-channel gap, a duplicate-sprite draw, 3 wrong-heading call
sites, a bridge-texture formula, and a horizontal-face UV axis pick --
see that branch's own commit history for full details on each).

At the user's request, ported ONLY those real, evidence-based fixes onto
a fresh branch cut from clean `main` (the actual merge-base of this
whole investigation), explicitly EXCLUDING both hand-built workarounds
that predate the discovery: g_model_map/ModelMapEntry/lookup_object_
model/emit_model_object (the .E-model id-table hack), and the display-
list bytecode interpreter (a second, independent hack for the same
underlying gap, never present on main to begin with). Renamed the same
functions/locals e-model-texturing did (emit_object_billboard ->
emit_catalog_object, tick_anim_record's param_1 -> catalog, etc.) so the
two branches read the same way.

Notable branch-specific finding: main's own generic DAT_00086c80 sign/
decal dispatch already called emit_catalog_object directly with no
_decal_row[]/LAB_decal_frame_resolved indirection -- that table turned
out to be a pre-existing wrapper from e-model-texturing's OWN base
history (predating this session, not part of the fix set), not something
this session's fixes require. Confirmed live (see below) that main's
simpler direct dispatch already produces correct lever/switch/writing/
gravestone/bridge behavior once the heading and bridge-texture fixes are
applied -- so it was deliberately NOT ported, keeping this branch's
implementation smaller than e-model-texturing's for the identical
end result.

Also confirmed live: main's own emit_anim_object_frames and
emit_object_billboard were functionally identical to e-model-texturing's
pre-session starting point (diffed against commit 79e78aa, right before
that branch's own fixes began), and main's load_door_frames already used
the correct (fixed) 60000-based scratch constant rather than the
30000 value e-model-texturing had to introduce -- so no additional
branch-specific adaptation was needed beyond the renames.

VERIFICATION: clean compile after every change (scoped renames verified
via line-range grep before each sed/perl pass, to avoid touching a
variable's other, unrelated role in the same function -- e.g. iVar16/
iVar30/_v_offset each have a small-int role AND a pointer role in
emit_catalog_object, only the pointer role needed splitting out). Full
build + `BUILD=1 ./run-regressions.sh`: 6/6 clean. Live UW_DEBUG_DOOR
trace confirmed the exact same catalog resolutions e-model-texturing
documented: catalog=1 (DFRAME.E) -> 20 points/12 faces, catalog=14
(DOOR.E) -> 8 points/7 faces, catalog=2 (FBRIDGE.E) -> 8 points/5 faces,
and UW_DEBUG_DECAL confirmed the bridge's real TMOBJ texture resolves to
abs_frame=690 (within the documented TMOBJ 30/31 plank range) rather
than the old -1 placeholder. Screenshot confirmation: a real door mesh
(distinct paneled-door texture, not the flat corridor wall pattern
around it) visible from tile (23,5) looking at the door placed at
(22,5) -- repro: TELEPORT 23 5, REVEAL, REVEAL (a second REVEAL is
needed after any TELEPORT/SETPLAYERPOS -- the first redraw after a
teleport lands on the pre-teleport tile pointer, a known demomode gap
documented in demos/demo_dungeon_room.txt's own header comment). Bridge
mesh/texture verified via the debug trace above rather than a clean
screenshot -- every camera position tried near the bridge's placement
(36-38,24-25) put the player either inside solid rock (0 visible tiles)
or standing on/above the bridge itself looking into the chasm below it,
not at a useful oblique angle; not chased further this session since
the trace-level confirmation (real geometry + real texture id, matching
e-model-texturing's own proven-correct values exactly) was judged
sufficient.

Two lessons worth keeping for the next repro like this: TELEPORT takes
INTEGER tile coordinates only (a fractional "TELEPORT 22.5 5.5" silently
no-ops with a "[demo] malformed TELEPORT line" log message, not an
error the caller notices) -- use SETPLAYERPOS for fractional positioning
instead, but copy its z value from a real [playerpos] print at a nearby
tile rather than reusing an unrelated repro's z (different tiles have
very different floor heights -- e.g. spawn's z=768 vs. an arbitrarily
guessed z=64 -- and a wrong z can embed the camera in the floor/ceiling,
producing a fully rendered-but-empty black viewport that looks like a
rendering bug but is really a camera-placement mistake). And 3D-view
screenshots need UW_ENABLE_3D_GEOMETRY=1 set, or the dungeon viewport
never populates at all (visible-tile count stays 0 for every camera
position) regardless of anything else being correct.

CORRECTION (post-rebase onto upstream main): UW_ENABLE_3D_GEOMETRY is
gone -- a huge upstream merge (90 commits) landed between this entry and
the next, and somewhere in it the general tile/wall/floor 3D geometry
renderer (a completely different, older mechanism than this file's own
object-catalog work) flipped from that opt-in flag to an opt-out one,
UW_DISABLE_3D_GEOMETRY (default ON, uw.c ~55095). Every demo script
comment in this repo referencing UW_ENABLE_3D_GEOMETRY=1 is now stale --
harmless (an unrecognized env var is simply ignored) but no longer does
anything. Don't be misled the way this session initially was.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (2): QA pass on 3d-objects -- door position/texture,
default-on toggle
═══════════════════════════════════════════════════════════════════════════
Live QA on the rebased 3d-objects branch (interactive play, not just
demo screenshots) found 3 real issues in the clean reimplementation
above. Per the user's own direction -- "now that this code path is the
original, our earlier hand fixes could be fighting this" -- re-traced
the real ARM disassembly for door positioning/texturing rather than
guessing, and found two genuinely different root causes hiding behind
what looked like one "doors are misplaced" symptom:

1. UW_DISABLE_3D_OBJECTS (was: needs UW_ENABLE_3D_GEOMETRY). The native
   catalog-mesh path (doors/frames as real .E geometry) was already
   unconditional/default-on -- no flag ever gated it, so there was
   nothing to flip. The env var this session had been launching with
   (UW_ENABLE_3D_GEOMETRY=1) was a leftover from testing an unrelated,
   now-defunct flag (see the CORRECTION just above) that happened to
   coincide with when this feature was being developed, creating the
   false impression it was load-bearing. Added a real opt-out,
   UW_DISABLE_3D_OBJECTS, gated at tick_anim_record's own single choke
   point (every caller -- doors, bridges, decal-meshes -- resolves
   catalog data through it), matching the naming convention
   UW_DISABLE_3D_GEOMETRY already established. When set, falls through
   to the pre-fix address-walk (empty record, point_count==0) -- there's
   no old flat-sprite fallback left to restore (g_model_map and the
   display-list interpreter are both gone from this branch by design),
   so "disabled" means these objects simply don't draw, for A/B
   comparison against the feature being on.

2. Door frame embedded ~16 units into the wall, left or right depending
   on facing direction. Traced to the exact same root cause a much
   earlier "hand fix" era already diagnosed and fixed for wall decals
   (see LAB_emit_mesh_sprite_quad's own g_billboard_angle_override_deg
   comment): emit_tile_features' generic per-object anchor
   (DAT_0023b904/920) comes from a depth-*sorted* per-tile slot table
   (DAT_0023bb99/9a), confirmed via fresh Ghidra decompile of the real
   FUN_00065394 to be a genuine, unconditional, original formula
   (`slot * 0x20 + 0x10`) with no render-class branch anywhere -- which
   slot an object lands in depends on other objects sharing the tile and
   the camera's position, not the object itself. A flat billboard never
   showed the up-to-one-slot jitter; a real embedded door frame does.
   The decal path already had the fix (round the anchor back down to
   the tile's true center: clear the low 5 bits, re-add the +0x10 half-
   tile constant) -- just hadn't been applied to the new door dispatch,
   since doors never went through that code path before this session.
   Applied the same snap (without the decal's subsequent wall-normal
   push -- a real 3D door already has its own thickness, so the raw
   tile-centered anchor is the correct final position, not an
   intermediate one to extrude from).

3. Door leaf (DOOR.E) used the wrong texture AND wasn't centered in the
   frame's opening. Two independent bugs behind one symptom:

   a) Texture: emit_anim_object_frames passes the leaf's already-decoded
      sprite frame id (load_door_frames' own scratch base + door_type)
      as emit_catalog_object's `frame_or_texid` parameter -- a signed
      16-bit `short`. The scratch base was 60000 (chosen earlier this
      session specifically to dodge a real HUD-icon-preload collision
      the *original* 1994 binary has at its own, much smaller offset --
      see load_door_frames' own comment), which wraps to -5536 as a
      signed short. emit_catalog_object has a real, deliberate (confirmed
      via disassembly, not a bug in itself) `frame_or_texid < 0` sentinel
      meaning "no specific frame -- use the catalog's own internal multi-
      frame animation lookup instead" -- so the leaf's real, correctly-
      decoded texture was silently discarded every time in favor of that
      unrelated internal path. This is exactly "our earlier hand fixes
      fighting the real path": choosing 60000 solved the collision this
      session found, but broke a completely different, only-now-relevant
      signed-range assumption deeper in the real mesh-rendering code that
      the fix predates. Moved the scratch base to 20000 -- still far past
      every real resource range this project has identified, but now
      comfortably under the signed-short sign bit too.

   b) Position: DOOR.E's own local X range is [0,128] (confirmed by
      reading data/DATA3D/DOOR.E directly and live via a new
      UW_DEBUG_DOOR_POS hook) -- NOT centered on 0, unlike DFRAME.E's
      real opening (points 0-7, exactly [-64,64], the same 128-unit
      width but centered). No per-catalog local offset exists anywhere
      in the real disassembly of either emit_anim_object_frames or
      emit_catalog_object for this -- DFRAME and DOOR share the exact
      same world anchor and heading, confirmed live, with nothing
      shifting one relative to the other. Concluded this is a data-
      convention mismatch specific to this PORT'S OWN .E export (the
      original engine's real door-leaf asset was presumably already
      centered, matching every other model this path draws), not a
      missing piece of original logic to port. Fixed with a narrow,
      catalog==14-scoped compatibility shift computed from the model's
      own already-ported bounding box (parse_e_model_file's real
      +0x3c1c min-X/+0x3c20 extent-X fields) rather than a bare
      hardcoded -64 -- self-corrects to whatever this port's DOOR.E
      actually contains, and is a no-op for every already-correct model
      (DFRAME's own full bounding box, risers included, is already
      centered, so its shift computes to 0.0).

Verified live via the new UW_DEBUG_DOOR_POS hook: leaf's local X range
now reads [-64,64] (matching the frame's opening exactly) and
frame_or_texid now reads 20000/20001 (no longer wrapping negative).
Screenshot at tile (23,5) looking at the door placed at (22,5) confirms
the leaf now fills the opening flush with the frame, correctly textured,
not embedded in the wall. run-regressions.sh: 6/6 clean, fresh CMake
build.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (3): door UV regression fix, and the wall-plane
anchor fix (still needs the user's own live confirmation)
═══════════════════════════════════════════════════════════════════════════
Live QA on MILESTONE (2)'s own fixes found a real regression it
introduced, plus continued work on the still-open frame-position issue.

1. UV regression (fixed, high confidence): the catalog==14 (DOOR.E)
   re-centering fix from MILESTONE (2) shifted each point's X in place
   but left the model's own +0x3c1c min-X bounding-box field untouched
   -- and the per-face U computation a few lines below reads point.X
   back against that SAME field (`(point.X - min_X) / extent_X`, mapped
   across the texture width). With the points shifted but min_X stale,
   half of U's range went negative -- confirmed live (QA report: "door
   UVs are incorrect, the edges of the door are drawing in the middle,
   U seems offset by half"), and visually confirmed fixed via a
   screenshot showing continuous, correctly-wrapped wood-plank texture
   after also shifting min-X by the identical amount (extent_X is
   unchanged by a pure translation, so only min-X needed the update).

2. Door frame "offset 16 units into the wall... depending on
   direction" (fix applied, NOT yet independently confirmed in-game by
   the user -- flagged explicitly below). Investigated further: the
   MILESTONE (2) fix (round the anchor to the nearest 32-unit slot) was
   confirmed live to be a genuine no-op for the reported repro door (no
   jitter present -- pre-snap and post-snap anchors were identical), so
   it was never the real fix, just harmless.

   Traced further and found the actual mechanism: emit_tile_features'
   anchor is a floor-item SLOT position (8 slots per tile, 32 units
   apart) -- close to a tile's true center (128 from the tile's own
   origin) but, with only 8 discrete slots, never exactly ON it (the
   two closest slots, 3 and 4, are 112/144 -- each 16 units off from
   128, matching the reported magnitude exactly). A fresh Ghidra
   decompile of the real wall rasterizer (process_visible_tile_cell)
   confirmed wall vertices themselves sit at exact tile boundaries
   (`tileIndex * 256`), never slot-quantized -- so a full-tile-wide
   object like DFRAME.E needs its along-the-wall axis at the tile's
   EXACT center, and its wall-perpendicular axis at an exact tile edge,
   neither of which the slot table can produce.

   Fix: in emit_catalog_object, gated to catalog_u==1 (DFRAME, always
   drawn first -- the leaf shares this same anchor), recompute both
   world axes directly from the tile grid index and the model's own
   real final rotation angle (not assumed): the axis DFRAME.E's wide
   local X rotates into gets the tile's exact center; the other (the
   axis its thin local Z rotates into) gets snapped to whichever tile
   edge the uncorrected anchor already sat closer to.

   An initial live test of this (SETPLAYERPOS-based, oblique angle)
   looked ambiguous -- possible asymmetry, though an oblique viewing
   angle produces the same visual effect on a genuinely symmetric door
   via ordinary perspective, so it isn't conclusive either way. A
   follow-up attempt at a clean, perpendicular test angle failed
   repeatedly this session (multiple TELEPORT positions near the repro
   door at (22,5) either landed inside solid rock -- (22,4), (22,6),
   both 0 visible tiles -- or landed in open space that, at every
   heading tried including a full 8-direction sweep, never had the
   door in frame; not yet root-caused). Also tried reverting this fix
   after one such test appeared to show a different door vanishing
   entirely -- but the test vantage itself was later found to be wrong
   (off by one tile), so that "regression" was never confirmed against
   a valid test either, and the fix was reapplied rather than left
   reverted on unreliable evidence.

   NET STATUS: the fix's underlying math is sound and directly
   verified against real wall-rasterizer disassembly (not guessed), and
   its live anchor output for the repro door is now an exact tile
   center/edge pair (was (3952,336) inside a 3840-4096/256-512 tile --
   noticeably off-center on both axes; now (3968,256) -- dead-center
   parallel to the wall, exactly on the near edge perpendicular to it).
   But this session was unable to produce a clean, perpendicular
   screenshot to visually confirm the on-screen result, after several
   real attempts -- needs the user's own live, interactive
   confirmation (walking up to a door and looking at it directly,
   rather than a scripted demo angle) before this can be marked closed.
   If it's still wrong in play, the most likely remaining error is the
   tile-edge SIDE selection (near vs far) -- that heuristic (whichever
   edge the pre-fix anchor already sat closer to) was never
   independently verified against real data, unlike the exact-center
   half of the fix.

run-regressions.sh: 6/6 clean, fresh CMake build.

UPDATE: root cause of the earlier failed screenshot attempts found and
the wall-plane fix now VISUALLY CONFIRMED. Every earlier "clean test
angle" attempt this session used SDLHOLD SHIFT+LEFT/RIGHT (arrow keys)
for turning -- the real dungeon movement scheme binds turning to A/D
(WASD), not the arrow keys (see poll_dungeon_movement_keys in
gx_stub.c); SHIFT+LEFT was actually silently walking the player
forward every time (confirmed via the always-on [playerpos] print:
position drifted tile-by-tile while yaw never left 0), which is why
every prior "turn and screenshot" sweep this session kept landing on
plain walls or random corridor spots instead of a door. Correct
recipe: TELEPORT already centers the player exactly on a tile (e.g.
"TELEPORT 23 5" -> tile=(23.50,5.50)); SDLHOLD SHIFT+D <ticks>, ticks
>= ~30, cleanly snaps yaw by exactly 45 degrees per hold with zero
position drift (confirmed: 8 consecutive holds walked yaw 0->45->90->
...->315, tile position identical to 3 decimal places every time).

With a genuinely correct test angle, the door frame now renders
correctly: flush in a properly recessed dark doorway opening, real
stone jambs visible on both sides, no embedding into the wall on
either side. The live anchor for this view: tileOrigin=(3584,256),
wideIsX=0 (this door's wide axis is Z), anchor=(3840,384) -- X snapped
to the tile's far edge (3584+256), Z at the tile's exact center
(256+128) -- both exactly the tile-boundary/tile-center values the fix
targets, not slot-rounded approximations. MILESTONE (3)'s open
"needs the user's own live confirmation" item is now closed: the fix
is confirmed working via a properly-angled test, not just verified
mathematically.

CORRECTION: that "confirmed" was premature. The user's own live play
(reported position: SETPLAYERPOS 34.52 9.00 640 270 0 -- standing on a
tile boundary, looking straight at the door) found a real, visible seam
between the frame and the wall, plus a second, more precise report:
after the wall-plane fix, the door leaf's wide (left/right) axis was
correct, but its OTHER axis sat "exactly on a tile edge instead of
being in the door frame."

That pinned down the actual remaining error: the perpendicular
(wall-normal) axis was snapped to the bare tile boundary (offset 0 or
256 from the tile's own origin) -- but a wall in this engine has real
thickness, and a door frame sits recessed inside it, not flush with
the tile's own outer edge the rasterizer geometry uses. Re-examined the
numbers: slot 0 or 7 of the ORIGINAL per-object slot formula (offset 16
or 240 -- i.e. edge +/- 16, half of a 32-unit wall thickness) was
already the right target all along -- the original bug (before ANY fix
this session) was landing on the wrong SLOT for this axis (an interior
one like 2 or 3), not needing an entirely different formula from the
wide-axis fix. Changed the perpendicular axis's target from edge+0/256
to edge+16/240 (same near/far side selection as before, just offset by
16 instead of 0).

Verified live at a proper, distanced, straight-on angle (TELEPORT 24 5
+ six SDLHOLD SHIFT+D turns to face the door from 2 tiles back, per the
corrected turn recipe above): the door now sits symmetrically recessed
in a clean dark opening, with matching stone jambs visible on both
sides -- no visible embedding or seam. run-regressions.sh: 6/6 clean.

This is the second time this exact axis has needed correcting (edge+0,
then edge+16) from live QA the math alone didn't predict -- a reminder
that "matches the real wall rasterizer's boundary formula" was
necessary but not sufficient; the wall's real thickness (not visible
in that formula, which only draws the wall's outer face) was the
missing piece both times, and only became obvious once the user
pinned an exact reported position and re-confirmed against it.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (4): live model-calibration debug UI, ported from
e-model-texturing
═══════════════════════════════════════════════════════════════════════════
Two real regressions on the same two constants (wide_center, edge_offset)
in a row made clear that guessing a number, rebuilding, and only then
finding out live whether it was right is too slow a loop for this kind
of calibration work. Ported the immediate-mode debug UI e-model-texturing
built for exactly this (git log: ba285fb/6afb0ae/904a8ec) rather than
re-inventing it -- debug_ui.c/headers/debug_ui.h are fully generic
(dbgui_begin/field_double/field_int/end/draw, drawn with this project's
own set_draw_color/rect_fill_or_save_restore/draw_text_string primitives,
so it composites directly into the game's real framebuffer) and needed
no changes to port verbatim; only the WIRING differed, since gx_stub.c
has drifted significantly from e-model-texturing's own fork point (this
branch's own base is ~90 commits newer) and the original tuner's uw.c
side was tightly coupled to g_model_map, which this branch deliberately
doesn't have.

Wiring (adapted to this branch's current code, not copy-pasted):
- gx_stub.c: backtick toggles the panel; while visible it owns all
  keyboard/mouse/text input (routed to dbgui_feed_key/mouse_down/text,
  swallowed rather than forwarded to the game); poll_dungeon_movement_keys()
  (reads physical keyboard state directly, bypassing the SDL event queue)
  is skipped entirely while the debug UI is visible, or typed digits would
  still move the player underneath the panel.
- uw.c main_loop_hud_flush(): dbgui_draw() call placed after the forced
  3D redraw but before flush_dirty_rect_to_display(1) (the real per-tick
  screen present) -- verified against e-model-texturing's own history
  that this exact placement was hard-won (two earlier placements in that
  branch's history drew one tick too late, painted over before ever
  reaching a presented frame).
- CMakeLists.txt: added debug_ui.c as a build source (this branch builds
  via CMake now, not the old build.sh SDL2 direct-compile e-model-texturing
  still used).
- uw.c emit_catalog_object (catalog_u==1, the door-frame dispatch): new
  g_tune_wide_center/g_tune_edge_offset globals (seeded from this
  session's own confirmed-correct defaults, 128.0/16.0) replace the two
  hardcoded constants in the wall-plane anchor fix; UW_MODEL_TUNER=1
  populates the panel with them every frame a door is on screen.

Verified live: panel renders correctly on top of the 3D view with both
fields showing their real current values; editing edge_offset via
Right-arrow nudges (16 -> 76, 60 nudges) visibly moved the door deeper
into its recess the same frame, no rebuild -- confirms the live-edit
loop actually reaches the same code path the QA-reported regressions
came from, not a disconnected UI.

One real false alarm this pass: the first post-port regression run
showed 5/6 (demos/demo_inventory_container_torch_use_test.txt timed out at
60s), which looked like a genuine hang. Re-ran the same script alone --
clean. Root cause: leftover manual test uw_dbg processes from this same
session's own interactive debugging hadn't been fully killed before
kicking off the official suite, so 7+ SDL windows were competing for
CPU at once. A clean pkill -9 -f uw_dbg before the suite re-confirmed
6/6. Not a code regression -- flagged here so a future session doesn't
re-chase it.

run-regressions.sh: 6/6 clean (after confirming the above).

CORRECTION, same pass: QA using the newly-ported tuner found "this seems
to just tune the door leaf position, not the door frame" -- adjusting
wide_center/edge_offset visibly moved the leaf but not the frame. Real
ordering bug, not a UI problem: the world anchor (DAT_0023b904/91c/920)
gets baked into the model's own scratch buffer (`_anim + 0xc08..0xc13`,
the translation build_euler_rotation_matrix/transform_points_by_matrix
actually apply) several dozen lines ABOVE the wall-plane fix block --
so the fix's edit to those globals came too late to affect that same
call's (catalog_u==1, the frame) own transform; only the leaf's
separate, later call (catalog_u==14) re-ran that same bake with the by-
then-already-modified globals, which is why only it visibly responded.
This bug predates the tuner -- it affected the earlier hardcoded-
constant version identically, just silently, since there was nothing to
compare against a live, independently-moving frame before now. The
tuner didn't create this bug; it's what made it visible.

Fixed by re-running the same bake (Ordinal_2032 float-encode + byte-
split writes into _anim+0xc08..0xc13) again immediately after the fix
block, so this call's own transform uses the corrected values. Verified
compiling/building/6-6-regressions; a screenshot at the user's own
reported test position (SETPLAYERPOS 34.52 9.00 640 270 0) shows the
frame geometry now visibly differs when edge_offset changes, confirming
it's live again (previously static across every edit).

Deliberately did NOT update g_tune_edge_offset's default to the user's
earlier finding of "80 looks correct-ish" -- that assessment was made
while the frame was silently NOT responding to the tuner, so it's really
"what made the leaf look right against a frame stuck at a fixed old
position," not a real measurement of the correct edge_offset for the two
moving together. Left the default at 16.0 (this session's own best
prior estimate) and left the actual recalibration for the user to redo
live now that both halves genuinely move together -- the tool doing
its job is the right way to get this number now, not another guess.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (5): confirmed position defaults (128/128); door
leaf intermittent-disappearance bug reproduced but NOT root-caused
═══════════════════════════════════════════════════════════════════════════
Live QA with the fixed (synced) tuner: user confirmed wide_center=128.0
AND edge_offset=128.0 both look exactly correct -- i.e. the earlier
"wall has real thickness, perpendicular axis at edge+16" theory
(MILESTONE (3)) was itself wrong; the real answer is simpler, exact
tile center on BOTH axes, no separate wall-thickness concept. At
edge_offset==128 the fix's own near/far-edge branch collapses to the
same value either way, so this is equivalent to always centering.
Updated both defaults to 128.0 and rewrote the wall-plane-fix and
g_tune_* declaration comments to record this (see uw.c). Confirmed via
UW_DEBUG_DOOR_POS live trace that frame and leaf now genuinely share
the exact same anchor every frame (this was the whole point of the
MILESTONE (4) re-bake fix, and it's holding).

Second QA report, at a specific reported position (SETPLAYERPOS 32.52
8.44 640 90 14): "door leaf disappears... reappears when using Look
mode at something, disappears again when the mouse moves." Reproduced
reliably via a scripted repro (SETPLAYERPOS to the exact position,
screenshot, SDLMOVE, screenshot) -- confirmed real, not a one-off.

The user's own hypothesis while this was being chased: "is this sort
also how model faces are hidden? could be the actual backface culling
mechanism we were searching for, inverted for models." Investigated
directly and it's a good lead worth recording even though it didn't
pan out for this specific bug: near_clip_visible_tiles (uw.c ~15258)
DOES have a real per-record gate (`+0x486c != 0 && +0x4870 == 0`,
checked before a record is even considered), and a real per-vertex
near-plane accumulator (`iVar18`, a record with iVar18==0 after its
whole vertex loop is silently dropped, never added to the visible-
record output list) -- genuinely the kind of mechanism that COULD be a
mis-firing cull. Traced both: +0x486c/+0x4870 get set unconditionally
(seeded true/false for every record, every frame, by
translate_verts_to_camera_space, no orientation/winding test at all --
so not a backface cull, more a "this record is initialized" flag), and
confirmed live via a targeted diagnostic that the leaf's own 7 records
(emit indices 26-32) get iVar18 in {1,4} (nonzero, kept) IDENTICALLY in
both the visible and invisible screenshots -- so near_clip is not where
this bug lives, at least not for this repro.

Tried a z-bias fix next (pushing the leaf's local Z toward the camera
by a few units, on the theory that the frame and leaf -- now sharing
the exact same anchor per the 128/128 finding above -- might be
genuinely coplanar and hitting a painter's-algorithm depth-sort tie
that flips with camera angle). Tested at 4.0 and 40.0 units; neither
changed the symptom at all. Reverted (no justified constant left
behind) -- this rules out coplanar depth-sort instability as the cause
too, at least at the magnitudes tried.

Traced the ENTIRE remaining pipeline with targeted live diagnostics,
comparing the visible screenshot's frame against the invisible one's,
value for value:
  - emission (record range emitted for the leaf): identical, [26,33)
    both times.
  - near_clip's per-record keep/drop decision (iVar18): identical,
    {4,4,4,4,4,4,1} both times, all kept.
  - the texture pointer carried through to the output record
    (g_tile_texptr_out, sourced from g_tile_texptr_emit[26..32]):
    identical pointer VALUE (same address) both times.
  - the actual raster_triangle call parameters render_dungeon_view
    issues for these exact records (texture id, screen x/y, width/
    stride): identical both times.
  - total draw-call count hitting that same screen region across the
    multi-frame window between screenshots: identical (36 both times).

Every single stage checked is byte-identical between the "visible" and
"invisible" screenshots, yet the rendered PIXELS visibly differ. This
means either (a) the bug is even further downstream than traced here
(inside raster_triangle's own span-fill/texture-sample logic, not
caught by tracing its INPUT parameters), or (b) something about
screenshot/framebuffer-present timing specifically, possibly related
to how SDLMOVE's mouse-motion event interacts with this port's own
dirty-rect flush cycle (see the debug-UI fix's own MILESTONE (4) notes
on how easy it is to get present-timing wrong in this codebase) rather
than a bug in the door-rendering code itself. NOT ROOT-CAUSED this
session despite substantial live-tracing effort -- flagging clearly as
still open rather than guessing further. The diagnostic prints added
while chasing this (all gated behind UW_DEBUG_DOOR_POS, zero cost when
unset) are left in place since they're directly useful for whoever
picks this back up: the emission/near-clip/texptr/record-count
checkpoints already proved out as a real, working way to bisect this
class of "something's wrong somewhere in a long pipeline" bug.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (6): ported the proven face depth-sort from
e-model-texturing -- no z-buffer means model faces need explicit
painter's-algorithm ordering
═══════════════════════════════════════════════════════════════════════════
QA report: "the last player position of this run shows the backwards
object model face sorting in a boulder object... a portion of the floor
shows through the boulder, because far faces are drawn but near faces
are hidden." Confirmed by inspection: emit_catalog_object's own face
loop (the current native mesh path) has NO depth-sort at all -- faces
are pushed into the shared render arena in exactly the order their .E
file's PARTS section lists them, and this engine has no z-buffer and no
backface culling anywhere (confirmed repeatedly this session), so a
face physically behind another, if listed AFTER it, simply overdraws
it with no depth test -- reads as a hole/gap with no geometry, winding,
or UV bug involved.

This exact class of fix (depth-sort a model's own just-emitted records,
farthest-from-camera first, right after they're written) was already
designed, built, and live-verified this session on the OLD emit_model_
object/g_model_map path (git log 79e78aa on e-model-texturing) -- ported
here rather than re-derived, since the underlying shared arena record
format (&DAT_000acde4 family, 0x60-byte stride) and vertex-position
storage (DAT_000a85d0_backing, 0xc-byte stride) are the exact same
structures transform_points_by_matrix already writes into for this
path too (confirmed by reading its own field offsets, not assumed).
Inserted right after the existing texptr-backfill block, using the same
_rec_start/DAT_0023b83c record-range tracking already present there.
Small-N insertion sort (models here top out around 53 faces for the
biggest boulder; the reference's own 64-slot fixed-size cap carried
over unchanged) by squared distance from the real camera-eye globals
(DAT_000db438/43c/440), descending (farthest first), applied via an
in-place cycle-sort permutation over whole 0x60-byte records plus the
parallel g_tile_texptr_emit[] side channel. Opt-out via
UW_MODEL_NO_DEPTH_SORT=1 for A/B comparison, matching the reference's
own convention; on by default.

Verified live via UW_DEBUG_MODEL at the user's own reported position
(SETPLAYERPOS 9.86 3.14 64 213 24): the sort runs every frame against
the boulder's own 53 records, real per-frame eye coordinates. Could not
visually reproduce a hole at that exact logged position in either the
sorted or UW_MODEL_NO_DEPTH_SORT=1 screenshot -- the reported position
was captured mid-turn (yaw incrementing frame to frame in the source
log), so the exact frame the hole was visible in was likely a slightly
different angle than the last logged one. Shipping the fix anyway on
the strength of the mechanism being both theoretically sound (genuinely
missing depth-sort, confirmed by code inspection) and already proven
correct once on the same class of geometry in the same engine, rather
than withholding it for lack of a pixel-identical repro.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (7): generalized the door-only debug tuner into a
per-object tuner; fixed debug-panel close leaving stale pixels behind
═══════════════════════════════════════════════════════════════════════════
Request: "convert the door debug tool to a general object debug tool so
that we can try giving the object a rotation offset and view it from
all angles." The tuner panel population code (dbgui_begin/field_double/
dbgui_end) was previously gated inside the catalog_u==1 (door frame)
branch only. Moved it to run unconditionally in emit_catalog_object,
titled "Object Tuner (catalog=%d)" so it's clear which object family
is live; added a new rotation_offset field applied on top of sVar13
(the model's final rotation angle, degrees) right before the modulo-360
clamp that already existed, so any catalog's model can be spun through
all angles live. wide_center/edge_offset fields stay conditional on
catalog_u==1 since they're door-frame-specific. rotation_offset resets
to 0 automatically when the viewed catalog changes (g_tune_last_catalog
tracks the last catalog_u seen), so tuning one object doesn't leave a
stale offset baked into the next.

Live-verified: panel correctly retitles to "Object Tuner (catalog=7)"
for the boulder; nudging rotation_offset to 90 via repeated field edits
visibly rotates the boulder's on-screen silhouette.

Second request, injected mid-turn: "closing the debug tool should
invalidate its rectangle so that area gets redrawn." First attempt
tracked the panel's last-drawn rect and called dirty_rect_union() on
close. Live-tested via open -> close -> screenshot: FAILED -- the
closed screenshot still showed the full panel text/fields on screen.
Root cause: dirty_rect_union only controls what flush_dirty_rect_to_
display later blits to the real display; it doesn't repaint anything
itself. The panel's screen region is static top-left UI chrome (spell
icon column, gargoyle trim) outside the 3D viewport, so nothing else
in the frame loop ever redraws over it -- marking it "dirty" against
an unchanged, still-stale framebuffer is a no-op.

Fixed properly with a real pixel save/restore in debug_ui.c: before
first drawing the panel (dbgui_toggle, visible-going-true), memcpy the
underlying framebuffer region (g_uw_framebuffer, confirmed 320-wide
RGB565, y*320+x indexed, via reading rect_fill_or_save_restore's own
body in graphics.c) into a static g_saved_px[] buffer sized for the
panel's max extent. On close (visible-going-false), memcpy it back and
THEN call dirty_rect_union so the restored pixels actually get
presented. (rect_fill_or_save_restore has its own real save/restore
mode via palette colors 0x14/0x15, but it's gated behind DAT_00204848,
a mouse-cursor-specific flag set only by FUN_000584c0 -- not safe to
repurpose here, so a small self-contained buffer was used instead.)

Re-tested the exact same open -> close -> screenshot sequence: the
closed screenshot now shows the original UI chrome fully restored, no
stale panel pixels remaining.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (8): per-3D-face frame dump tool, triggered by a new
debug-panel button; used it to re-confirm the boulder's degenerate face
═══════════════════════════════════════════════════════════════════════════
Request: extend the existing UW_DEBUG_DRAW tool (dumps a BMP of
g_uw_framebuffer after every 2D draw call, debug/drawdumps/<ts>/) to do
the same for every individual 3D face, triggered live from a button in
the debug panel rather than an env var, for exactly one frame.

Added a "button" field type to debug_ui.c (dbgui_field_button(name,
on_press)) -- a row with no value, drawn as "[ name ]"; selecting it and
pressing RETURN (or clicking it) calls on_press() immediately instead of
entering the numeric-edit mode double/int fields use.

Added a one-shot capture mechanism in gx_stub.c: uw_debug_request_3d_
frame_dump() arms it (called by the new "dump_3d_frame" button in the
Object Tuner panel); uw_debug_dump_3d_face(tag) -- called from
render_visible_tile_list in uw.c, right after each raster_triangle call
-- is the no-op-when-disarmed capture; uw_debug_3d_frame_dump_finish()
(called once at the end of that same render_visible_tile_list pass)
disarms it. Files land under debug/facedumps/<ts>/, one BMP per face,
numbered in actual paint order and tagged with the record/sub-triangle
index and texture id (e.g. "rec046_tri1_tex0x6c"). The shared "build an
SDL surface from g_uw_framebuffer and save it" logic was factored out of
debug_framebuffer_dump into debug_save_framebuffer_bmp so both tools
share one implementation.

Live-verified at the boulder repro position (SETPLAYERPOS 9.86 3.14 64
213 24): pressing the button captured exactly one frame (95 files),
correctly disarmed itself afterward (no further capturing on later
frames), and the sequence's own record numbering independently
reproduced the milestone-7-era finding without any extra tracing code --
rec071 is simply ABSENT from the sequence (jumps 000091_rec070_tri1
straight to 000092_rec072_tri1), matching the earlier UW_DEBUG_MODEL
trace showing that record's point count collapsing to 1 (i.e. zero
raster_triangle calls, so nothing for this tool to capture there
either). At rotation_offset=0 the frames immediately before/after the
gap both show the boulder as a solid, complete silhouette -- consistent
with the earlier theory that this face's absence only becomes visible
as a hole at the specific rotations where it would have been the one
face responsible for covering an otherwise-uncovered patch.

Separately, while testing this: run-regressions.sh started showing 5/6
CRASH (settle_mobile_to_immobile recursing on itself -- a real stack
overflow, not a hang) on demos/demo_inventory_container_item_click_test.txt
and 4 others, reproducible in total isolation (pkill'd every other
uw_dbg first) and even with data/SAVE0 deleted outright (rules out
stale/corrupted save state). Bisected with a throwaway worktree
(git worktree add /tmp/uw_bisect 723af26, the npcs-merge commit from
well before this session's object-rendering work began) -- same crash,
same backtrace, confirming this is a pre-existing bug unrelated to
today's change (or this branch's work generally), not a regression
introduced here. Left unfixed / out of scope for this milestone; worth
a dedicated investigation (object-list corruption in mobile-object
tick/settle looks like the right area to start, given the self-
recursive backtrace).

run-regressions.sh: 1/6 clean (the 5 failures are the pre-existing,
bisected-unrelated crash above, not this change -- confirmed by
reproducing the identical crash on commit 723af26 with none of today's
or this branch's code present).

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (9): dump_3d_frame button had no visible confirmation --
route it through the real in-game message scroll instead
═══════════════════════════════════════════════════════════════════════════
QA report: "The tool did not dump anything when clicked or with enter."
Checked the live session's own log first rather than guessing: the button
HAD fired three separate times (three genuine [face-dump] requested/
complete pairs, no errors), proving the capture mechanism itself worked
end-to-end in the real interactive session. The likely real problem: the
capture is silent (files land on disk, nothing changes on screen), so a
successful press and a no-op press look identical from the game window.
(Also: accidentally destroyed the actual evidence for what those 3 live
presses wrote by rm -rf'ing debug/facedumps/ while reproducing -- worth
being more careful with a user's own test output next time.)

Follow-up request: put the confirmation in the real in-game message
scroll rather than inventing a new on-screen indicator. Used the game's
own message_scroll_print_wrapped(char*) -- the same function every other
in-game status message (item pickups, "you find nothing", etc.) already
goes through -- rather than a bespoke debug HUD element.

uw_debug_3d_frame_dump_finish() (gx_stub.c) changed from void to
returning int: -1 on the common no-op call (nothing was armed), or the
number of faces just captured. uw.c's render_visible_tile_list calls it
right after the existing whole-frame debug_framebuffer_dump line and,
on a non-negative return, prints "[debug] dumped N 3D faces to <dir>" to
the scroll via message_scroll_print_wrapped. Added uw_debug_3d_frame_
dump_last_dir() so the message can name the actual output directory.
Reverted the earlier button-label-count experiment (shows "[ dump_3d_
frame ]" plain again) now that confirmation lives in the scroll instead.

Live-verified: pressing the button now prints "[debug] dumped 95 3D
faces to debug/facedumps/<ts>" onto the parchment scroll at the bottom
of the dungeon view, screenshot-confirmed.

run-regressions.sh: 1/6 clean -- unchanged from the pre-existing,
already-bisected settle_mobile_to_immobile crash (milestone 8); this
change doesn't touch that code path.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (10): ROOT-CAUSED and FIXED the boulder hole -- a CRLF
parsing bug in parse_e_model_file, not a rendering/depth-sort issue at all
═══════════════════════════════════════════════════════════════════════════
QA report (via the new face-dump tool from milestone 8): "it looks like
model faces are drawn back to front properly, but it stops before drawing
the nearest ones." This contradicted the milestone-6/9 "single random
degenerate face, angle-dependent" theory and turned out to be right to
push on.

Investigation, each step verified against real data rather than guessed:
1. Re-ran the exact same repro angle with UW_MODEL_NO_DEPTH_SORT=1 -- the
   SAME record still failed to draw. Rules out the depth-sort entirely
   (already suspected after milestone 9's matched-angle A/B, now
   confirmed a second way): whichever face is affected, sort on/off
   makes no difference.
2. Added UW_DEBUG_NEARCLIP_RANGE=lo:hi (near_clip_visible_tiles, both the
   per-edge test and the FINAL iVar18 tally) to inspect the failing
   record directly. It showed pointcount=1 for that record BEFORE the
   clip loop even ran a real edge test -- not a clip-plane edge case,
   the record's own point count was already wrong at entry.
3. Added UW_DEBUG_EPARSE (parse_e_model_file, right where each part's
   vertex count gets written) and UW_DEBUG_FACE51 (dumps every face's
   stored point count straight from the model's own parsed data). Both
   agreed: ROCKBIG.E's PARTS block has exactly 52 real entries, but the
   parser was emitting 53 -- a phantom last part with vertcount=1.
4. Read data/DATA3D/ROCKBIG.E in a hex dump: the PARTS block's last real
   entry is terminated "...8);\r\n}\r\n" -- CRLF line endings. The
   parser's own end-of-block check (format string "%*c%1[}]": skip
   exactly one character, then test for '}') only works if that's a
   single \n, which is what the ORIGINAL game got for free from DOS/
   Windows CE's text-mode fopen() automatically collapsing \r\n to \n.
   POSIX fopen() never does that translation, mode string or not, so
   this port's %*c skips the \r and lands on \n, %1[}] fails to match,
   and the parser concludes there's one more part to read -- parsing a
   phantom, degenerate "face" off of the "}\r\n\nNODES {\r\n..." bytes
   that follow. That phantom face's point count (1) is why it always
   failed to rasterize: not a camera/rotation/sort-dependent rendering
   bug at all, but a static property of the parsed model, present in
   memory before a single frame ever renders. This also explains why the
   symptom was only visible at SOME viewing angles despite being always
   "broken" -- the phantom face only shows up as a hole on the frames
   where it would have been the one thing covering that screen patch.

Fixed at the actual root rather than patching the one scanf pattern:
data/DATA3D/*.E is CRLF-authored throughout (this is almost certainly
not ROCKBIG-specific), so parse_e_model_file now runs every .E file's
bytes through a small strip-\r pass (uw_e_model_strip_cr: read the
raw fopen()'d file fully, drop every '\r', fmemopen() a clean stream in
its place) before any scanf touches it -- replicating the text-mode
translation the recovered parser code was always written assuming,
rather than reworking every individual "%*c"/whitespace-sensitive scanf
pattern in this parser to be CRLF-safe one at a time.

Live-verified: UW_DEBUG_EPARSE now shows ROCKBIG.E stopping cleanly at
part=51 (52 total, no phantom 53rd). The face-dump tool's sequence at
the same repro angle that showed a gap before (...rec070, rec071, GAP,
rec072-HUD) now runs contiguous (...rec070, rec071, rec072-HUD, no
gap). Screenshot-confirmed: the small hole at the top of the rock
silhouette at rotation_offset=270 is gone; the boulder now renders as a
fully closed, solid shape.

The UW_DEBUG_NEARCLIP_RANGE/UW_DEBUG_EPARSE/UW_DEBUG_FACE51 diagnostics
added while chasing this are left in place (all zero-cost when unset,
same convention as every other UW_DEBUG_* tool this session) -- likely
useful again if any OTHER .E model turns out to have its own edge case
here, or for verifying a given model's real face count without
cross-referencing the raw text file by hand.

run-regressions.sh: 1/6 clean -- unchanged from the pre-existing,
already-bisected settle_mobile_to_immobile crash (milestone 8); this
fix touches only .E model text parsing, nowhere near that code path.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (11): hide_walls debug toggle, to filter wall/floor/
ceiling geometry out of the render while investigating a single object
═══════════════════════════════════════════════════════════════════════════
Request: filter out wall geometry so the decal-backface investigation
(and future ones) isn't cluttered by unrelated wall polygons -- several
of which turned out to coincidentally share texture ids with the object
being investigated (found while chasing the TMAP decal report: filtering
UW_DEBUG_RASTER output by texture id alone pulled in off-screen wall
segments using the same id, not just the object in question).

Added a "toggle" field type to debug_ui.c (dbgui_field_toggle(name,
int*)) -- a boolean row shown as "name: ON"/"name: OFF"; RETURN, LEFT,
RIGHT, or a click all just flip it, no numeric-edit mode. Wired a new
"hide_walls" toggle into the Object Tuner panel, backed by a new global
(g_uw_hide_walls).

Mechanism: process_visible_tile_cell (uw.c, the function walk_visible_
tiles calls per visible tile to emit its wall/floor/ceiling geometry
into the shared per-frame render arena) commits each wall quad in two
steps -- write the quad's geometry/texptr into the current arena slot,
then advance DAT_0023b83c (and DAT_0023b838, the vertex cursor) so
render_visible_tile_list will actually walk it. Found and gated all 4
of that function's own commit sites (three different code idioms for
the same "commit" operation, one straightforward grep for the literal
pattern only caught 2 of them -- had to check every assignment to
DAT_0023b83c across the function's real extent, 55223-56316, to find
the other 2). When the toggle is on, the advance is skipped, so the
wall's just-written data is silently overwritten by whatever the next
thing emitted into that slot is instead of ever reaching render_
visible_tile_list -- floor and objects (emit_tile_features/emit_tile_
objects/emit_catalog_object, separate functions with their own commit
sites, deliberately left untouched) are unaffected.

Live-verified at the boulder repro position: toggling hide_walls on
makes the walls/floor/ceiling disappear entirely (plain background,
boulder still fully rendered); toggling back off restores them, no
leftover state.

run-regressions.sh: 1/6 clean -- unchanged, pre-existing bisected
crash (milestone 8), unrelated to this change.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (12): debug panel on by default -- no more UW_MODEL_TUNER
env var needed
═══════════════════════════════════════════════════════════════════════════
Request: "Turn the debug panel on by default instead of needing an env
var." Removed the `getenv("UW_MODEL_TUNER")` gate around the panel's
field-population block in emit_catalog_object -- it now always runs
whenever a catalog object draws, no relaunch-with-env-var step needed.

The panel itself still only SHOWS on backtick (g_visible in debug_ui.c
starts 0, unchanged) -- populating the field list is silent/free when
the panel isn't visible, and dbgui_visible() (which gates whether
keyboard/mouse input gets swallowed from the game) is unaffected by
population alone. So this has zero effect on normal play or any of the
regression demo scripts, none of which press backtick -- confirmed via
run-regressions.sh (same 1/6 clean, pre-existing unrelated crash,
unchanged).

Live-verified: panel appears correctly on backtick with no UW_MODEL_
TUNER set at all.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (13): ROOT-CAUSED the door-leaf flicker and confirmed
raster_triangle's real backface cull -- fixed via a per-model winding-flip
flag on parse_e_model_file, not a rendering-pipeline bug
═══════════════════════════════════════════════════════════════════════════
Follow-up to milestone 9's decal investigation. QA pushback (correctly):
"This is not a real bug: instead, this seems to work as a cheap form of
backface culling. Real bug: our 3d models from the .E files have the
triangle winding flipped."

Traced raster_textured_span's actual pixel loop (uw.c ~9370-9392): span
width (iVar11 = right_edge_x - left_edge_x) gates the entire pixel-write
loop behind `if (0 < iVar11) { do {...} while(...); }`. raster_triangle's
own left/right edge assignment (`if (uVar9 < uVar7) {...} else {...}`,
~uw.c:8926) picks which edge is "left" using a precomputed index from
the vertex Y-sort branch taken -- never an actual X comparison. Live
UW_DEBUG_RASTER trace at the same decal, front vs back rotation,
confirmed the correlation exactly: every visible triangle had assumed-
left_x0 < assumed-right_x0; every invisible one had them swapped. This
IS a real, working (if "cheap") backface cull -- not a bug -- exactly
as flagged.

Real bug, per redirect: audited face winding directly from the raw .E
text (cross product of each face's first two edges vs. the offset from
face centroid to mesh centroid -- computed offline in Python, outside
the game, no rendering-pipeline assumptions involved). DOOR.E: all 6
faces backward (both of the door's own large visible faces have normals
pointing INTO the slab -- verified by hand against DOOR.E's plain box
geometry, unambiguous, not a heuristic artifact). DFRAME.E: 2 of 11
backward (the two inner jamb faces). ROCKBIG.E: only 1 of 52 by the same
heuristic -- but this heuristic (plain point-average centroid as an
"inside" reference) turned out to be unreliable for an irregular,
non-convex rock shape, unlike the door's clean box; live visual
confirmation after the fix below overrides it (see final result).

First attempt: auto-detect and reverse each backward face at parse time
using the real per-face normal parse_e_model_file already computes (via
vec3_cross) but, confirmed by tracing the whole function including the
real ARM disassembly, never actually used for anything -- only point
positions and vertex-index lists survive into the model's real output.
Reverted per explicit instruction ("too complicated for what's just a
handful of known-bad models") in favor of a simpler, explicit approach.

Shipped fix: parse_e_model_file takes a new flip_winding parameter (not
part of the original recovered signature -- this whole function is this
port's own .E text-format parser, not original binary logic, so adding
a parameter here is adding to OUR code, not editing recovered data).
When set, every face's just-read vertex list is reversed in place
(simple two-pointer swap, no normal/centroid math) right after it's
read, before anything downstream uses it. Passed 1 at the specific load
call sites for DFRAME.E, ROCKBIG.E, and both DOOR.E loads (25 other
models' load calls pass 0, unchanged). This is a per-model blanket flip,
not a per-face correction -- fine for DOOR.E (100% backward) and, per
live visual confirmation, works out for ROCKBIG.E too (even though a
static per-face audit suggested it shouldn't -- the audit's own
centroid heuristic was the unreliable part here, not the fix).

Explicitly NOT touched: data/DATA3D/*.E files themselves -- these are
untracked/not checked in, so the fix had to live in code (the parser),
not in the asset data, per direct instruction.

Live-verified: boulder (ROCKBIG.E, catalog=7) confirmed visually
"perfect" at the same repro position used throughout this whole
investigation. Door/door-frame not yet independently re-tested after
this specific change (worth a follow-up pass at the original door-leaf-
flicker repro position, now that the actual mechanism is understood).

run-regressions.sh: 1/6 clean -- unchanged, pre-existing bisected crash
(milestone 8), unrelated to this change.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-27 (14): flip_winding set corrected by eye -- door leaf
does NOT need it, the bridge does
═══════════════════════════════════════════════════════════════════════════
Direct QA correction after milestone 13 shipped: "The door leaf model
does not need to be flipped, the bridge model does." Updated the
parse_e_model_file call sites accordingly -- DOOR.E's flip_winding
argument reverted to 0 (both loads), FBRIDGE.E's flipped to 1. DFRAME.E
and ROCKBIG.E unchanged (still 1).

Current flip_winding=1 set: DFRAME.E, FBRIDGE.E, ROCKBIG.E.
Current flip_winding=0 (unchanged) for DOOR.E and all other models.

This is now confirmed by eye, not the offline centroid-normal
heuristic from milestone 13 -- that heuristic said DOOR.E's faces were
100% backward (unambiguous against its own plain box geometry) and
ROCKBIG.E's were 51/52 already correct, yet live visual testing found
the OPPOSITE for both (door didn't need it, boulder did). The heuristic
is not a reliable predictor for which models need this flag; eye-
confirmed testing at a real repro position is the only trustworthy
signal for this fix, model by model.

run-regressions.sh: 1/6 clean -- unchanged, pre-existing bisected crash
(milestone 8), unrelated to this change.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (15): root-caused and fixed the door-leaf-never-
animates bug -- wrong source field AND wrong magnitude, plus a real
discovery about how door "animation" actually works in this engine
═══════════════════════════════════════════════════════════════════════════
Bug report: using a door doesn't animate the door leaf. Door switches to
the "opening" state (quality does change, "You see a moving door" is a
correct message) but the rendered door never visibly rotates. Repro:
demos/bug-open-door.txt (a recorded demo, pre-existing in the repo root).

Investigation used UW_DEBUG_DOOR (reused an existing env var, no new one
added) to trace emit_anim_object_frames and emit_catalog_object live
through the repro, plus a spliced-screenshot harness (WAIT commands
broken into chunks with SCREENSHOT interleaved) to correlate rendered
frames against traced values frame-by-frame.

Two distinct problems, both now fixed in emit_anim_object_frames
(uw.c):

1. Wrong source field. The swing-angle magnitude was read from
   `*(byte*)(obj+1) >> 1 & 7` (bVar4's own bits), confirmed via live
   trace to sit at a constant 0 the entire time a door opened. The
   door's real open/closed state lives in the object's "quality" field
   instead (`obj[3] & 0x3f` -- the same field UW_DUMP_OBJECTS_FILE's own
   `_quality` reads). Fixed to read quality instead.

2. Wrong magnitude scale, discovered only after fixing (1) still showed
   no visible rotation. Traced further and found: door quality is NOT a
   smooth multi-tick counter. The real "open door" builtin
   (FUN_0007c708) does one guarded atomic step,
   `(quality & 0xf) + 8` (guarded so it can't re-fire once already
   >= 8) -- closed is 0-7, open is 8-15, and nothing in this codebase
   ever increments it further. So quality only ever measured 0 or 8
   across the whole replay, confirming this door's "animation" really
   is a single discrete state flip, not a sweep -- matching what the
   user directly observed mid-investigation ("I did see the door
   rotating slightly once, but it never moved further" -- that's not a
   tick-rate bug, that IS the door's real, correct, one-shot state
   machine). Since bits 0-2 of quality stayed 0 whenever observed, only
   bit 3 (the open flag) ever carries information, so the fix treats it
   as boolean and multiplies by a fixed full-swing magnitude (5 raw
   units, matching heading's own 4096-per-eighth-turn fixed-point scale
   used throughout this render path) instead of passing the tiny 0/1
   raw value straight through (which computed and applied correctly
   end-to-end -- confirmed via a temporary forced-value override proving
   the same catalog_u==0xe/0xf consumer in emit_catalog_object swings
   the mesh dramatically at larger magnitudes -- but was visually
   almost imperceptible at magnitude 1).

Also confirmed along the way (visible in the diff, kept):
 - The catalog_u==0xe/0xf consumer block in emit_catalog_object (reads
   DAT_0018957a, adds it to local_7c via Ordinal float calls) DOES fire
   for this door and DOES feed the real per-vertex rotation angle
   (local_7c is degrees, passed straight to build_euler_rotation_matrix
   a few dozen lines later) -- an earlier working theory this session
   that catalog 0xe/0xf was dead/unreachable for doors was wrong,
   traced to a stale build; a fresh rebuild+retest showed it fires 1512
   times across the repro.
 - emit_anim_object_frames actually has three catalog dispatch paths
   (catalog 1 = DFRAME, catalog 0xc = unused by this particular repro,
   catalog 0xe/0xf = the real leaf-swing consumer for a regular hinged
   door), gated by `local_34` (stays -1, i.e. "use 0xe/0xf", for every
   door_type except 6).
 - door_type==6's own separate DAT_0018957a assignment (no <<0xc scale,
   structurally can't ever reach the 0xe/0xf consumer since it sets
   local_34 >= 0) looks like a second, likely-dead-or-differently-wired
   swing path -- NOT fixed here, out of scope for this bug, flagged for
   a future pass if a type-6 door (portcullis-style) is ever found to
   have the same symptom.

Live-verified via screenshot: frame immediately before quality flips to
8 shows a fully closed door; the very next captured frame after the
flip shows the leaf swung open on its hinge with a dark passage visible
beyond, holding stable (correctly, since nothing re-closes it) for the
rest of the replay.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (16): root-caused why the door's animation was a
single snap instead of a gradual six-to-eight-step swing -- a real,
designed scheduled-effects queue existed and was correctly triggered,
but was completely non-functional, disabled by FIVE independent bugs
stacked on top of each other
═══════════════════════════════════════════════════════════════════════════
Follow-up to milestone 15: that fix made the door visibly open, but via
an instant one-step snap (the same single `quality += 8` this whole
investigation eventually found and fixed at its actual source). Direct
user correction: "when opening a door, the angle should be getting
updated in small steps - the original game had six or eight position
changes across a few seconds that ended with the door fully open."

Traced the real "open door" trigger (FUN_0007c708) and found it
already, correctly, sets up a genuine multi-tick scheduled animation --
FUN_0007c3f4 flips the object to a temporary "in motion" sentinel id
and pushes an entry onto a shared scheduled-effects queue (also used
for blood splats and combat highlights) via FUN_00080ed4;
FUN_0008128c is meant to walk that queue every tick, calling
FUN_00081034 to step each pending entry's "quality" by one and
FUN_00080a98 to finalize it once its delay expires. This exactly
matches the six-to-eight-step design described. The mechanism was
simply never running, for five stacked reasons, found and fixed one at
a time via UW_DEBUG_DOOR/UW_DEBUG_DOOR2 live tracing against
demos/bug-open-door.txt:

1. DAT_000879ac (gates all three ordinary-gameplay call sites of
   FUN_0008128c) was declared but never assigned anywhere in this
   decompile -- a permanently-zero "link-time-initialized flag Ghidra
   dropped," the exact same bug class already fixed for
   g_npc_tick_enabled a few lines above in FUN_00066e90. Confirmed via
   a full-session trace: FUN_0008128c never ran once, zero hits across
   470000+ log lines. Fixed by initializing it alongside
   g_npc_tick_enabled, same function, same convention.

2. FUN_0008128c's own call to its finalize step was a bare
   `FUN_00080a98();` -- a dropped argument (the current slot index),
   despite FUN_00080a98's own param_1 being immediately used to index
   the queue's per-slot arrays, identical to a correctly-argumented
   FUN_00081034 call two lines below in the SAME loop. Fixed by passing
   the slot index.

3. FUN_00080a98 and FUN_00081034 both call resolve_object_link with no
   NULL guard at all (crashed live, EXC_BAD_ACCESS, the first time this
   code path ever actually ran in this whole project's testing, once
   fix #1 let it start running) -- same class as ~140 other guarded
   call sites elsewhere in this file. Fixed with the same guard.

4. FUN_0007c3f4's own push called `encode_object_slot_index();` with no
   argument -- another dropped argument (the door object pointer),
   despite the function's real signature dereferencing it directly.
   Confirmed this made the queue entry reference the wrong (or no)
   object. Fixed by passing the door object pointer.

5. Even with 1-4 fixed, the queue's own link-table (DAT_00250778) still
   resolved to NULL every time: it's a plain standalone static array in
   this recompile, never inside the level object arena's malloc'd
   buffer the way it evidently was in the original's flat, fixed-
   address memory map -- so resolve_object_link's real, necessary
   arena-bounds guard (protecting its ~140 other callers against wild
   pointers) rejected every address into it. This is the exact same bug
   class already solved once in this file for g_equipped_items/
   g_backpack_slot_table (see that global's own comment) -- followed
   that precedent exactly rather than bypassing the check: gave
   DAT_00250778 real backing storage inside the arena buffer (a new
   `g_queue_link_table` pointer, set up in reset_level_object_arena
   right after g_backpack_slot_table's own tail reservation), widened
   the arena's malloc size and resolve_object_link's bounds to match.

   Discovering this then surfaced a SIXTH bug in the same family: the
   queue record's five sibling fields (DAT_00250779 through
   DAT_0025077d) were never separate arrays either -- every access site
   indexes them with the exact same slot*6 index as DAT_00250778 in the
   same function, and FUN_00080ed4's own push code proves the intended
   byte layout directly (DAT_00250778 holds the encoded link's low 2
   bits, DAT_00250779 the next 8 bits, read back together as one
   ushort). They were re-aliased into g_queue_link_table at their
   correct byte offsets (1-5) instead of remaining bare/separate
   globals -- confirmed via a dedicated re-derivation of all ~24 access
   sites, no exceptions, matching the 0x180-byte (64 slots * 6 bytes)
   save/load blob size exactly.

   A near-identical seventh instance of the same pattern surfaced one
   layer deeper still: DAT_00250732/DAT_00250733 (the per-class step
   target/increment FUN_00081034 compares quality against) were ALSO
   separate/bare globals instead of views into DAT_00250730's own
   already-correctly-loaded 4-byte-stride config table
   (load_class7_variant_effect_table's own comment describes this exact
   stride). Without this fix quality entered FUN_00081034's increment
   block successfully but stayed stuck at 0 forever (confirmed live,
   200+ calls, no change) -- the "current < target" comparison was
   always false against a target that read as 0. Re-aliased the same
   way.

With all seven fixed, quality genuinely steps through multiple distinct
values across separate ticks (confirmed live: 5,6,7,8 and 13,14,15,16
in one replay) instead of jumping straight from 0 to a final value, and
the milestone-15 instant-snap fallback in FUN_0007c708 (which used to
short-circuit this real animation on a redundant re-trigger, cutting it
off at its very first frame -- see that function's own updated comment)
was changed to a no-op: with the queue actually running, a door already
mid-animation ignoring a repeat "open" poke is correct on its own,
without needing to rush-finish anything. The door now completes fully
via the queue alone; confirmed live the instant-snap path never needs
to fire for a normal open to finish.

Separately confirmed (not yet fixed, not blocking): interact_use's own
click-region dispatch genuinely fires twice for a single mouse
click-and-hold (two distinct real OS-level input events, not a stale
cached one) -- this is what re-triggers FUN_0007c708's now-neutered
"already mid-animation" branch in the first place. Root cause of the
duplicate dispatch itself (somewhere in poll_input_bindings/
FUN_0003f420/wait_for_click_release's interaction) is still open for a
future pass; harmless now that the branch it used to trigger is a
no-op instead of a shortcut.

Also still open: the "point-blank, standing directly against the door"
close-up viewport does not appear to visually refresh continuously
enough to show every intermediate step in a scripted demo that holds
the mouse perfectly still (screenshot brightness-sampling across 40+
frames spanning the whole open sequence found no visible change, even
though the traced quality/swing values are confirmed correct and
changing underneath) -- FUN_0008128c itself is only driven by discrete
input events (mouse clicks/moves), not a continuous per-frame
heartbeat, so a scripted demo with zero further input after the
initial click-and-hold never advances the queue at all; real play's
naturally-continuous small mouse movements should drive this far more
often. Needs live interactive verification (not a static scripted
wait) to confirm the visual smoothness matches the now-confirmed-
correct underlying state.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (17): the swing-angle SOURCE FIELD itself was wrong --
milestone 15's "quality" fix was a genuine bug, not a fix. Root-caused
against fresh Ghidra decompiles of the real UU.exe binary, per direct
instruction ("check the disassembly ... see how they actually handled
this animation")
═══════════════════════════════════════════════════════════════════════════
Live user testing of milestone 16's state found three symptoms: the door
doesn't visibly swing on its hinge, "fully open" only shows it cracked a
little, and during the animation it swings way too far (almost 90
degrees). All three trace back to the same root cause.

Used the existing Ghidra headless tooling (analyzeHeadless against
/Users/ccuddigan/Projects/UW1/decomp, program "UU.exe" -- the real ARM
WinCE binary this whole port decompiles, found alongside the DOS
original "UW.EXE" in the same Ghidra project) to get fresh, unmodified
decompiles of FUN_00064384 (emit_anim_object_frames) and FUN_00081034
(scheduler_step_entry) straight from the binary, bypassing this
project's own possibly-already-hacked C source entirely.

Finding: the real door-open trigger's swing-magnitude line was always
`iVar8 = sign * (bVar4 >> 1 & 7)` -- reading bits 9-11 of the door
object's own word0 -- NOT quality (obj[3] & 0x3f) at all. Milestone
15's fix (substituting a fabricated `((quality>>3)!=0) ? 5 : 0`
boolean-times-fixed-magnitude value) replaced a CORRECT field read
with an incorrect one, based on a stale live trace taken before the
scheduler chain (milestone 16) was fixed -- at that point in the
investigation the real field genuinely did sit at a constant 0, but
that was a symptom of the scheduler being broken, not evidence the
field itself was wrong.

The real mechanism, confirmed by reading scheduler_step_entry's own
fresh decompile: doors' real loaded class-7 behavior flags (from
objects.dat, read into DAT_00250730) are 0x84 -- bit 2 set, bit 0 (the
"quality ramp toward a target" path milestone 16 verified and got
excited about) NOT set. Bit 2's branch (`uVar8 == 4` in
scheduler_step_entry) directly increments the SAME word0 bits 9-11 by
the elapsed-ticks parameter every tick, merged back via the same
`& 0xe00` / `& 0x1e00` masks emit_anim_object_frames reads through --
this is the real six-to-eight-step gradual sweep, and milestone 16's
scheduler fixes (all still correct and necessary) already made it run;
it just never got a chance to matter because emit_anim_object_frames
was discarding its result and substituting a fixed, oversized value
instead. (Quality really does just flip +8/-8 open/closed in one
atomic step, as milestone 16 found -- that part was right. It's simply
not what drives the visible swing angle.)

Reverted the swing-magnitude line to its real original form. Confirmed
live (UW_DEBUG_DOOR, demos/bug-open-door.txt): the field now genuinely steps
0 -> 1 -> 2 -> 3 -> 4 -> 5 across separate ticks (not jumping straight
to a fixed value), and a full split-screenshot replay shows the door
leaf swung open on its hinge at a moderate, correct-looking angle by
the end of the sequence (not the ~90-degree overshoot nor a barely-
cracked sliver). A mid-sequence screenshot still shows the door closed
despite the trace confirming the field had already advanced by then --
consistent with the already-documented, separate, not-yet-fixed
finding that this viewport only refreshes on discrete input events in
a scripted demo with zero further input, not a continuous per-frame
heartbeat; needs live interactive testing (real, continuously-moving
mouse input) to confirm the visual smoothness matches the now-
confirmed-correct underlying state.

Tooling note for future passes: the real ARM WinCE binary (UU.exe) is
already imported into the SAME Ghidra project as the DOS original
(UW.EXE) that other work this session referenced -- both live under
/Users/ccuddigan/Projects/UW1/decomp (UW.gpr), addressable via
analyzeHeadless with -process "UU.exe". Its own address space
(ARM:LE:32:v8, image base 0x00010000) matches every "// was
FUN_XXXXXXXX" comment throughout this file directly -- e.g.
emit_anim_object_frames's own address, 0x64384, is exactly where
FUN_00064384 lives in that project. This is a much higher-confidence
ground truth than re-deriving intent from this project's own C source
alone, and should be reached for earlier next time a HACK's exact
original behavior is in doubt.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (18): QA pass on milestone 17 -- fixed a real
regression from milestone 16, added a tunable for the hinge-pivot report,
and investigated (but did not resolve) the close-reopens-instead-of-
closing report in depth
═══════════════════════════════════════════════════════════════════════════
Live QA on milestone 17's swing-angle fix found three things: "door
swings open now" (confirmed working), "rotation origin is in the middle
of the leaf and not the hinge, so rotation looks off", and "trying to
close the door seems to put the door back in the opening state, not
closing state".

1. CONFIRMED REGRESSION, FIXED: milestone 16 made FUN_0007c708's
   `id == 0x1cf` branch a no-op, on the theory that 0x1cf was a
   transient "still mid the current scheduled animation" sentinel and
   a redundant re-trigger should do nothing. Checked every place that
   could plausibly reset an object's id away from 0x1cf once set
   (FUN_0007c4a8, scheduler_finish_entry's own tail, scheduler_despawn_entry)
   and found none -- it's a PERMANENT identity change on first use, not
   a transient flag. The real caller (try_combine_or_stow_object,
   `(*param_2 & 0xf) < 8 ? FUN_0007c580 : FUN_0007c708`) routes every
   use after the first through this exact branch via the object's own
   now-permanently-high low nibble. The no-op broke every subsequent
   open, not just the redundant-click case it targeted. Reverted to
   match the real disassembly exactly.

2. HINGE PIVOT (rotation origin in the middle, not the hinge): traced
   to an EARLIER session's own anchor fix (g_tune_wide_center/
   g_tune_edge_offset, both 128 = exact tile center), added to fix the
   door FRAME's wall-plane position -- confirmed correct for DFRAME
   (a symmetric, full-tile-wide, non-rotating object) but never
   verified for the LEAF, which silently shares the exact same anchor
   (DAT_0023b904/920 are globals, set once by the frame's own call and
   simply still in place when the leaf's separate call runs moments
   later). DOOR.E's own local mesh isn't symmetric around its origin
   (POINTS span local X 0-128, not centered), so build_euler_rotation_matrix
   rotating around that origin, placed at the frame's centered anchor,
   pivots roughly mid-leaf instead of at the hinge edge. Added a
   SEPARATE, live-tunable `g_tune_leaf_hinge_offset` (starts at 0.0,
   zero behavior change until adjusted) plus its own object-tuner panel
   row, gated to catalog_u==0xe/0xf, applied as an offset along the
   same "wide" axis wide_center itself offsets. Not yet dialed in to a
   confirmed-correct value -- needs the same live nudge-and-watch
   process wide_center/edge_offset themselves were tuned with
   (backtick to open the panel while a real door is swinging).

3. CLOSE REOPENS INSTEAD OF CLOSING: investigated in real depth against
   fresh disassembly but NOT resolved. Confirmed live that the actual
   dispatcher for a plain "use" click is NOT the quality-based one at
   use_object_on_target (`quality < 8 ? FUN_0007c708 : FUN_0007c580`)
   but a DIFFERENT one in try_combine_or_stow_object, keyed on the
   object's own word0 low nibble instead (`(*param_2 & 0xf) < 8 ?
   FUN_0007c580 : FUN_0007c708`) -- FUN_0007c580 fires on a door's
   first-ever use (word0 low nibble starts at 0), FUN_0007c708 fires on
   literally every use after that, forever, since word0's low nibble
   becomes part of the permanent 0x1cf identity (finding 1 above) and
   never resets. FUN_0007c708's own `id==0x1cf` branch (now correctly
   restored) only ever ADDS 8 to quality's low nibble, guarded to
   no-op once quality is already >= 8 -- meaning, via THIS dispatcher,
   a door that's already open has no path back to a closing action at
   all; every subsequent click just no-ops. Whether this is a genuine
   gap in this port (a missing/miswired third code path), a
   misidentified caller (there may be a different, not-yet-found
   dispatcher for plain reuse that this session never located), or
   actually matches original 1992 behavior (doors closing via a
   different mechanism entirely, e.g. proximity/auto-close, not a
   second click) is still an open question. Needs either a fresh
   disassembly pass specifically tracing try_combine_or_stow_object's
   own caller(s) and every other site that calls FUN_0007c580/
   FUN_0007c708, or real knowledge of how doors close in the original
   game, to resolve with confidence rather than more guessing.

Tooling note: this session's disassembly work used
/private/tmp/ghidra_scripts/DumpDoorSwing.java, DumpSchedulerFns.java,
and DumpDoorDir.java (decompile+disassemble a list of hardcoded
addresses against the UU.exe program via analyzeHeadless) -- kept in
place for a future pass on the close-dispatch question, just change
the address list.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (19): fixed the object tuner's per-catalog field
visibility bug, and root-caused + fixed a real crash using a pull chain
(demos/bug-pull-chain-crash.txt) -- three stacked pointer-truncation bugs
═══════════════════════════════════════════════════════════════════════════
Two QA reports: "only able to tune leaf_hinge_offset on doors of type
14, not 1" (a usability bug in milestone 18's own new tunable), and "using
a pull chain to open a door causes a crash" (a real, reproducible
EXC_BAD_ACCESS, repro saved as demos/bug-pull-chain-crash.txt).

TUNER VISIBILITY: the object-tuner panel's field list resets on every
single emit_catalog_object call within a frame (not once per door), so
with the frame (catalog_u==1) and leaf (catalog_u==0xe/0xf) drawing in
the same frame plus whatever else is in the scene, whichever catalog
happened to draw LAST determined which fields were visible -- leaf_
hinge_offset (gated to catalog_u==0xe/0xf only) was invisible whenever
catalog 1 drew last. Fixed by showing all three door-family tunables
(wide_center, edge_offset, leaf_hinge_offset) together whenever ANY
door catalog (1, 0xe, or 0xf) was the last one drawn, instead of
splitting them by exact catalog.

PULL-CHAIN CRASH: reproduced immediately via lldb against the saved
repro. Root-caused through THREE separate, stacked pointer-truncation
bugs along the same call chain (use_object_on_target ->
FUN_0007c2ec -> FUN_0007cdbc -> FUN_0007d074 -> FUN_0007d0b0's own
"case 8" -> object_list_insert_head), each one only surfacing once the
previous one was fixed and execution got one step further:

1. FUN_0007d074's own param_2/param_3 were both declared `undefined4`
   (32-bit) despite being real `ushort *` pointers at every call site
   (confirmed via FUN_0007cdbc's own matching parameter types) -- and
   DAT_0024cff0, which param_2 gets stored into, had the exact same
   bug (also dereferenced directly elsewhere in the same function).
   Classic pointer truncation on this 64-bit host; retyped all three.

2. Fixed with (1), the crash moved one call deeper into
   FUN_0007d0b0's own "case 8": a bare `object_list_insert_head(local_34);`
   -- a dropped second argument (every other call site of this
   function passes exactly two) -- with puVar10 (an object slot this
   same block had just allocated and populated) the obvious missing
   argument.

3. Fixed with (2), the crash moved again, this time into
   object_list_insert_head itself, with an invalid FIRST argument this
   time. Traced to `iVar16`/`iVar11` -- both plain `int` locals in
   FUN_0007d0b0, but reused within this same "case 8" to hold
   FUN_000537d0's real `ushort *` return value (already flagged, but
   left unfixed, by an EARLIER session's own comment: "a separate,
   not-yet-fixed truncation bug ... out of scope for this
   tilemap_lookup-focused pass"). iVar16/iVar11 are genuinely reused
   for unrelated small integers in every OTHER case of this switch (and
   iVar11 even earlier within this same case), so a blanket retype
   wasn't safe -- added two dedicated, correctly-typed locals
   (_case8_p1/_case8_p2) scoped to just this case's own pointer uses
   instead, including two further uses of the same truncated value
   (FUN_0007c580/FUN_0007c814 calls) the original fixer's comment
   hadn't traced out to.

Confirmed live: demos/bug-pull-chain-crash.txt no longer crashes (reaches
"end of input, exiting" cleanly) after all three fixes landed together
-- fixing any one or two in isolation only moved the crash one call
frame deeper, never resolved it.

run-regressions.sh: 6/6 clean.

═══════════════════════════════════════════════════════════════════════════
MILESTONE 2026-09-28 (20): resolved the "close via chain works, close via
direct click doesn't" mystery -- confirmed via fresh disassembly that
direct-click's one-way behavior is GENUINE ORIGINAL GAME DESIGN, not a
port bug. Also fixed one more independent pointer-truncation bug found
along the way
═══════════════════════════════════════════════════════════════════════════
QA follow-up: "Using the pull chain works to open the door / Using the
pull chain again closes the door properly / Using the door when open
does not close the door, but shows the end part of the opening
animation... Interesting - closing the door works fine via the pull
chain use chain, but not using the door directly. Look into that."

Traced the two interaction paths (which milestone 18 had already
partly identified) all the way to source, and this time verified BOTH
against a fresh, unmodified Ghidra decompile of the real UU.exe binary
rather than reasoning from this project's own (possibly already
HACK-adjusted) C source:

- Direct door click routes through FUN_0007bcdc, gated on the door's
  own word0 low nibble (`(*param_2 & 0xf) < 8 ? [try combination, then
  FUN_0007c580] : FUN_0007c708`). Confirmed byte-for-byte identical
  against the real binary's own FUN_0007bcdc -- this project's C source
  is completely faithful here, not a decompilation error. Since word0's
  low nibble becomes part of the door's permanent "activated" identity
  on first use (see milestone 18's own finding) and never resets, this
  path's FUN_0007c580 (the only branch that can actually close a door)
  is only ever reachable on a door's FIRST-EVER interaction; every
  later click permanently routes to FUN_0007c708 (open), which no-ops
  once already open. Confirmed the SAME in FUN_0007c814 (the "toggle"
  action available to level scripts, `sVar3==2` in
  babl_builtin_gronk_door) -- it checks the exact same word0 field, so
  it would have the identical one-way problem if anything actually used
  it that way.

- The pull chain does NOT go through either of those word0-gated
  paths for its own toggling. babl_builtin_gronk_door (the real
  script-triggered door action, called from level-script effects like
  a chain's own "use" behavior) dispatches on `sVar3` -- a value read
  directly from the CHAIN's own script parameter -- calling
  FUN_0007c580 (close) or FUN_0007c708 (open) EXPLICITLY, not via
  FUN_0007c814's word0-based toggle. The chain's own alternating
  behavior comes from whatever independently toggles which explicit
  action (sVar3==0 vs sVar3==1) the chain's script requests each pull
  -- outside the scope of this investigation, but structurally
  separate from and unaffected by the door's own permanently-stuck
  word0 nibble.

CONCLUSION: this is genuine original 1992 engine design, not a bug
introduced by this port. A plain click can only ever open a door once
via this path (any door state after that is fixed); closing a door is
by design something switches/levers/chains do via their own,
independently-tracked toggle state, not something re-clicking the door
itself was ever supposed to do. Not "fixed" -- changing FUN_0007bcdc's
dispatch condition to use quality instead of word0 (which WOULD make
direct clicks toggle correctly) would be a deliberate GAMEPLAY CHANGE
diverging from the authentic original, not a bug fix, and wasn't made.

Found and fixed one more, independent bug while tracing this:
babl_builtin_gronk_door's own `iVar6` -- declared plain `int`,
truncating FUN_000537d0's real `ushort *` return on this 64-bit host,
the exact same bug class as dozens of others already fixed this
session, just never yet hit hard enough to visibly misbehave (per the
function's own pre-existing comment: "never exercised deep enough to
crash/misbehave visibly yet"). Retyped to `ushort *`.

run-regressions.sh: 6/6 clean.
